diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4cd737844..123c1f2b4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -542,6 +542,7 @@ jobs: - name: Configure run: | cmake --preset ${{ matrix.preset }} \ + -DMORPH_LINK_JOBS=1 \ -DMORPH_BUILD_NET=ON \ -DMORPH_BUILD_TUI=ON \ -DMORPH_BUILD_OFFLINE_SQLITE=ON \ @@ -549,8 +550,23 @@ jobs: -DCMAKE_CXX_COMPILER=clang++-${{ env.CLANG_VERSION }} \ $MORPH_PACE_AUTO_INSTALL_FLAG + # Sanitizer-instrumented compiles and links of the heaviest test files go past the runner's 16 GB and 3 GB of + # swap at one job per CPU, and the runner is lost with no compiler error. Extra swap costs nothing unless it + # is needed; the Build step prints the swap used. A self-hosted runner sizes its own memory. + - name: Add swap for the build's heaviest compiles + if: runner.environment == 'github-hosted' + run: | + sudo fallocate -l 12G /mnt/build-swap + sudo chmod 600 /mnt/build-swap + sudo mkswap /mnt/build-swap + sudo swapon /mnt/build-swap + free -m + - name: Build - run: cmake --build --preset ${{ matrix.preset }} --parallel "$(nproc)" + run: | + cmake --build --preset ${{ matrix.preset }} --parallel "$(nproc)" + free -m + grep -E '^(pswpin|pswpout) ' /proc/vmstat # A sanitizer job whose binaries are not instrumented runs the whole suite # and learns nothing, while reporting success. Asserting this over one @@ -780,6 +796,7 @@ jobs: - name: Configure run: | cmake --preset clang-coverage \ + -DMORPH_LINK_JOBS=1 \ -DMORPH_BUILD_NET=ON \ -DMORPH_BUILD_OFFLINE_SQLITE=ON \ -DMORPH_BUILD_QT=ON \ @@ -790,6 +807,17 @@ jobs: -DCMAKE_C_COMPILER_LAUNCHER=sccache \ -DCMAKE_CXX_COMPILER_LAUNCHER=sccache + # The instrumented link of morph_tests alone peaks near 13.5 GB, so Configure allows one link at a time + # (MORPH_LINK_JOBS=1), and the compiles that run beside it need more than the runner's 16 GB and 3 GB of swap. + # Extra swap costs nothing unless it is needed; the Build step prints the swap used. + - name: Add swap for the build's heaviest compiles + run: | + sudo fallocate -l 12G /mnt/build-swap + sudo chmod 600 /mnt/build-swap + sudo mkswap /mnt/build-swap + sudo swapon /mnt/build-swap + free -m + # QT_QPA_PLATFORM=offscreen here too, not just on Test below: Catch2's # catch_discover_tests() runs each Qt-linked test binary once at BUILD # time to enumerate its cases, which can abort on this headless runner @@ -800,15 +828,22 @@ jobs: - name: Build env: QT_QPA_PLATFORM: offscreen - run: cmake --build --preset clang-coverage --parallel "$(nproc)" + run: | + cmake --build --preset clang-coverage --parallel "$(nproc)" + free -m + grep -E '^(pswpin|pswpout) ' /proc/vmstat - name: Test env: # Required for the ladder tests, which open real Qt widgets/sockets # on a runner with no display. QT_QPA_PLATFORM: offscreen + # %4m, not %p: each test process writes a profile the size of its + # binary's counters, and one file per process over every Catch2 case + # fills the runner's disk. The merge pool keeps at most four files per + # binary and merges into them, under a lock, as processes exit. run: | - LLVM_PROFILE_FILE="build/clang-coverage/%p.profraw" ctest --preset clang-coverage --parallel "$(nproc)" -LE stress + LLVM_PROFILE_FILE="build/clang-coverage/%4m.profraw" ctest --preset clang-coverage --parallel "$(nproc)" -LE stress # Deliberately left on the implicit `success()`, unlike the three test # steps that carry `!cancelled()` (ladder-tests' scenario corpus, @@ -905,6 +940,7 @@ jobs: - name: Configure (gcc-debug with MORPH_BUILD_QT=ON) run: | cmake --preset gcc-debug \ + -DMORPH_LINK_JOBS=1 \ -DMORPH_BUILD_QT=ON \ -DCMAKE_C_COMPILER_LAUNCHER=sccache \ -DCMAKE_CXX_COMPILER_LAUNCHER=sccache @@ -1203,6 +1239,7 @@ jobs: if: steps.filter.outputs.run == 'true' run: | cmake --preset gcc-debug \ + -DMORPH_LINK_JOBS=1 \ -DMORPH_BUILD_QT=ON \ -DMORPH_BUILD_QT_QUICK=ON \ -DMORPH_BUILD_LADDER=ON \ @@ -1210,6 +1247,18 @@ jobs: -DMORPH_BUILD_BANK_EXAMPLE=ON \ $MORPH_PACE_AUTO_INSTALL_FLAG + # The build ends by linking the largest test binaries, debug information and all, several at once; past the + # runner's 16 GB and 3 GB of swap that ends in exit 143 with no compiler error. Extra swap costs nothing unless + # it is needed; the Build step prints the swap used. A self-hosted runner sizes its own memory. + - name: Add swap for the build's heaviest links + if: steps.filter.outputs.run == 'true' && runner.environment == 'github-hosted' + run: | + sudo fallocate -l 12G /mnt/build-swap + sudo chmod 600 /mnt/build-swap + sudo mkswap /mnt/build-swap + sudo swapon /mnt/build-swap + free -m + # QT_QPA_PLATFORM=offscreen here too, not just on Test below: Catch2's # catch_discover_tests() runs each Qt-linked test binary once at BUILD # time to enumerate its cases, which aborts on a headless runner (no X @@ -1235,6 +1284,8 @@ jobs: # this job cannot cover this half -- it reads the source tree, not the # configure. cmake --build --preset gcc-debug --target ladder_bank_server --parallel "$(nproc)" + free -m + grep -E '^(pswpin|pswpout) ' /proc/vmstat # ── moc output that climbs out of the build tree ───────────────── # Same gate as linux-qt above, and for the same reason -- see its @@ -1751,6 +1802,29 @@ jobs: path: clang-format-report.txt if-no-files-found: ignore + # ── Table tests in WebAssembly, under Node ──────────────────────────── + # The table module is header-only and builds without Qt: its tests run + # single-threaded under Node, so the count gates and the fixture's pinned + # digest are checked on a third standard library and a 32-bit target. The + # cases that need threads are tagged [threads] and left out. + table-wasm: + name: Table tests (WebAssembly, Node) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install build tools + run: | + sudo apt-get update -q + sudo apt-get install -y ninja-build + - uses: mymindstorm/setup-emsdk@v14 + with: { version: 4.0.7 } + - name: Configure + run: emcmake cmake -S . -B build-wasm -G Ninja -DCMAKE_BUILD_TYPE=Release -DMORPH_BUILD_TESTS=ON -DMORPH_BUILD_EXAMPLES=OFF + - name: Build + run: cmake --build build-wasm --target morph_table_tests + - name: Run + run: node build-wasm/tests/morph_table_tests.js "~[threads]" + # ── actionlint (the workflows themselves) ───────────────────────────── # The workflows are thousands of lines of YAML and embedded bash that no # other job checks. actionlint validates expressions, job references and diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a4fbb30c..7b8e1b5eb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -493,6 +493,43 @@ add_library(morph ${_morph_library_type} src/ui/document.cpp src/ui/expression.cpp src/ui/interpreter.cpp + src/ui/interpreter_elements.cpp + src/ui/interpreter_components.cpp + src/ui/interpreter_lowering.cpp + src/ui/interpreter_forms.cpp + src/ui/interpreter_fixed_grid.cpp + src/ui/interpreter_collections.cpp + src/ui/interpreter_rows.cpp + src/ui/interpreter_table_actions.cpp + src/ui/interpreter_table_layout.cpp + src/ui/interpreter_table_model.cpp + src/ui/interpreter_charts.cpp + src/ui/interpreter_mount.cpp + src/ui/grid_1.cpp + src/ui/grid_2.cpp + src/ui/grid_3.cpp + src/ui/mount_1.cpp + src/ui/mount_2.cpp + src/ui/mount_3.cpp + src/ui/table_config.cpp + src/ui/table_dialogs.cpp + src/ui/table_filter_menu.cpp + src/ui/table_rows_1.cpp + src/ui/table_rows_2.cpp + src/ui/table_state.cpp + src/ui/table_state_model.cpp + src/ui/table_views.cpp + src/forms/field_control.cpp + src/forms/form_session.cpp + src/table/description.cpp + src/table/edits.cpp + src/table/level_cache.cpp + src/table/query.cpp + src/table/row_selection.cpp + src/table/state_store.cpp + src/table/view_cache.cpp + src/ui/cell_format.cpp + src/ui/form_rows.cpp src/ui/library.cpp src/ui/service.cpp src/ui/tour_checks.cpp @@ -637,6 +674,7 @@ target_sources(morph include/morph/offline/file_offline_queue.hpp include/morph/offline/replay_ledger.hpp include/morph/session/session.hpp + include/morph/forms/derive.hpp include/morph/forms/field_errors.hpp include/morph/forms/forms.hpp include/morph/forms/blank_as.hpp @@ -659,6 +697,15 @@ target_sources(morph include/morph/ui/frontend.hpp include/morph/ui/value.hpp include/morph/ui/locale_table.hpp + include/morph/ui/stretch_columns.hpp + include/morph/ui/table_config.hpp + include/morph/ui/table_dialogs.hpp + include/morph/ui/table_filter_menu.hpp + include/morph/ui/measure.hpp + include/morph/ui/table_rows.hpp + include/morph/ui/form_rows.hpp + include/morph/ui/grid.hpp + include/morph/ui/cell_format.hpp include/morph/ui/page_layout.hpp include/morph/ui/message.hpp include/morph/ui/expression.hpp @@ -726,6 +773,9 @@ target_sources(morph include/morph/ui/chat/transcriber.hpp include/morph/ui/preferences.hpp include/morph/ui/preference_sync.hpp + include/morph/ui/table_state_model.hpp + include/morph/ui/table_state.hpp + include/morph/ui/table_views.hpp include/morph/ui/host_vocabulary.hpp include/morph/ui/catalogue.hpp include/morph/ui/chart_scale.hpp @@ -764,6 +814,7 @@ target_sources(morph include/morph/forms/engine/overrides.hpp include/morph/forms/engine/field_layout.hpp include/morph/forms/engine/form_view.hpp + include/morph/forms/engine/field_control.hpp include/morph/forms/engine/collection.hpp include/morph/forms/engine/wizard.hpp include/morph/forms/engine/collection_view.hpp @@ -773,10 +824,17 @@ target_sources(morph include/morph/table/filter.hpp include/morph/table/view_change.hpp include/morph/table/engine.hpp - include/morph/table/plan_conformance.hpp include/morph/table/query.hpp + include/morph/table/record_name.hpp + include/morph/table/row_selection.hpp + include/morph/table/runtime.hpp + include/morph/table/bands.hpp + include/morph/table/description.hpp + include/morph/table/level_cache.hpp + include/morph/table/view_cache.hpp include/morph/table/selection.hpp include/morph/table/edits.hpp + include/morph/table/state_store.hpp ) # The detail/ headers that public headers include. They are not public surface @@ -1336,6 +1394,11 @@ if(MORPH_BUILD_QT) add_subdirectory(tests/qt_quick) endif() + # The browser's frontend baseline: one Qt for WebAssembly executable, run by hand under a headless browser. + if(EMSCRIPTEN AND MORPH_BUILD_QT_QUICK AND MORPH_BUILD_TESTS) + add_subdirectory(tests/qt_quick/wasm) + endif() + # Qt for WebAssembly has no TLS sockets: a browser's WebSocket carries the TLS. if(MORPH_BUILD_EXAMPLES AND NOT EMSCRIPTEN) add_subdirectory(examples/qt_tls_client) diff --git a/codecov.yml b/codecov.yml index d09d7aed5..68733cd0e 100644 --- a/codecov.yml +++ b/codecov.yml @@ -171,6 +171,8 @@ component_management: paths: - include/morph/** - src/ui/** + - src/table/** + - src/forms/** statuses: - type: project target: 97% @@ -257,6 +259,7 @@ component_management: name: "morph forms (include/morph/forms)" paths: - include/morph/forms/** + - src/forms/** statuses: - type: project target: 97% diff --git a/docs/spec/README.md b/docs/spec/README.md index 5ddc412ab..e7b39c9ea 100644 --- a/docs/spec/README.md +++ b/docs/spec/README.md @@ -135,8 +135,11 @@ rules, exact values and reactive session, headless · [`table/engine.md`](table/engine.md) — sorting, filtering and view mapping for a table, on and off the owner thread, and `table::apply` for a server · -[`table/database_pages.md`](table/database_pages.md) — paging a table that -lives in a database: `planQuery`, `Page::totalKind` and the conformance helper +[`table/table.md`](table/table.md) — the one table every surface +uses: a table as a description any model can offer, the single pipeline, +unloaded cells and levels, the caches, configuration, acting on rows, and the budgets · +[`table/editing.md`](table/editing.md) — typing into a table: a grid of a form, cells of a model's table, the +cell editor, walking, paste, header bands, spans, summary rows and fixed grids **Reactive state and control** [`reactive/signals.md`](reactive/signals.md) · diff --git a/docs/spec/core/backend.md b/docs/spec/core/backend.md index 827c47c31..7f6b5d14b 100644 --- a/docs/spec/core/backend.md +++ b/docs/spec/core/backend.md @@ -791,6 +791,7 @@ changes it. | `coalesceWindow` | `50 ms` | How long a connection's changes are merged before one `changes` event is sent; see [Coalescing](#coalescing). | | `clock` | the system clock | The server's "now", read by [time-derived fan-out](#time-derived-fan-out). A test supplies one it advances by hand. | | `clockRecheck` | `1 s` | The longest the server sleeps before reading `clock` again; see [time-derived fan-out](#time-derived-fan-out). Not positive is refused by the constructor. | +| `tableWork` | null (the worker pool) | Where a table's reply is built ([table.md, "A model's tables"](../table/table.md#a-models-tables)): a `Table.` action runs its table's function on the model's strand and pins the source's snapshot there, then sorts, filters and pages on this executor, and resumes on the strand with the page. The server installs a `table::TableRuntimeScope` naming it around every dispatch, beside the session's. | ```cpp using LogProvider = std::function( @@ -1231,6 +1232,33 @@ what it changed. Every executing message takes this path: the `execute` kind, offline replays (which arrive as executes), and anything else that dispatches through `dispatchExecute`. +- **A table is one more record.** A `Table.` action's reply is built on + `ServerConfig::tableWork`, but its fan-out is the record machinery's: the + table's record is watched, admitted and re-authorised as any record is, and + an action whose result holds a `table::ChangedRows` names that table's + rows as `updates` keys (see [registry.md, + `BRIDGE_REGISTER_TABLE`](registry.md#bridge_register_tablem-id-fn-)). + The reply reads its view from the server's one view cache (sized by + `ServerConfig::views`, counted by `RemoteServer::viewStats()`), which + `RemoteServer` puts in the `table::TableRuntime` it installs around a + dispatch beside `tableWork`; see [table.md, "The view + cache"](../table/table.md#the-view-cache). +- **Change observers come first.** `RemoteServer::attach(observer)` registers + an `effects::IChangeObserver`, such as a table's level cache, and hands it + its announce sink (`effects::AnnounceSink`, holding the server weakly). On + the server strand, `fanOut` calls each observer's `changed(changes)` before + it finds a recipient, so a client that refetches because of the event reads + what the observer left. An observer only removes: it neither loads, waits + nor calls out. One that throws is logged and the fan-out goes on. +- **`announce` is a fan-out with no caller and no observers.** + `RemoteServer::announce(record, keys)` reports a change no execute made, from + any thread: an unregistered record is refused (`"unregistered record: + "`) and nothing is sent; otherwise the change is built as an execute's + is (the record's derived records whole, more than `effects::kMaxChangeKeys` + keys a whole-type change), posted to the server strand, and fanned out as a + time fact's is, with no caller, so a `privateKeys` record reaches every + watcher without keys. The observers are not told: an arrival never + invalidates the cache that announced it. - **The model strand derives.** `finishRemote`, on success only and before the reply, calls `effects::deriveChanges(actionType, result, ranOn)`. `ranOn` is the instance the action ran on: its model type, its id, and, for a keyed @@ -2522,6 +2550,8 @@ server: each call is a loop task, so the loop serialises them. | `coalesceWindow` | `std::chrono::milliseconds`, default `50 ms`: how long a connection's changes are merged before one `changes` event is sent; zero sends each fan-out at once; negative throws `std::invalid_argument`. See [Coalescing](#coalescing). | | `clock` | `std::function`, default empty (the system clock): the server's "now" for [time-derived fan-out](#time-derived-fan-out). | | `clockRecheck` | `std::chrono::milliseconds`, default `1 s`: the longest sleep before `clock` is read again; not positive throws `std::invalid_argument`. | +| `tableWork` | `std::shared_ptr`, default null (the server's worker pool): where a `Table.` reply is built, off the model's strand. | +| `views` | `morph::table::ViewCacheOptions`, default `maxBytes` 64 MiB and no `onCompute`: the bound of the server's one view cache across its tables, and a hook called on the thread that computes a view. | ### `SimulatedRemoteBackend` diff --git a/docs/spec/core/registry.md b/docs/spec/core/registry.md index 420e5b1c1..6ee283741 100644 --- a/docs/spec/core/registry.md +++ b/docs/spec/core/registry.md @@ -30,6 +30,7 @@ without knowing their concrete types. - [Registration macros](#registration-macros) - [`BRIDGE_REGISTER_MODEL(M, NAME)`](#bridge_register_modelm-name) - [`BRIDGE_REGISTER_ACTION(M, A, NAME, ...)`](#bridge_register_actionm-a-name-) + - [`BRIDGE_REGISTER_TABLE(M, ID, FN, ...)`](#bridge_register_tablem-id-fn-) - [Moving a registrar out of the header](#moving-a-registrar-out-of-the-header) - [`BRIDGE_REGISTER_VALIDATOR(A, FN)`](#bridge_register_validatora-fn) - [`MORPH_CLIENT_ONLY` — suppressing model-owning registrars](#morph_client_only--suppressing-model-owning-registrars) @@ -249,6 +250,19 @@ returns the empty string for it, entries are recorded unstamped, and replay does no fingerprint check on them. Opting in is a matter of defining the member. +**An action may run itself.** Every dispatch path (the dispatcher's runner and +its Task runner, `LocalBackend`'s ordinary and Task ops) calls the handler +through `detail::invokeExecute(model, action)`, which is +`Action::invoke(model, action)` when the action declares a static +`template invoke(Model&, Action&)`, and `model.execute(action)` +otherwise. Whether the handler is a Task is read from that call's type too. It +is how an action the framework defines for a model, such as a table's +`QueryTable` and `DescribeTable` (see +[`BRIDGE_REGISTER_TABLE`](#bridge_register_tablem-id-fn-)), carries its handler +with it, so the model declares no `execute` for it. Such an action is +registered with its result named, since there is no `M::execute(A)` to deduce +it from. + ### `payload_schema.hpp` — the payload fingerprint ```cpp @@ -631,7 +645,9 @@ class ActionDispatcher { - `evaluate` runs the gates `dispatch` runs, as checks rather than refusals, and never `Model::execute`: it decodes the body, reconciles `Quantity` - precision, recomputes the computed fields, and returns an `Evaluation` — the + precision, clears the derived members (`forms::clearDerived`), recomputes the + computed fields — those of each nested aggregate (a `std::vector` element, + a nested struct, either inside an engaged `std::optional`) before the action's — and returns an `Evaluation` — the recomputed body (`ActionTraits::toJson`), `forms::fieldErrors` of it, and `ready`, whether `dispatch` would execute it (every `Quantity` within its unit's bounds, and `ActionValidator::ready`). No model instance, @@ -645,8 +661,13 @@ class ActionDispatcher { `Quantity` fields to their declared precision, rejects any `Quantity` field outside its unit's declared bounds (`morph::forms::enforceQuantityBounds`, throwing `QuantityDecodeError`; a no-op for actions with no `Quantity` - members or whose units declare no `bounds()`), overwrites any declared - computed fields from their inputs (`morph::forms::recomputeAll`, + members or whose units declare no `bounds()`), value-initialises every + derived member (`morph::forms::clearDerived`, `forms/derive.hpp`: a member its + type's field metadata marks `derived()`, in the action and in every nested + aggregate of it — the model's to set, so a value a client sent is + never the one kept), overwrites any declared + computed fields from their inputs (`morph::forms::recomputeAll`, the nested + aggregates' own first, [forms.md](../forms/forms.md) — a no-op for actions with no `computedFields`; runs after precision reconciliation and bounds enforcement and before the validator check, so the validator sees the @@ -1044,6 +1065,89 @@ A client-side alternative, `BRIDGE_REGISTER_ACTION_FOR_CLIENT`, avoids the `MORPH_CLIENT_ONLY`](#bridge_register_action_for_client--a-header-seam-for-morph_client_only) below. +### `BRIDGE_REGISTER_TABLE(M, ID, FN, ...)` + +Registers table `ID` of model `M` ([table.md, "A model's +tables"](../table/table.md#a-models-tables)). `ID` is a string literal; `FN` is +`&M::fn`, a `table::ServedTable (M::*)(table::TableContext const&)`, or +`morph::table::typed(&M::fn)` for a function returning +`std::shared_ptr const>`. The options after `FN` are the +record's: `morph::table::rowScoped` and `morph::table::derivedFrom`. + +```cpp +BRIDGE_REGISTER_MODEL(lims::DesignModel, "DesignModel") +BRIDGE_REGISTER_TABLE(lims::DesignModel, "designs", &lims::DesignModel::designs) +BRIDGE_REGISTER_TABLE(lims::DesignModel, "recipes", &lims::DesignModel::recipes, morph::table::rowScoped) +BRIDGE_REGISTER_TABLE(lims::SampleModel, "samples", morph::table::typed(&lims::SampleModel::sampleRows)) +``` + +It requires `BRIDGE_REGISTER_MODEL(M, ...)` before it, and +`` and `` in the translation +unit. It emits: + +- **`table::TableTraits`**, where `KEY` is the member function: `FN` itself, + or `FN.function` for a typed table. It holds `model`, `row` (`void`, or the + typed table's `Row`), `registered = true`, `id` and `serve = FN`. Everything + that names a table in C++ is keyed on `KEY`, so `table::TableOf<&M::fn>` (the + table's record type), `table::ChangedRows<&M::fn>` and + `effects::updatesTable<&M::fn>` / `changesTable<&M::fn>` name a typed table as + they name a plain one. `TableOf` does not compile for a function no + registration names. Every translation unit that names a table's `TableOf` or + `ChangedRows` must see its registration, so the macro belongs in the model's + header. +- **Two actions**, registered as an action with an explicit result is: + `"Table." ID`, the action type `table::QueryTable` (its JSON is the + `TableQuery`'s; result `GenericPage`), and `"Table." ID ".describe"`, the action + type `table::DescribeTable` (result `TableDescription`, built by + `table::servedDescription`: the description with `capabilities.maxSortKeys` + carried from the served table's `limits.maxSortKeys`, then its revision; a + bound of 0 or above `table::kMaxSortKeysBound` (32) refuses the request with + `table.sourceContract`, as it refuses every query to the table, and a page's + `revision` is that description's). Both run + themselves through `invoke` (see [`ActionTraits`](#actiontraitsaction)), + and both are `Loggable::No`: they read, and a page fetch is not written to an + action log. +- **The table's record**, through `record::detail::registerTableRecordOnce`: a + `RecordInfo` for `TableOf` named `::typeId()>.` `ID` + (`DesignModel.designs`), keyed by `key`, with `table = true`. `rowScoped` sets + `privateKeys`; `derivedFrom<…>` sets `derivedFrom`. A table's record keeps its + key when it is derived: a source's change reaches it as a whole-record change, + as for any derived record, and its own actions name its rows. +- **The opaque holding.** `"Table." ID`'s result slots gain + `ResultSlot{typeid(TableOf), "", .opaque = true}` + (`detail::registerOpaqueResultOnce`), which resolution turns into + `ActionRecord{.record, .keyField, .paths = {}, .opaque = true}`. A page holds + parallel `keys` and `rows` arrays, not objects with a key member, so the + action holds the record at no path: it holds it for watch admission, and no + reader looks for its rows in the value. An opaque slot neither hides a path + nor is hidden by one. + +The record and the holding are suppressed under `MORPH_CLIENT_ONLY`, like every +registrar that records facts only a process hosting models serves. + +**`ChangedRows` in a result.** The result walk (see [Action result +slots](#action-result-slots)) reports a type with a `heldRecord` and a +`heldMember()` at that member as well as at its own path: +`table::ChangedRows` is reported as `TableOf` at `.rows`, so an +action returning one, or a struct with one member per table, has its changed +keys collected for `updatesTable` as any record's are. An +`updatesTable` on an action whose result has no `ChangedRows` is refused +when the registries resolve. + +**A table id is unique in the process**, not only in its model. The action ids +carry the id and no model, and the effects registries are keyed by action id: a +second action type under `"Table." ID` is listed in `actionResultConflicts()` +and refused when the registries resolve, with "action `Table.` is +registered by two action types; give each its own id", which fails every +effects lookup of the process. `QueryTable` is keyed on the function, not on the +id text, so two models' tables `"rows"` are two action types and the conflict is +seen rather than one table answering with the other's rows. + +**Admission.** A principal may watch a table's record when it may run any +action holding it: the table's own `Table.`, or an action whose result holds +its `ChangedRows` (see `RemoteServer::mayWatchRecord`). Refusing a principal a +table therefore means refusing it all of them. + ### Moving a registrar out of the header `BRIDGE_REGISTER_MODEL`/`BRIDGE_REGISTER_ACTION`'s registrar initialiser is @@ -1459,6 +1563,7 @@ correctly under `MORPH_CLIENT_ONLY`. | `BRIDGE_REGISTER_MODEL_SOURCE` | `(M)` | Static-init factory registration for a `M` already declared via `BRIDGE_DECLARE_MODEL`. Reads `NAME` back off `ModelTraits::typeId()`. | | `BRIDGE_DECLARE_ACTION` | `(M, A, NAME, ...)` | `ActionTraits` specialisation + a link-time canary requiring `BRIDGE_REGISTER_ACTION_SOURCE(M, A)` somewhere in the link. Optional 4th arg: `Loggable`. No registration. | | `BRIDGE_REGISTER_ACTION_SOURCE` | `(M, A)` | Static-init dispatcher, result-slot and executor registration for an `A` already declared via `BRIDGE_DECLARE_ACTION`. Reads `NAME` back off `ActionTraits::typeId()`. | +| `BRIDGE_REGISTER_TABLE` | `(M, ID, FN, ...)` | `table::TableTraits<&M::fn>`, the actions `Table.` and `Table..describe` (both `Loggable::No`), the table's record `.` and the action's opaque holding of it. Options: `table::rowScoped`, `table::derivedFrom<…>`. See [`BRIDGE_REGISTER_TABLE`](#bridge_register_tablem-id-fn-). | | `BRIDGE_REGISTER_VALIDATOR` | `(A, FN)` | `ActionValidator` specialisation + custom predicate. | ### Detail helpers @@ -1692,6 +1797,13 @@ read through `detail::recordRegistry()`. `localOp`, which enforces the same `ValidationError` gate as this spec's `ActionDispatcher::registerAction` for the local execution path and performs the same computed-field recompute (`morph::forms::recomputeAll`) for it. +- **Derive actions.** A form's derive action is an ordinary action of the + form's model whose input derives from `forms::DeriveOf` (its JSON + `{"body": }`, through the in-class glaze + meta the deriving type inherits) and whose result is `forms::Derived` + (`{"values": [{"path": "specimens[3].limit", "value": …}]}`). The application + registers it as `Loggable::No` with no effects, so a derive call is a read + ([../table/editing.md](../table/editing.md#derived-values)). - **[forms.md](../forms/forms.md)** — `allRequiredEngaged`; the closed cross-field rule vocabulary (`allRulesSatisfied`, `x-rules`) that composes into `validate()` alongside it; and `computed`/`computeList`/`recomputeAll`, @@ -1737,10 +1849,23 @@ handler contributes `R`. id once in `detail::actionResultConflicts()`. Matching refuses a listed id, since which result a cached query holds would otherwise depend on link order. Recording rather than throwing keeps the registrar `noexcept`. -- **A slot** is `{std::type_index type, std::string path}`. Every visited - aggregate is one, the result itself at path `""`, so matching against the - record registry can later stop at the first registered record on a path. The - walker does not read the record registry. +- **A slot** is `{std::type_index type, std::string path, bool opaque}`. Every + visited aggregate is one, the result itself at path `""`, so matching against + the record registry can later stop at the first registered record on a path. + The walker does not read the record registry. A visited type with a + `heldRecord` type and a `heldMember()` also yields a slot of `heldRecord` at + that member, as `table::ChangedRows` does. An `opaque` slot is added by + `BRIDGE_REGISTER_TABLE` only, for a record the result holds at no path. +- **A holder's members.** A visited type with `openMembers()` (a range of + names) or `partialMember()` (one name) is also recorded in + `ActionResult::holders` as `HolderMembers{path, open, partial}` + (`detail::walkHolders()`), a named member its reflection lacks left out. + `table::Page` names `awaiting` and `distinct` as open and `unloadedRows` as + partial. Resolution gives each `ActionRecord` the `open` and `partial` + member paths of every holder above one of its paths: while one is set, a row + the result does not hold may come to belong to it, or a merge by key would + leave it describing other rows. The client's catalog copies `open`, + `partial` and `opaque` into `ui::ActionRecordInfo`. - **Visited:** the result; the value of a `std::vector`, `std::optional` or `std::map` (adds no path segment); the members of a type glaze writes as an object, either by pure reflection or through a `glz::meta` object mapping. @@ -1823,7 +1948,9 @@ for every action, which records its result holds. contains it (a path contains itself and every path below it; `""` contains all). So each path stops at its first registered record, and a record's own members are never searched for further records. Kept slots are grouped by - record into `ActionRecord{record, keyField, paths}`, giving `recordsOf`. + record into `ActionRecord{record, keyField, paths}`, giving `recordsOf`. An + opaque slot of a registered record is an `ActionRecord` with no paths and + `opaque` set, apart from the path matching. `actionsHolding(record)` is the inverse: the action ids, in id order, whose `recordsOf` names the record. - **Validation.** Resolution refuses, all problems at once: @@ -1846,7 +1973,9 @@ for every action, which records its result holds. identical declaration is one, and a translation unit that does not see it reads the same effects; - a keyed record with `derivedFrom`: a key-level change to a source does not - say which derived rows moved, so a derived record is keyless; + say which derived rows moved, so a derived record is keyless. A table's + record (`RecordInfo::table`) is the exception: a source's change reaches it + as a whole-record change, and its own actions name its rows; - a `derivedFrom` source that is not a registered record: it never changes, so the derived record would never be refreshed; - a `derivedFrom` cycle among registered records, a record derived from diff --git a/docs/spec/forms/engine.md b/docs/spec/forms/engine.md index 597ec3f30..5978f1828 100644 --- a/docs/spec/forms/engine.md +++ b/docs/spec/forms/engine.md @@ -21,6 +21,7 @@ which is the host's contract ([../ui/host.md](../ui/host.md)). - [Submitters and typed forms](#submitters-and-typed-forms) - [The field overlay](#the-field-overlay) - [Rendering](#rendering) +- [Derived values](#derived-values) - [Collections](#collections) - [Wizards](#wizards) - [Rendering collections and wizards](#rendering-collections-and-wizards) @@ -36,7 +37,7 @@ Header-only, in the base `morph` target: | `field_model.hpp` | `FieldKind`, `SubmitMode`, `FieldSpec`, `FieldGroupSpec`, `FormModel` | | `rules.hpp` | `SchemaError`, `Tri`, `RuleOperand`, `RuleExpr`, the gating and presentation verdicts | | `values.hpp` | `FieldError`, `WireValue`, `Encoding`, `ValueContext`, `encodeScalar`, `decodeScalar`, `convertDraft`, `parseOptions` | -| `form_session.hpp` | `Submitter`, `ChoiceFetcher`, `FormSessionOptions`, `FieldState`, `RowState`, `FormSession` | +| `form_session.hpp` | `Submitter`, `ChoiceFetcher`, `FormSessionOptions`, `FieldState`, `RowState`, `FormSession`; its rounds of derived values use `forms/derive.hpp`'s `DeriveOptions`, `DeriveRound`, `DeriveLoad` and `DeriveState` | | `handler_submitter.hpp` | `handlerSubmitter`, `handlerChoiceFetcher` | | `typed_form.hpp` | `Form`, and the definition of `FormModel::forAction()` | | `overrides.hpp` | `FieldView`, `Overrides` | @@ -82,7 +83,7 @@ the text does not matter). | `ObjectArray` | an array of objects | an array of nested objects | A `FieldSpec` also carries the label, help, placeholder and i18n key; `required` and `x-blankAs`; `x-readonly`, -`x-hidden`, `x-computed`'s inputs; exact bounds (`minimum`, `maximum`, `multipleOf`, `x-exactMinimum`, +`x-hidden`, `x-computed` and its inputs, `x-derived`; exact bounds (`minimum`, `maximum`, `multipleOf`, `x-exactMinimum`, `x-exactMaximum`) and instance bounds (`x-minimum`, `x-maximum`); places; the units with their exact factors; the enum options; the Choice descriptor; the section and column span; the slider range; and the children of an `Object` or `ObjectArray`. Nesting is described to `kMaxNestingDepth` (4) levels and stops where a `$ref` chain @@ -225,6 +226,17 @@ it. A view mounted on it is destroyed first. fetch, keep the selection. A failed fetch is not repeated on its own: `retryOptions()` fetches again, and opening the field's dropdown in `formView` runs it, so options that failed when the form was built (an action that needs the screen's own setup first) are fetched once the user asks for them. +- **A Choice member of a collection row** looks up each `x-optionsDependsOn` name among its row's members first, then + among the top-level fields, so a grade can depend on its row's material and the form's site. Its options are not + fetched until an editor of it opens (`FieldState::openOptions()`, which a grid's cell editor calls as it opens), so + a column of 300 rows fetches nothing until a user opens a cell. Every row member's fetch goes through one cache of + the session (`SessionCore::sharedChoices`): identical `(optionsAction, request)` pairs share one fetch for the + session's life, a second ask joining the fetch in flight or taking its reply, and a failed fetch is not kept, so + the next ask fetches again. A column of rows over five materials makes five requests. A top-level Choice keeps its + own query, unshared. +- **Options narrowed per row.** `FieldState::narrowOptions(values)` keeps only the options whose JSON literal is + listed (a grid column's `options` overlay); `options()` offers the narrowed list, and nothing restores every option. + `overridePlaceholder(text)` replaces the placeholder the same way (a column's `placeholder` overlay). - **Automatic submission waits for options in flight.** While any top-level Choice is fetching, its selection is unjudged — a parent just changed — so the automatic Effect does not submit; the settled query wakes it, after a stale selection has been cleared. @@ -282,7 +294,7 @@ before it. | Slider | `Slider` over `x-min`..`x-max` by `x-step` | | Array | `TextInput`, comma-separated | | Object | `Panel` of its members' cells | -| ObjectArray | a `forEach` of row panels, each with Remove, and an Add button | +| ObjectArray | a `forEach` of row panels, each with Remove, and an Add button; with `x-widget: grid` (or an overlay's `widget: grid`), a grid of its rows (`ui::formGrid`, [../table/editing.md](../table/editing.md#a-grid-of-a-form)), one column per member in schema order | - **A cell** is the label (a `ui::TextRole::Label` text, so the theme's `field.caption.case` shapes it) and the control (which marks a required field, live, and describes itself with the help), visible while the field is. The cell owns the caption, and the control owns the required mark and the unit: the mark is the @@ -325,9 +337,94 @@ before it. ([../ui/interpreter.md](../ui/interpreter.md#lowering)): the interpreter adds it as a field-path override, and the cell around it (caption, help, visibility) is drawn as for every override. -**Not supported:** the grid widget (`x-widget: grid` on an `ObjectArray`), whose keyboard model needs a way for the -view tree to move focus, which it does not have (a kit's grid is reached through a host component); and a -document's subtree overrides. +The scalar controls (every kind but an Object and an ObjectArray) are `detail::engine::scalarControl(session, +field)` in `forms/engine/field_control.hpp`, which a grid's cell editor draws too; `form_view.hpp` includes it and +`ui/grid.hpp`, and neither of those includes `form_view.hpp`. + +**Not supported:** a document's subtree overrides. + +## What changed, and edits not yet committed + +- **The load record.** For every scalar field, the members of an Object and of each row of an `ObjectArray` + included, the session keeps the draft and the unit it held when the form was last loaded, by + `FieldState::path()` (`specimens#3.mass`), and each row of a collection then. Construction, `prefill`, `reset`, + a `refill` that loads a field and a successful submission that ends a field's edit write it, for the fields they + load. +- **`modified(path)`** (tracked) is true when the field's draft or unit differs from the record, or the field is a + member of a row added since the load. A computed member (`FieldSpec::computed`, from `x-computed`) and a derived + one (`FieldSpec::derived`, from `x-derived`) are never modified: only a round writes them. Any other member stays modified whatever freezes it after the user typed in it. + **`rowModified(arrayPath, key)`** is true when a member of the row is modified or the row was added since. +- **`loadGeneration()`** (tracked) is a count that moves with each load: each write through `FieldState::load`, + which sets the fields it writes afresh, their units included. Construction, `prefill`, `reset`, a `refill` that + loads a field, a successful submission that ends a field's edit and a round of derived values (`loadDerived`) + that writes a member are loads. A switch of units as loaded alone (`switchUnitsAsLoaded`) is not, and nor is a + `revert`. What follows loads, such as a fixed grid's `unit` overlay giving a field its unit again after a load, + reads it; since a switch as loaded moves it not, one grid's switch is never another's load. +- **`revert(path)`** restores the record's draft and unit, programmatically; a row's path (`specimens#3`) reverts + each member, and reverting a row added since the load removes it. +- **`field(path)`** takes a row by key too: `rows#.member`, as `FieldState::path()` writes it, beside + `rows[i].member` by position. +- **Before-submit hooks.** `addBeforeSubmit(hook)` returns an id for `removeBeforeSubmit`; `submit()` runs every + hook, in the order added, before it reads the body, so an edit not committed yet (a grid's open cell editor) + is sent with the rest. +- **A refused submission's fields.** A reply's `errors` member names them: an object from a field's path + (`specimens[1].mass`, read as `field(path)` reads it) to a message, or to a list of messages of which the first is + shown. Each is that field's refusal: `refusal(path)` (tracked) gives it while the field keeps the draft it had then; + a path the form has no field for is not shown. Such a reply did not save the record, so what it sent stays an + edit. The next reply replaces them, and a failure clears them. A failure names no field: a + `model::ActionRefusal`'s arguments fill its sentence, and an argument whose name happens to be a field's path is + not that field's error. A reply member named `errors` is reserved for field errors: an action whose reply carries + a domain member of that name has it read as field errors, and the record taken as not saved. +- A field is frozen (`readonly()`) by `x-readonly`, `x-computed`, `x-derived`, a frozen parent or a `readonlyWhen` + naming it. + +## Derived values + +A form asks for the values it cannot compute from what it holds in **rounds** +([../table/editing.md](../table/editing.md#derived-values)): an evaluation of the action, whose recomputed body gives +the computed members (`x-computed`, on the action and on a row type), and a call of the form's derive action, whose +`forms::Derived` reply gives the derived members (`x-derived`, `FieldSpec::derived`). Neither is a member the user can +edit, so a round never replaces a draft the user typed. + +- **`deriveWith(DeriveOptions)`** turns rounds on: `evaluate` sends the body to the action's evaluation (the UI + service's `ui-evaluate`), `derive` sends `{"body": }` to the derive action, `scheduler` runs the debounce, + `debounce` is how long a commit waits for a further one (**150 ms** by default), and `refused` is told the paths a + derive reply named that are no derived member. Until it is called a session makes no round. +- **`noteCommit()`** is what a committed edit runs (a grid's `FormGridSource::committed`). With a round in flight + it marks the round stale; otherwise it restarts the debounce timer, whose expiry starts a round; with no scheduler + a round starts at once. +- **A round** captures itself (`captureRound()`: the next sequence, `partialBody()`, and the row keys of every + collection by `FieldState::path()`), sets `deriveState()` to `Running`, and sends the evaluation and the derive call, + each when set, with that body. At most one round is in flight. +- **`partialBody()`** is the body as far as it encodes: every top-level field that encodes; an Object or a collection + member by member, a blank member or one that does not encode left out; every row written, in order, `{}` for a row + with nothing. A left-out member decodes to its default on the server. +- **Loading.** `loadDerived(round, Derived)` writes the derived members a reply names, and + `loadDerived(round, evaluatedBody)` the computed members of the recomputed body (a computed member the body leaves + out of an object it holds is blank; its `errors` and `ready` are not read). Both resolve `name[i]` through + `round.rowKeys[name][i]` and the row's current position by key, so a value lands on the row it was computed for + after rows were inserted or removed, and a value for a row removed since is dropped (not refused). A path that + names no member of the reply's kind is refused and returned in `DeriveLoad::refused`. A load is programmatic and no + edit, as `assign` is: nothing is submitted, what the user typed stays an edit, and a member it writes that held its + loaded value holds the new one as loaded. A field's snapshot (`FieldState::snapshot`, what `refill` and a save's + settle compare) leaves computed and derived members out, so a round never makes a top-level field look edited or + different from what a submission sent: a save the round overlaps still ends the edit of what it sent, and a later + `refill` still reaches the collection. A computed or derived member is never `modified`. +- **`switchUnitsAsLoaded(switches)`** switches units the same way, converting each draft: what the first unit a grid's + per-row `unit` overlay gives each loaded row is, so the cell is not modified by it and a revert returns to it. It + takes unit switches only, so nothing beyond the cells it names is recorded as loaded. +- **Order.** Each kind of reply keeps the sequence it last loaded; a reply of an older round loads nothing, so derived + values never go back to an older result. When both replies of a round settle, `deriveState()` is `Failed` if + either failed (the values stay as they were), else `Current`; a stale round then starts one more at once, with the + newer body. `recalculate()` starts a round unless one is in flight. `deriveFailing()` is true from a round that + failed until a round succeeds, a retry in flight included: a grid's stale marks and its standing "Derived values could + not be recalculated" with "Recalculate" follow it, so they stay while the retry runs. +- **`insertRow(position)`** inserts a blank row before `position` (past the end appends), a user action like + `addRow`. +- **`removeRows(keys)`** removes rows by key in one change and returns them as `RemovedRow{position, row}`, each with + the position it stood at, ascending; **`restoreRows(rows)`** puts them back, each at its position, in one change, the + rows whole (their keys, drafts and units), so a grid's "Undo" of a deletion restores what was typed. An array's + `minItems` and `maxItems` are `FieldSpec::minItems` and `maxItems`, the bounds a grid's row operations keep. ## Collections @@ -398,14 +495,17 @@ to every form they draw, so `Overrides` reach the editor's and every step's fiel built-in header (`collection_title`; the wizard's before the step's position); empty shows the schema's. A header chrome draws its own. - **Chrome.** `CollectionChrome` and `WizardChrome` replace the view's own parts with a host's: the collection's - header, each row (the rows are then a list of the chrome's nodes rather than a table), the confirm (mounted only - while an action waits) and the editor dialog (handed the editor's form view to place); the wizard's header and - navigation. A chrome is handed the session and drives it through the same calls the built-in parts make, so its - gates are the session's: a chrome's Next does nothing until `canNext()`. A master-detail view has no editor - dialog to replace. + header, each row (the rows are then a list of the chrome's nodes rather than a table), the rows table whole + (`rows`, handed the session and what draws a row's Open and row-action buttons for its key text, empty when the + view has neither; unused while `row` is set), the confirm (mounted only while an action waits) and the editor + dialog (handed the editor's form view to place); the wizard's header and navigation. A chrome is handed the + session and drives it through the same calls the built-in parts make, so its gates are the session's: a chrome's + Next does nothing until `canNext()`. A master-detail view has no editor dialog to replace. - **Through a document.** The interpreter lowers a `collection` or `wizard` node to these views over sessions it builds from `Catalog::view` or `Catalog::wizard` and its model alias - ([../ui/interpreter.md](../ui/interpreter.md#lowering)). + ([../ui/interpreter.md](../ui/interpreter.md#lowering)). It sets the collection's `rows` chrome: the rows are a + table on the engine over `source()`, sorted, filtered, arranged, copied and persisted as every other table of + the screen ([../table/table.md](../table/table.md#collections-and-master-detail)). ## Corpora diff --git a/docs/spec/forms/forms.md b/docs/spec/forms/forms.md index e6c544f19..86b504f5d 100644 --- a/docs/spec/forms/forms.md +++ b/docs/spec/forms/forms.md @@ -264,7 +264,9 @@ to mark a field optional loses data rather than silently accepting a gap (see `std::string_view` that the action declares, or 3. It is the destination of an `A::computedFields` entry — a derived, read-only field is never something the user must fill in; see - [Computed fields](#computed-fields). + [Computed fields](#computed-fields), or +4. Its type's field metadata marks it `derived()` — the model sets it; see + [Derived members](#derived-members--derived-and-x-derived). Required-ness is derived here, and `x-rules` is derived from `A::formRules`, **independently**. They can therefore disagree; the one disagreement that makes @@ -913,7 +915,7 @@ this dual read. | Key | Where | JSON type | Meaning / renderer obligation | |---|---|---|---| -| `required` | top-level (object), and every nested-aggregate object schema (inlined property or `$defs` entry) — see [Nested aggregates (recursive, cycle-safe)](#nested-aggregates-recursive-cycle-safe) | array of strings | Names of members that must be engaged before submit. A member is listed unless it is a `std::optional<...>`, appears in `A::optionalFields`, or is a `computedFields` destination (see the [Required-ness rule](#required-ness-rule)). Always emitted (an explicit `[]` when nothing is required). The renderer blocks submission until every listed field has a value. | +| `required` | top-level (object), and every nested-aggregate object schema (inlined property or `$defs` entry) — see [Nested aggregates (recursive, cycle-safe)](#nested-aggregates-recursive-cycle-safe) | array of strings | Names of members that must be engaged before submit. A member is listed unless it is a `std::optional<...>`, appears in `A::optionalFields`, is a `computedFields` destination, or is a derived member (see the [Required-ness rule](#required-ness-rule)). Always emitted (an explicit `[]` when nothing is required). The renderer blocks submission until every listed field has a value. | | `x-order` | property node (sibling of `$ref`) | non-negative integer | The member's 0-based **declaration index**. Renderers lay fields out in ascending `x-order`, not in JSON key order (object key order is not preserved across DOMs). | | `x-decimalPlaces` | property node (sibling of `$ref`) | non-negative integer | The field's *declared* precision (`Quantity::declaredDecimals`, unit default unless the type overrides it; or a bare `math::Rational` member's `FieldMeta::decimals`, which is not rounded to on dispatch). The numeric input step / rounding granularity for entry in the canonical unit. **Enforced, not merely advisory:** the request/reply dispatch path *rounds* each submitted `Quantity` to this precision before storing it — the stored value, not just its tag, is reduced (see [Advertised precision is enforced on dispatch](#advertised-precision-is-enforced-on-dispatch)). A model serving one *instance* of an action may overwrite this with a value from data — see [Per-instance constraints](#per-instance-constraints--values-that-live-in-data); `x-instanceConstraints` (below) says when it did. | | `x-unitAlternatives` | property node (sibling of `$ref`) | array of objects | Convertible display/entry units for the field, derived from `UnitTraits::relations`. **Omitted entirely** when the unit declares no convertible peers. Each element has the five subfields below. The renderer offers these as a unit selector and recomputes the entered value *exactly* on switch; the submitted payload is always in the canonical unit (the one named by `ExtUnits`). | @@ -929,7 +931,8 @@ this dual read. | `title` | property node (sibling of `$ref`) | string | The field's display label — an explicit `FieldMeta::label`, else a title-cased member name (`dryMassPct` → "Dry Mass Pct"). Standard JSON-Schema vocabulary, not an `x-*` key. **Always emitted.** See "Field metadata" above. | | `x-placeholder` | property node (sibling of `$ref`) | string | In-control placeholder/hint shown while the field is empty, from `FieldMeta::placeholder`. Omitted when empty; never submitted. | | `x-readonly` | property node (sibling of `$ref`) | boolean | `true` when the field should be displayed but not editable. Emitted only when `true` — including on every `computedFields` destination (see [Computed fields](#computed-fields)). Not a security control — see "Field metadata is not a security control" above. | -| `x-computed` | property node (sibling of `$ref`) | object | Marks the field as derived. Present when the action declares it as a `computed(...)` destination ([Computed fields](#computed-fields)); absent otherwise. | +| `x-computed` | property node (sibling of `$ref`) | object | Marks the field as computed. Present when the action, or the element type of a `std::vector` member, declares it as a `computed(...)` destination ([Computed fields](#computed-fields)); absent otherwise. | +| `x-derived` | property node | boolean | `true` on a member its type's field metadata marks `derived()`: a value the model sets from the domain's data, emitted with `x-readonly` and left out of `required` ([Derived members](#derived-members--derived-and-x-derived)). | | ↳ `inputs` | `x-computed` object | array of strings | Wire field names of the sibling fields the value derives from, in declaration order. Advisory to the renderer; **authoritative computation is the server's** — see [Where the value is authoritative](#where-the-value-is-authoritative). | | `x-hidden` | property node (sibling of `$ref`) | boolean | `true` when the field should not be shown at all; the field remains part of the action payload. Emitted only when `true`. Not a security control. | | `x-widget` | property node (sibling of `$ref`) | string | The preferred control id: `"textarea"`, `"slider"`, `"radio"`, `"combo"`, `"password"`, `"checkbox"`, … A `fieldMetadata`-shaped override (a `.field`/`.widget` entry, read structurally — see [widget_hints.md](widget_hints.md)) wins; else the field type's own `widget()` (`Multiline`, `Ranged`). **Advisory** — a renderer that lacks the named control falls back to the type-default control (text area → text field, slider → numeric input, radio → combo). Omitted when neither a wrapper type nor an override supplies one. | @@ -2391,7 +2394,9 @@ struct LineItem { into a `detail::ComputeList<...>` value assigned to `static constexpr auto computedFields`. The framework detects it via the `detail::HasComputedFields` concept, mirroring `detail::HasOptionalFields`/`HasFormRules`. -- **`recomputeAll(action)`** is the single evaluator: it walks +- **`recomputeAll(action)`** is the single evaluator: it first recomputes + every nested aggregate (each element of a `std::vector` member, a nested struct member, either inside an engaged `std::optional`), recursively, with `recomputeAll` on each, so a top-level entry + over the rows (a sum of their totals) reads them recomputed; then it walks `A::computedFields` and, for each entry, overwrites the destination member with `fn(action)` — or, if any declared input is unengaged (`hasValue() == false`, for an input satisfying `EmptyCapableField`; a non-empty-capable @@ -2419,6 +2424,31 @@ never something the user must fill. `x-computed`/`x-readonly` are additive, optional `x-*` keys (see the [renderer contract](#renderer-contract-the-schema-key-vocabulary) table below); an action that declares no `computedFields` emits neither key. +### Derived members — `derived()` and `x-derived` + +A value that needs the domain's data (a limit from the standard in force, a +density looked up from the material) cannot be a computed field, which must be +pure. Its member is marked derived in its type's field metadata: + +```cpp +inline const std::array Specimen::fieldMetadata{ + morph::forms::derived<&Specimen::limit>()}; // describe<&Specimen::limit>().withDerived() +``` + +The schema writes `x-derived: true` and `x-readonly: true` on its property and +leaves it out of `required`. `recomputeAll` does not touch it: the model sets +it when it executes the action. Every execution path clears it first +(`forms::clearDerived`, `forms/derive.hpp`: every derived member of the action +and of every nested aggregate (each element of a `std::vector` member, a nested struct member, either inside an engaged `std::optional`), recursively, value-initialised) +before `recomputeAll`, so neither the model nor a computed field over it reads +a value the client sent — the in-process path included, so an action reads +the same in a local topology as over a server. `allFieldBoundsSatisfied` and +`fieldErrors` skip a derived member's declared `minimum`, `maximum` and +`multipleOf`: the validator runs on the cleared value, before the model sets +it. A form asks for derived values while the user is +entering through its derive action (`DeriveOf` in, `Derived` out; +[../table/editing.md](../table/editing.md#derived-values)). + ### Where the value is authoritative `recomputeAll` runs on every execution path, each authoritative: @@ -2591,7 +2621,9 @@ for the exhaustive tables and design rationale. |---|---| | `template auto computed(Fn fn)` | A `detail::ComputedField` value. | | `template auto computeList(Fields... fields)` | A `detail::ComputeList` value — assign to `static constexpr auto computedFields`. | -| `template void recomputeAll(A& action)` | Overwrites every `A::computedFields` destination in place; a no-op when `A` declares none. | +| `template void recomputeAll(A& action)` | Overwrites every computed destination in place: those of every nested aggregate (each element of a `std::vector` member, a nested struct member, either inside an engaged `std::optional`), recursively, then `A::computedFields`'; a no-op when there are none. | +| `template FieldMeta derived(label, help)` (`forms/derive.hpp`) | `describe(label, help).withDerived()`: a derived member, `x-derived`. | +| `template void clearDerived(A& action)` (`forms/derive.hpp`) | Value-initialises every derived member of `A` and of every nested aggregate (each element of a `std::vector` member, a nested struct member, either inside an engaged `std::optional`), recursively. | ## Design decisions @@ -2804,12 +2836,22 @@ therefore stops at its first repetition: that inner member is `truncated` must carry it is not ready. An optional member left blank is not an exception: the body omits it, and that is a body the schema accepts. -Computed fields, `formLayout`/`fieldSpans`, and `formRules` remain **top-level -only** regardless of nesting depth: a nested aggregate declaring any of those -has no effect on the generated schema. This keeps the generator focused on -what a nested-aggregate schema actually needs (per-field annotations) rather -than becoming a general recursive-descent schema compiler that also -re-derives layout/rules/computed-field semantics at every level. +`formLayout`/`fieldSpans` and `formRules` remain **top-level only** regardless +of nesting depth: a nested aggregate declaring any of those has no effect on +the generated schema. This keeps the generator focused on what a +nested-aggregate schema actually needs (per-field annotations) rather than +becoming a general recursive-descent schema compiler that also re-derives +layout and rules at every level. + +**Computed fields of a nested aggregate are the exception.** A grid enters the +rows of a `std::vector` member, and a row's own total is a pure function of +the row. So a nested aggregate type that declares `computedFields` (a +`std::vector` element, a nested struct member, either inside a `std::optional` +member, at any depth; the shapes the schema itself descends into) has those members written `x-computed`/`x-readonly` and +left out of its `required`, as the top level's are, and `recomputeAll` +recomputes every such nested value before the action's own entries, on every +path. A derived member of a nested type (`derived()`, below) is left out of its +`required` too, and cleared on every server path as the top level's is. Every nested-aggregate type in the chain must be **default-constructible**, exactly like the top-level action type (see below): the recursion builds its @@ -2822,7 +2864,8 @@ own probe instance purely to enumerate its members via reflection. from the top-level action type — they are not consulted on a nested aggregate, no matter how deep `mergeSchemaExtras` otherwise recurses (see [Nested aggregates (recursive, cycle-safe)](#nested-aggregates-recursive-cycle-safe) -above). Computed fields (`computedFields`) are likewise top-level only. +above). Computed fields (`computedFields`) are read from the top-level action +type and from every nested aggregate type (see above). The action type must also be **default-constructible**: `mergeSchemaExtras` builds a probe instance (`A probe{}`) purely to enumerate member names and types diff --git a/docs/spec/forms/views.md b/docs/spec/forms/views.md index 52ba4c137..3f15f7c40 100644 --- a/docs/spec/forms/views.md +++ b/docs/spec/forms/views.md @@ -161,6 +161,12 @@ type it is instantiated on. Each derived column carries: indirection. - `kind` — the column's table kind, by the names `morph::table::ColumnKind` reads: `custom` for an `x-comparator` member; + `measure` for an `x-measure` member, an amount with its unit's id + (`table::MeasureValue`), tested before the exact-value rule since its object + has `num` and `den` too (a forms collection refuses such a column with a + `SchemaError` on it: its table has no unit registry to read the cells' + units through, so it could neither order them nor show them in their units; + rows with measures are served as a model's table); `quantity` for an exact value (`num`/`den`) with `ExtUnits`, `decimal` without; `date` / `dateTime` for an integer with `x-widget` `epochDays` / `epochSeconds`, or a string with `format` `date` / `date-time`; `integer`, @@ -170,6 +176,21 @@ type it is instantiated on. Each derived column carries: defaulting to `field`; a renderer that wants a readable header without an override uses `title`. - `x-unitAlternatives`, `x-comparator` — copied off the property when present. +- `x-level` — the data level the column's cells need + ([../table/table.md, "Data levels"](../table/table.md#data-levels)), copied + off the property as `x-comparator` is. The row schema carries it on each + property the row type's `columnLevels()` names + (`static constexpr std::array columnLevels() noexcept`); + an entry naming a member the row does not have is skipped in the schema and + refused where the table reflects its columns. A collection reads it as + `CollectionColumn::level`. +- `x-column-group` — the id of the declared column group the column is in + ([../table/table.md, "Column groups"](../table/table.md#column-groups)), + copied off the property as `x-level` is. The row schema carries it on each + property the row type's `columnGroups()` names + (`static constexpr std::array columnGroups() noexcept`). It is not + `x-group`, which a form layout writes for the title of a field's group + ([forms.md](forms.md)). - `enum` — the values of a closed set: the property's `enum`, or the `const` of each `oneOf` entry (glaze's shape for an enum with names). @@ -194,7 +215,7 @@ have is emitted as a bare `{field, label}` column with no `x-decimalPlaces` / | `v-title` | top-level | string | Screen title. Defaults to `v-query`'s type id. | | `v-query` | top-level | string | Registered query action's type id; executed with an empty body. | | `v-rowKey` | top-level | string | Wire field uniquely identifying a row. Defaults to `"id"`. | -| `v-columns` | top-level | array | Ordered column descriptors: `{field, label, kind, title?, "v-hidden"?, "x-decimalPlaces"?, ExtUnits?, "x-unitAlternatives"?, "x-comparator"?, enum?}`. Derived from the row type unless `V::columns` overrides it. | +| `v-columns` | top-level | array | Ordered column descriptors: `{field, label, kind, title?, "v-hidden"?, "x-decimalPlaces"?, ExtUnits?, "x-unitAlternatives"?, "x-comparator"?, "x-level"?, "x-column-group"?, enum?}`. Derived from the row type unless `V::columns` overrides it. | | `v-rowAction` | top-level | object | `{action, bind?}` — the action a row activation opens. Omitted when `V` declares no `rowAction`. Carries only `action`/`bind`, never `label`/`scope`/`confirm`. | | `v-actions` | top-level | array | `{action, label, scope, bind?, confirm?}` per entry — buttons that run an action. `scope` is `"row"` or `"collection"`; `confirm` is omitted when `false`; `bind` is omitted when empty. Omitted entirely when `V` declares no `actions`. | diff --git a/docs/spec/qt_quick/backend.md b/docs/spec/qt_quick/backend.md index eeb80989a..fb148a474 100644 --- a/docs/spec/qt_quick/backend.md +++ b/docs/spec/qt_quick/backend.md @@ -314,6 +314,18 @@ state, so its look follows the selection alone; its `clicked` fires the row's `t rows that have them, as the contract's "Selection by key" says; a user's change reports exactly the existing rows selected. +A summary row (`setRowSummary`) is `MorphTableRow.summary`: a `summaryFill` rectangle in `Theme.tableSummary` +(`color.table.summary`) over its background, and its tap, context and long-press handlers off, so it is never +selected, activated or given a cell menu. A span across columns (`RowSpan::columns`) is a `spanPlan` entry's +`columns`: the spanning cell and its backdrop are laid out across that many columns from its own +(`MorphTableRow.spanWidth`), and the cells it covers in its row and the rows below are hidden. + +Header bands (`setBands`) are the QML property `bands`, `[{level, text, first, count, pinned}]` with `text` the label +and its unit (`ui::headerText`): one item per run (`band`), at its level's line above the group line, from the +left edge of the first column at the visible places it names to the right edge of its last, so a band moved apart is +two items and never covers a foreign column. `groupRowHeight` is everything above the column headers: the band lines, +then the group line. + A spanning cell (`setRowSpans`; `TableImpl::planSpans` resolves it against the rows as they stand, each time a row comes, goes, moves or is told its spans) stays a cell of its origin row, left out of that row's `tallest` and `implicitHeight`, and overflows the row downward: `MorphTableRow.spanPlan` (`[{column, rows}]`, the spans clipped to the @@ -339,6 +351,88 @@ document hid): it takes no focus and no tap, has no accessible node, and is left caches as a hidden cell is. `Accessible` has no cell extent, so assistive technology reads the cell in its origin row. +**A table over a `TableSource`** draws what the mount realizes ([table.md, The renderer](../table/table.md#the-renderer)). +The mount gives it a horizontal-range handler before any row, and `TableImpl::setOnHorizontalRange` sets +`sourceRows`: the rows then go into a plain item (`rowsPlane`), not the column layout, and each is placed at the top +of its view row (`setRowIndex` writes `viewRow`), whatever its place among the children, since the focused row stays +realized outside the row window; a row is striped by its view row's parity, not its place. **The measure.** +`tableMeasure` answers pixels: a unit is `Theme.unitWidth`, a monospace character `Theme.monoAdvance`, a column's +padding `table.cellPaddingX` a side and a content column's start twelve units, so the mount gives a windowed fixed +column the width `measure` gives it unwindowed. **Cells by column.** `setCellColumn` writes the cell's `measuredIndex` (the column it +is placed in and reports its widths for) and pools a cell with none through `ItemBase::cover`, so a pooled cell is +hidden and placed nowhere; a row never places a source table's cells by their order, and places them once per event +loop turn however many a pass moves (`schedulePlace`). **The column window.** +`setColumnWindow` writes `windowColumns` (`[{column, offset, width}]`, pixels, pinned first), `windowTotalWidth` and +`pinnedShown`, and sets `arranged`: from then on no width is worked out over every column (`widths` is empty and the +caches are not scanned), the header has a label for each window column only (`headerCellCount`), at its offset, and a +row places each cell at its column's offset and width. A pinned column's header label and cells are held at the +leading edge (`x` plus `hflick.contentX`), above the rest: a header label on the surface colour, and a row's pinned +cells over an opaque backdrop the row makes in `cells` for a table with pinned columns only (`pinnedBackdrop`: the +surface, then a further instance of the row's `background` cut to the pinned columns, so the row's state shows there +too), which the scrolled cells pass beneath. Only they follow a sideways scroll (`placePinned`). `hflick` reports its `contentX` and the viewport less the select column (`hscroll`), unless +`setHorizontalOffset` moved it; a cell reports its natural width and its least width (`shrinkWidth` within its natural width), each +plus the padding, the first time either is larger than what the column was told (`measured`), and the table reports +each header's width the same way, again when a font or a sort mark changes it; the mount grows a content column by them +and fits the stretch columns to the viewport (`tableMeasure().shrinkFloor` is 8 units). **Row height.** A row's `measuredHeight` is its tallest placed cell's plus the padding, +counted in `rowMeasures`, or the one-line height when every column keeps one line, which measures nothing. +`layoutRows`, once per event loop turn, sets each realized row's height to what it measures, but no lower than the +height it had when the column window (`windowColumns`: its columns or their widths, counted in `windowEpoch`) last +changed; a row measured again in the same window takes what it measures, so one measured while a pooled row still +held another row's cells settles to its own height (a row that left is forgotten), takes their mean as the height of every row not realized, places each row +at `rowTop(viewRow)`, and moves `flick.contentY` so the first visible row keeps its place: a row above it that grows, +or a mean that changes, moves the view by as much (the mount holds no row heights, so this anchoring is +`MorphTable`'s). The rows in view (`rowAtY` over the top and bottom of the viewport) are what the table reports. +**Focus** is the table's own: over a source, `activeFocus` stays on `MorphTable`, never on a row, which a recycled +slot would take away, and a tap gives it to the table; the arrows, Home, End, PageUp, PageDown, Ctrl+Home and Ctrl+End +fire `focusMove` with the `FocusMove`, Space and Enter act on the focused row when it is realized, and `setFocusCell` +writes `focusedRowIndex` and `focusedColumnIndex`, brings them into view (`showFocusCell`) and makes that row +`current`. A tap does not move the mount's focused cell: no seam carries a pointer's cell. **Ranges.** Shift with Up +or Down moves the focus and fires `selectRange` from the anchor (`anchorRowIndex`: the row last tapped or toggled, or +the one the focus left) to the focused row; a Shift-tap fires it to the tapped row; Ctrl+A and the select-all box +fire it over every row of the view, as `Extend`, unless the table has a `setOnSelectAll` handler +(`selectAllHandled`), when they fire `selectAll` instead, which `TableImpl` passes to the handler. `TableImpl` passes them to `setOnSelectRange`, which resolves them over rows not realized and +refuses one past `maxRangeRows`; each is `multiple` only. `setSelectionView(except)` marks every row but those keys until the +next `setSelection`; in that state a Ctrl-tap reports `Extend` with the keys now marked among the rows the table +holds, the tapped one toggled. `setCounts` writes +`accessibleRowCount` (-1 for a lower bound) and `accessibleColumnCount`; `Accessible` has no row or column count to +put them in, so they are properties only. **Load states.** `setCellLoad` writes the row's `cellLoads`; a cell not +loaded keeps its content bound at opacity 0 under a mark (`loadMarks`): a rounded bar 3 em wide for `Unloaded`, a +`!` of the same width for `Failed`, whose tooltip and accessible name say "Could not be loaded", each in the +column's alignment and neither measured into its width. **Cell accents.** `setCellAccent` writes the row's +`cellAccents` (`{tone, tooltip, invalid}` by column, the tone -1 for none); the row draws each accented cell's slot +(`accentMarks`, item `cellAccent`): the tone's fill at half strength (`cellTint`, `toneBgOf`) over the row's +background and under the cells, so a cell keeps its tone in a toned or selected row and the selection fill and bar +show through it (a pinned cell's slot is the pinned backdrop's, over its copy of the background and under the pinned +cells, so it lies between the same layers); for a tooltip a small accent square at the slot's top end (`moreMark`), a `ToolTip` on +hover after the style's press-and-hold interval and at once while the cell holds the keyboard focus, and an +accessible `ToolTip` named by the text, ignored while there is none. An `invalid` cell draws the `!` mark of a failed +load, with the accent's tooltip as its tooltip and accessible name. **Cell marks and editors.** `setCellMarks` +writes the row's `cellMarks` (`{readOnly, modified, error, stale, muted}` by column); the row draws each marked +cell's slot (`cellMarkSlots`, item `cellMark`): a read-only cell's wash of the scheme's muted colour at 12% +(`readOnlyWash`), a modified cell's accent square at the slot's top start (`modifiedMark`), an error outline in the +scheme's error colour (`errorOutline`), and a stale or muted cell at the theme's muted opacity. `setRowModified` +writes the row's `modified`, an accent bar at the row's leading edge (`rowModifiedMark`). `setCellEditor` gives the +editor's item the cell's column (`measuredIndex`) and covers the cells of that column, so the row places the editor +over the cell's rectangle; null uncovers them, and gives the focus back to the table when the window's active +focus item was inside the closing editor; the row's `editorColumn` says which column it is, -1 for none, and +`editorItem` the editor's item: focus inside an open popup the editor owns (a control's `popup`, such as a combo +box's list, or a `Popup` among the data of the editor or a control inside it) counts as inside the table, though +the popup is drawn in the window's overlay; focus in any other popup or dialog is outside it. While a +table takes text (`setOnText`, MorphTable's `takesText`), printable text on the focused cell is its `text` event; a +table that takes cell clicks (`reportsCellClicks`) has each tap on a cell reported as its row's `cellClick` +(`{column, double}`), the second tap of a double tap with `double`; and one that reports focus leaving +(`reportsFocusOut`) watches the window's active focus item and fires `focusOut` once it leaves the table and every +item in it. **Headers with a unit.** A column's `unit` is written after +its label, `Mass [kg]`, the column is measured to that text, and the header's `Accessible.name` is +`headerAccessibleName`, `Mass, kg`. **The status line** (`setStatus`) is one `Text` under the +rows and outside the sideways scroll (`statusText`: the counts, the state, what stands and the message, two spaces +apart), with a "Retry" `Button` while the state offers it (`retryShown`), firing `retry`, and a `Button` for each of +its entries (`statusEntries`, `{id, label}`, the standing ones first; `objectName` `statusEntry_`), firing +`statusEntry` with the id, which `TableImpl` passes to `setOnStatusEntry`; while not shown it takes no height. It is a +polite live region: once its text has held for half a second it is announced (`Accessible.announce`, from Qt 6.8, +polite by default), so a message is read out once and a count when it settles; before Qt 6.8 the text is the line's +accessible name (`StaticText`) and nothing is announced. + A heading row (`setRowHeading`, the row's `heading`) places its one cell from the first inset across the select column and every column, less two insets; its `TapHandler`, Enter and select box are off, and `shownRows` (the rows the current row, Ctrl+A and the select-all box run over) leaves it out, as does a content column's width scan. Its @@ -346,17 +440,96 @@ background gets `heading` only when the part declares it, so a `tableRow` restyl the stock `MorphTableRowBackground` fills a heading with `scheme.tableHeader`, as the header row is filled, which is clear until a theme sets `color.table.header`, so in the stock theme a heading stands out by its content alone. -A sortable column's header label (`header`) is a Tab stop, and a tap, Enter or Space on it fires `sort` with -the column's index, which reaches `setOnSort`; another header takes neither. The table never sorts: `setSort` writes -`sortColumn` (−1 for none) and `sortDescending`, and the sorted column's label shows ` ▲` or ` ▼` after its text. -Every sortable header keeps room for the mark in its column's floor, so the columns do not move when the sort does. -Qt's accessibility has no sort state, so the header (a `ColumnHeader` named by its label) states the order in its -`Accessible.description`, "Sorted ascending" or "Sorted descending". +A column's header label (`header`) is a Tab stop while it is sortable, or the table has menus or moves its +columns. A tap, Enter or Space on a sortable one fires `sort` with `{column, shift}`, `shift` while Shift is held +(`HeaderClick::Shift`; Ctrl, on a tap or a key, sorts as `Plain`), which reaches `setOnSort`; another header takes neither. The table never sorts: `setSort` writes +`sortMarks` and `sortDescriptions`, each by column, from `ui::sortMarkText` and `ui::sortDescription`, and a header in the +chain shows its mark after its text (` ▲`, or ` ▲2` with two or more keys). Every sortable header keeps room for a +one-key mark in its column's floor, so the columns do not move when such a sort does, and for the mark it draws now, +so a header of a chain of two or more keys widens to hold its place (` ▲2`) rather than cutting it. Qt's accessibility has no sort +state, so the header (a `ColumnHeader` named by its label, and `{label}, filtered` while `filteredColumns` names it) +states the order in its `Accessible.description`, `sorted ascending` or `sorted ascending, key 2 of 3`, and nothing out +of the chain. + +**Header menus.** With menus (`hasMenu`), a right click on a header, or Shift+F10 or the menu key on a focused one, fires +`menu` with its column, and the `⋯` (`tableMenuButton`, named `Table options`) at the header's trailing end, held in view +over the sideways scroll, fires it with −1. The `⋯` has a width of its own (`menuReserve`, a touch target) that the +columns leave free, so it covers no header or filter button. C++ reads the entries then and calls +`showMenu(column, entries)`, which opens `configMenu`, a `Popup` placed under that header (or the `⋯`), at its start +where it fits. The popup takes the focus: Up and Down move among the entries that can be chosen, passing over +separators and headings, Right or Enter opens a submenu and Left or Backspace goes back up, Enter or Space chooses, and +Escape or a press outside closes it and gives the focus back to the header. An entry is drawn as a button-style +`MorphMenu` draws it (`menuEntryText`): a checkable entry's `✓` (or room for one), an icon the theme names drawn as its +icon (one it does not, written as its name), the label, `›` for a submenu, the chord after it, and the description as +a muted line under it; a separator is a `MenuSeparator` line. Each entry is an `Accessible.MenuItem` with its +description, and a checkable one is a checkable button whose `checked` follows its mark: the state is on the button, which is what assistive technology reads, and a click puts the binding back before it is acted on. A choice comes back as `menuChoose` with +the column and the path. A closed popup is not shown, so it is neither a Tab stop nor an +accessible node. + +**Cell menus.** With a cell menu (`hasCellMenu`, from `setCellMenu`), a right click or a long press on a row's cell +(`MorphTableRow.columnAt` names the column under the pointer, a pinned column before the scrolled ones under it) fires +the row's `cellMenu` with the column, as Shift+F10 or the menu key does on the focused cell of a table over a source. +`TableImpl::openCellMenu` makes the row the selection alone, reported as `Replace`, when it is not marked, asks for the +entries, which focuses the cell, and calls `showCellMenu(anchor, entries)` with the cell's item: the same `configMenu` +opens under the cell, with the column −2, named `Cell options` for assistive technology, and the choice comes back as +`menuChoose` with that column, which C++ routes to the cell whose menu is open; closing it gives the focus back to the +table. Over a source, a key the table leaves is asked of C++ as `cellKey`: one that is none of the chords +`setCellMenuKeys` gave answers false at once, and one that is runs the focused cell's first enabled entry without a +submenu whose chord it is. + +**The column chooser and the sort dialog.** "Columns…" and "Sort…" in the table's menu open dialogs the interpreter +builds from widgets the backend already has (`ui/table_dialogs.hpp`), so the backend adds nothing for them: each is a +`MorphDialog` (test ids `table_columns` and `table_sort`, titled `Columns` and `Sort`), mounted beside the table in a +column that takes the table's place, layout and visibility. The column has no gap, so the dialogs' zero-sized +placeholders add no space. Inside it the table fills the column across, and along it unless its height is fixed or a +stretch: a row offers to fill its height to the column, and a share of the row is the column's to take. The chooser holds, +per column in the layout's order, a `MorphCheckbox` and two `MorphButton`s (`Move up`, `Move down`), then `Reset +columns`, `Group columns…` with its form (a `MorphTextInput`, a check box per column, `Create group`), a line and a +`Remove group` button per user-formed group, and `Done`; the sort dialog, per key, two `MorphSelect`s (the column, and +`ascending` or `descending`) and `Move up`, `Move down` and `Remove`, then `Add key` and `Done`. Escape or a press +outside dismisses either, which closes it as `Done` does. Each change applies as it is made; a refusal goes to the +table's status line, under the dialog. + +**The filter menu.** A filter button, "Filter…" and a group's "Filter {group}, {k} columns…" open a third dialog the +interpreter builds from the same widgets (`ui/table_filter_menu.hpp`): a `MorphDialog` (test id `table_filter`, titled +with the column's or the group's label) beside the other two. A values list is a `MorphTextInput` search, a +`MorphCheckbox` per value (`{text} ({count})`, `(Select all)`, `(Blanks)`), a muted `MorphText` heading per dimension +of a `Measure` column, a `▸` `MorphButton` on a date bucket that opens, and `More values`; a muted note says the list +may grow, how many cells could not be read, or why Apply applied nothing. The conditions are `MorphSelect`s (the +condition, `and` or `or`, a `Measure` column's unit, a group's match line) and `MorphTextInput`s, a date column's +operand a `MorphDateTimeInput`; an operand that does not read draws its field's error. `Apply` and `Clear filter` +end it. Escape or a press outside closes it; a condition waiting for its debounce is dropped with it. The backend adds +nothing for it. + +**Moving and resizing.** While the table moves its columns (`movable`), dragging a header and releasing it over +another fires `columnMove` with the dragged column and the other's visible place (`visibleColumns`, or the column's own +index when every column shows), and Ctrl+Shift+Left and Ctrl+Shift+Right on a focused header fire it with the place one +over. While it resizes them (`resizable`), each header ends in a `MorphTableHeaderEdge` (`edge`, six pixels, a +split cursor): dragging it fires `columnResize` with the header's new width in pixels, from which C++ takes the cell +padding on both sides (`measurePadding`, which the mount adds back) and rounds the rest to units of `Theme.unitWidth`, +and a double click on it fires the column with no width. A tap on the edge does not also sort. A sort tap reads Shift +from its handler's point, which carries the modifiers. + +**Filters and groups.** A filterable column's header ends in a filter `ToolButton` (`filter`), `▿`, or `▾` while +`filteredColumns` names the column, which fires `filter`. With `columnGroups`, a row `groupRowHeight` tall sits above +the headers: each group's label spans the headers at the visible places it names, worked out from the widths and the +column window the header is laid out by (`columnBox`), so it follows order, hidden and pinned columns, widths and the +sideways scroll; it ends in its own filter button (`groupFilter`), filled while the group is `filtered`, which +fires `groupFilter`. A filterable header keeps room for its button in its column's floor, and is named +`{label}, filtered` only while it is filterable and filtered. Ctrl+C on the table or a focused header, while the table +copies (`copies`), fires `copy`. + +The clipboard is `QGuiApplication::clipboard()`: `copyText` sets its text. A row draws its background part (`background`, the `tableRow` part restyle) under its cells and hands it its state: `selected`, `hovered` (the pointer over the row), `current` (keyboard focus within the row), `alternate` (an odd position, which C++ writes on every row after each append, destroy and move), `tone` (`setRowTone`: −1 for none, else the `ui::Tone` index), `selectColumn` (whether the table's select column shows the selection) and its `scheme`. +`setRowMarks` writes the row's own `busy`, `locked`, `unmatched` and `marksTooltip`: an unmatched row draws at +`Theme.mutedOpacity`, a busy one shows `busyMark` (a 3 px bar in `Theme.tableBusy` just inside the selection's bar, +anchored so that it follows a right-to-left layout), a locked one `lockedWash` (a `Theme.tableLocked` wash over its +cells), and a non-empty `marksTooltip` is the row's `tooltipText`; without one a locked row says "Locked by another +user" and a busy one "Saving this row", over the row's own `tooltip`. The row's height is the larger of its cells' and the background's `implicitHeight`; the stock background draws three marks that compose, then the hairline between rows, and its implicit height is a dense row's, `Theme.targetHeight - 8`. A toned row is tinted (`tint`: the tone's `bg` colour at half strength over `scheme.surface`) @@ -645,6 +818,14 @@ software scene graph: 6.8, as the accessible identifier, and every input kind as one node found by its name and role, the same node as its test id, that a driver focuses and types into (a text input) or sets (a slider), with a radio select's options as radio buttons. +- **The column window** (`test_qt_quick_table.cpp`, `QuickWindowFixture`: a table over `FakeRows` in a 1,280 × 800 + window, every column 64 px): the cells and header cells alive are the windows' (F2); flings create no cell once the + pools are warm (F8); the focused cell survives a scroll of 10,000 rows and 200 columns, with the view's counts (F10); + hiding and moving a column create no cell items (D8); the status line shows the counts and "Retry"; an unloaded + cell draws its placeholder and a failed one its mark, neither widening the column; a row's height does not shrink + when the column window moves and is forgotten when the row leaves the row window, and a table of one-line columns measures none; a row growing above the view keeps the rows in view + where they are; a windowed fixed column is as wide as an unwindowed one; a tap keeps the focus on the table and the + status line is announced (from Qt 6.8); Shift with an arrow, Ctrl+A and the select-all box select through the mount. - **qmllint** over every `MorphUi` component, through the module's lint target, failing on any warning (`tests/qt_quick/run_qmllint.cmake`). diff --git a/docs/spec/table/database_pages.md b/docs/spec/table/database_pages.md deleted file mode 100644 index 20c8f619e..000000000 --- a/docs/spec/table/database_pages.md +++ /dev/null @@ -1,297 +0,0 @@ -# `morph::table` — database pages - -Design spec for the seam that lets a model which holds its rows in a database page them there: `table::planQuery`, -the validated and normalised query; `Page::totalKind`, which says whether a reported total is the count or a lower -bound; and `table::conformanceFailures`, the helper that holds a model's translation to `apply`'s answers. Read -[`engine.md`](engine.md) first; this file extends its "Server mode" section. - -## Contents - -- [Why](#why) -- [Shape](#shape) -- [`planQuery`](#planquery) -- [Order: the model's row key](#order-the-models-row-key) -- [Semantics a translation keeps](#semantics-a-translation-keeps) -- [Per-kind translation](#per-kind-translation) -- [Text](#text) -- [Refusing what a store cannot translate](#refusing-what-a-store-cannot-translate) -- [Totals](#totals) -- [Conformance](#conformance) -- [Aggregate reports](#aggregate-reports) -- [What the seam does not do](#what-the-seam-does-not-do) -- [Alternatives considered](#alternatives-considered) -- [Failure modes](#failure-modes) - -## Why - -`apply` takes the server's rows as a `DataSource` and sorts, filters and slices them in memory. A list action over a -table that lives in a database then has to read every row of the table before it can return fifty of them. - -Measured on lims's ledger (Release build, SQLite on disk, one process): `ListEntries` over 10^6 entries took 527.6 s -and its peak resident memory went from 46 MB to 2,777 MB; a trial balance over 10^7 posted lines took 168.2 s and -peaked at 10,857 MB. `ListEntries` makes about five queries per entry (header, lines, an account lookup per line, the -company's currency), so most of its time is that per-entry pattern, not the volume of data; one flat read of the -narrow rows was not measured. Paging the rows once they were in memory took 140 ms. What the measurement does show is -that memory and time grow with the table, whatever the per-row cost. - -A database sorts, filters, offsets, limits and counts by itself. What it lacks is morph's interpretation of a -`TableQuery`: which columns exist and may be read, the bounds of `QueryLimits`, which operators a column's kind -defines, how an operand parses for its kind, and that a page request is clamped rather than refused. If every model -re-derived those from the raw `TableQuery`, two models would answer one query two ways, and neither would match -`apply`. The seam makes the interpretation one function whose output a model translates, and makes `apply` the -oracle the translation is held to. - -## Shape - -```text - TableQuery (untrusted body) - │ table::planQuery(query, columns, limits, mayRead, services, translatable) - ▼ - QueryPlan — validated, clamped, operands parsed to their column's kind - │ the model translates it into its own query (SQL, an index scan, a remote call) - ▼ - Page { rows, total, totalKind, offset } -``` - -Header-only, in `include/morph/table/query.hpp` beside `validate` and `apply`; the helper is -`include/morph/table/plan_conformance.hpp`. Neither depends on a database. - -## `planQuery` - -```cpp -[[nodiscard]] std::expected -planQuery(TableQuery const& query, std::span columns, QueryLimits const& limits = {}, - std::function const& mayRead = {}, Services const& services = {}, - std::function const& translatable = {}); -``` - -`planQuery` is, in order: `validate`; the `translatable` refusal; the guarded compile step; a pure projection of the -`CompiledFilter` into `QueryPlan`. `apply` calls `validate` and the same guarded compile step itself, so the -refusals of `apply` and of `planQuery` are the same values by construction, not by parallel code. - -The guarded compile step is one function, `compileFilterGuarded`, which `apply`, `Engine` and `planQuery` all call: -`compileFilter`, with an exception from the collator or the date parser returned as `ServiceFailed`. A throwing -service therefore never escapes any of the three. - -```cpp -enum class PlanUse : std::uint8_t { Sort, Filter }; -using FilterOp = CompiledFilter::Op; -using PlannedOperand = std::variant; - -struct PlannedSortKey { - std::string column; - ColumnKind kind; - std::string comparator; // a Custom column's comparator name; empty otherwise - SortDirection dir; -}; - -struct PlannedCondition { - std::string column; - ColumnKind kind; - FilterOp op; - PlannedOperand value; // the operand, typed by `kind`; empty for IsEmpty and NotEmpty - PlannedOperand upper; // Between's second operand; empty otherwise - std::string text; // the operand as the request gave it (Between: the first) - std::string upperText; // Between's second operand as given - bool caseSensitive; // text operators -}; - -struct PlannedColumnFilter { - std::string column; - Combine combine; - std::vector include; // empty means no condition - std::vector exclude; // a row matching any is rejected -}; - -struct PlannedGroup { - std::vector columns; // a row matches when the entries match on any column -}; - -struct QueryPlan { - std::vector sort; // most significant first - std::vector filters; // ANDed, in evaluation order - std::vector groups; // ANDed with `filters` - std::int64_t offset; // in [0, limits.maxOffset] - std::int64_t limit; // clamped to limits.maxLimit; zero is a count-only request - std::int64_t totalCap; // QueryLimits::totalCap -}; -``` - -- A group's columns carry `combine` as the group's, and their `exclude` is always empty: a group has no exclude. -- An entry that applies to none of a group's columns is the error `compileFilter` returns; an entry that applies to - some appears only under those columns. -- `PlannedOperand` is `std::int64_t` for `Bool` (0 or 1), as the engine holds it. -- An empty filter produces empty `filters` and `groups`. -- `planQuery` does not touch rows and is deterministic for equal inputs. -- A plan has no `wantTotal`: a model always reports a total (see Totals). `limit == 0` is the count-only request. - -## Order: the model's row key - -`apply` orders rows by the sort chain and breaks every tie by source row, so its order is total and stable, and an -empty sort is source order. A store has no source order, and an `ORDER BY` on a non-unique key, or none, makes -`OFFSET`/`LIMIT` pages repeat or skip rows. The contract on a store-backed model: - -- It names a unique, stable row key, and its source order is ascending by that key. -- It appends that key, ascending, as the last term of every ordering, including the empty sort. -- The oracle is `apply` over the same rows supplied in that key order. - -The plan does not carry the key: `RowId` is the model's. - -## Semantics a translation keeps - -The engine's rules (engine.md, "Keys and ordering" and "Filters") are the contract; a store's defaults differ from -them in these places, and the translation must not inherit the default. - -- **Empty and invalid cells sort after valid ones in either direction.** A store's `NULL` ordering is its own - (first ascending in some, last in others); the translation orders by "is empty" first, then by the value. -- **No operator but `IsEmpty` and `NotEmpty` matches an empty or invalid cell.** `IsEmpty` matches empty cells only, - so `NotEmpty` also matches invalid ones; a typed store has no invalid cells, and the model states how its columns - map (an unparsable stored value is a model decision, and the conformance corpus covers what it chose). -- **`exclude` keeps rows whose cell is empty.** A row matches no exclude entry on an empty cell, so it is kept. The - natural `NOT (x = 'a')` is unknown for a missing `x` and drops the row; render an exclude as "the cell is present - and meets the condition", negated. The same holds for `Combine::All` and for group entries. -- **Ties break by the row key** (above). - -## Per-kind translation - -Obligations on the store's query; SQL is an illustration. - -| Kind | Operand | Obligation | -|---|---|---| -| `Integer`, `Key` | `Rational` | The operand may be non-integral: `eq 1.5` matches nothing, `lt 1.5` matches values up to 1. Do not round the operand. | -| `Decimal` | `Rational` | Compare exactly. A value stored as numerator and denominator is compared by cross-multiplication or a common scale, never by a floating-point quotient. | -| `Quantity` | `Rational` in the canonical unit | Compare `amount * toCanonical`. A store holding amount and unit per row compares canonical values. | -| `Number` | `double` | A NaN cell is invalid, not a value. | -| `Date` | `int64` days since 1970-01-01 | Compare days. | -| `DateTime` | `int64` whole UTC seconds | The engine floors cells to seconds. A store holding finer instants (milliseconds) orders and ties by the floored second, and `eq` is a range over that second. | -| `Bool` | `int64` 0 or 1 | `false` before `true`. | -| `Text` | see [Text](#text) | | -| `Custom` | none | Ordered by the named comparator; see [Refusing](#refusing-what-a-store-cannot-translate). | - -An enum is a `Text` column holding the enumerator's name; the store's ordinal orders differently, so an enum is -translated as text (a mapped name column) or refused. - -## Text - -The engine compares a text operand to a cell after both pass through the collator's `fold`, and orders text by the -collator's `sortKey`. A store holds neither. `PlannedCondition::value` holds the folded operand (raw when -`caseSensitive`), and `text` holds the operand as given, so the model can use its store's mechanism. - -Text results equal the oracle's only when the store compares and orders by the same collator. Three ways satisfy that: - -- a stored fold column and a stored sort-key column, written through the same collator, which the query compares and - orders by; or -- a store collation documented to coincide with the collator. The default collator folds ASCII and Latin-1 letters - and orders by code point, and SQLite's `NOCASE` folds exactly ASCII, so `COLLATE NOCASE` reproduces the default - collator over ASCII data; or -- an expression the store evaluates over the stored text that equals the collator's fold, which the query compares and - orders by. It is exact when the expression maps every input to the collator's output byte for byte: for the default - collator that is the ASCII lower-casing plus the lowering of each two-byte Latin-1 capital (`C3 80` to `C3 9E` - except `C3 97`), where no replacement's output is the input of another, and the store's own lower-casing folds - nothing the collator leaves alone. Whether a given store's function does is a property of that store's build, so - the model's conformance run against the real store is what holds it. - -A text column for which none of them holds is refused in sort and filter through `translatable`, never answered -differently. A case-sensitive pattern needs a case-sensitive mechanism (`instr`, `GLOB`, a binary collation): a -store's `LIKE` may be case-insensitive by default, so `escapeLikePattern` alone is enough only on the folded path. - -## Refusing what a store cannot translate - -Some queries the engine accepts have no translation: a `Custom` sort key (its comparator is a function), a column -that is a serialisation or is computed, text under a non-matching collation. `planQuery` takes a predicate -`translatable(column, use)`, asked of the request's columns (including every column of a group, whether or not the -group's entries apply to it); a sort or filter on a column it refuses is `TableError{Unavailable, column}` with a -message naming the column. The predicate runs after `validate`, so the usual refusals come first and are identical to -`apply`'s. The conformance helper compares `apply` and the model on the queries the predicate accepts, and checks -that the refusals are equal values. Which columns a client may offer to sort and filter belongs in the schema and is -not part of this seam. - -## Totals - -`Page` has `TotalKind totalKind = TotalKind::Exact`, with `enum class TotalKind { Exact, AtLeast }`, written in JSON -by name, `"exact"` and `"atLeast"`, as the module's other wire enums are: - -- `Exact`: `total` is the count of the filtered view. -- `AtLeast`: `total` is a lower bound and the view has at least that many rows; a client shows "100,000 or more". -- `total` absent: not counted. - -`apply` reports `Exact` at or below `QueryLimits::totalCap` and omits the total above it. A model -either counts exactly, at any size, and reports `Exact`; or counts up to `totalCap + 1` rows and, when it found more -than `totalCap`, reports `AtLeast` with `total = totalCap`. Rules: - -- An estimate (a statistics table, a cached count) is never `Exact`; a model may report one only as absent. -- The count and the page run in one read transaction, so `total` agrees with the rows. -- The count covers the model's own scope (company, visibility) ANDed with the plan's filter, as the page does. -- A `limit` of zero returns the count and no rows. -- The conformance helper holds an `Exact` total to the true count on either side of the cap: where `apply` omits the - total it counts the view itself. - -`PageWindow::totalKind()` returns the kind of the latest reply that carried a total; `reset` clears it with the -total. `PageWindow` stops fetching past an `Exact` total only; past an `AtLeast` total it keeps fetching until a -reply is short. A glaze-read `Page` without the member reads `Exact`. - -## Conformance - -`conformanceFailures` in `include/morph/table/plan_conformance.hpp` runs a corpus of queries through `apply` over the -rows in key order and through the model's callback `PlanModel` (`QueryPlan -> ModelPage`, the page's row keys, offset, total and -total kind), and returns one description per -disagreement: rows (compared by key), offset, total and kind, and refusals (compared by code and column). -`standardCorpus` derives queries from a source's own cells: every operator each column's kind defines, both sort -directions on every column, an offset past the end, a zero limit, an exclude, a group. An operand is the cell's text -as `displayText` shows it, except that a `DateTime` cell (whole UTC seconds) is written as ISO 8601 UTC -(`2026-11-10T09:00:00Z`) and a `Date` cell (days) as `YYYY-MM-DD`: bare numbers do not parse as dates, so a query -built from them would be refused by `apply` and by the plan alike and compare nothing. - -Identical refusals count as agreement, so `conformanceFailures` also guards against a corpus that compared nothing: it -reports a column that the corpus filters with an operand (or, for sort-only queries, orders) when at least one query on it was -refused identically by `apply` and the plan and none was compared with the model. A query the model's `translatable` -refuses is skipped and counts as neither, so a column the model declares untranslatable is not reported. - -It lives under `include/morph/table`, not in the test tree, so a model in another tree includes it; it depends on -neither a test framework nor a database, returning descriptions for the caller's test to assert on. morph does not -depend on a database, so the framework test runs it against an in-memory reference model, a plan walker written from -the plan alone, with the total cap lowered so the above-cap rules run on a small table. A model over a store runs it -against its real store: that run belongs to the module that owns the store. - -The corpus is only as discriminating as the data. The data a store-backed model feeds it must include duplicate sort -keys, empty cells in each column, accents and case in text, sub-second date-times, quantities in more than one unit, -and non-integral operands on integer columns. `standardCorpus` takes its operands from the rows' own cells and adds a -half-step operand (`eq 1.5`, `lt 1.5`) for every integer and key column, so a translation that rounds an operand is -reported; the caller chooses the rows for the rest. - -## Aggregate reports - -A report that sums rows (a trial balance, stock on hand) computes its rows in the store, as a `SUM ... GROUP BY`, and -pages them one of two ways: with `apply` when the aggregate is small (a few hundred accounts), or with a plan -translated over the aggregate as a subquery: filters on the group key go to the inner `WHERE`, filters on the sums to -an outer `WHERE`, and the ordering to the outer query. A store-side sum of decimals needs a common scale (a value -held as numerator and denominator is not summed as a floating-point quotient). The plan does not describe the -aggregation, and `planQuery` is not given it. - -## What the seam does not do - -- It does not translate to SQL; morph has no ORM. -- It does not aggregate; if two modules hand-roll "aggregate in the store, then `apply`", an aggregate seam is due. -- It does not offer keyset paging: `PageRequest` is offset-based and a client fetches by offset. An offset costs time - linear in the offset in most stores, up to `QueryLimits::maxOffset`. -- It does not change `validate` or the defaults of `QueryLimits`. - -## Alternatives considered - -- **A SQL dialect in morph.** Couples morph to databases and to one dialect per backend; the model already knows its - store, and the plan is the part that is not store-specific. -- **Streaming every row to the engine.** Memory and time grow with the table, which is what was measured. -- **Loading the narrow rows in one query, then `apply`.** Removes the per-row queries but not the growth with the - table: at 10^7 rows the resident rows do not fit the criteria. -- **Each model validating the raw `TableQuery`.** Re-derives the operator and operand rules per model and drifts from - `apply`. -- **A boolean `totalExact`.** A present total is already exact, so it distinguished nothing a client can show. - -## Failure modes - -| Condition | Result | -|---|---| -| Query over a limit, unknown or hidden column | the `TableError` `validate` returns | -| Column or use the model's `translatable` refuses | `Unavailable`, naming the column | -| Operator the kind does not define, or an operand that does not parse | the `TableError` `compileFilter` returns | -| The collator or the date parser throws while operands compile | `ServiceFailed`, from `apply`, `Engine` and `planQuery` alike | diff --git a/docs/spec/table/editing.md b/docs/spec/table/editing.md new file mode 100644 index 000000000..9300dbbe5 --- /dev/null +++ b/docs/spec/table/editing.md @@ -0,0 +1,667 @@ +# `morph::table` — editing and grids + +Design spec for typing into a table: a grid that is part of a record being edited, cells of a model's table +edited one at a time, the cell editor, walking, pasting and validation, and the layouts an entry grid needs and +a read-only table uses too (header bands, spans, summary rows, fixed grids). Read [`table.md`](table.md) first, +for the pipeline this builds on, and [`../forms/engine.md`](../forms/engine.md) for fields, drafts and exact +encoding, which this reuses and does not repeat. + +## Contents + +- [Goal](#goal) +- [Two homes for an edit](#two-homes-for-an-edit) +- [A grid of a form](#a-grid-of-a-form) +- [Cells of a model's table](#cells-of-a-models-table) +- [The cell](#the-cell) +- [Walking](#walking) +- [Selecting cells, clipboard and fill](#selecting-cells-clipboard-and-fill) +- [Rows of a grid](#rows-of-a-grid) +- [Layouts](#layouts) +- [Document vocabulary](#document-vocabulary) +- [Invariants](#invariants) +- [API surface](#api-surface) +- [Tests](#tests) +- [What this does not do](#what-this-does-not-do) +- [Alternatives considered](#alternatives-considered) +- [Failure modes](#failure-modes) +- [Neighbouring specs](#neighbouring-specs) +- [Delivery order](#delivery-order) + +## Goal + +A laboratory application enters most of its data in grids: the specimens of a test, the fractions of a sieve +analysis, the layers of a core, the limits of a specification. What such grids need, in the order it matters: + +- **An editor per cell that follows the record's types:** text, integers, exact decimals with fixed places, + quantities, nullable numbers, dates, choices whose options depend on the row, check boxes. The kind can differ + between the rows of one column. +- **Computed cells beside entered ones**, read-only, which the cursor skips, and which follow every entered value. + The computation is often the domain's, on the server, over the whole record. +- **Validation that keeps what was typed** and says why it is wrong, at the cell. +- **A keyboard walk** that enters a column of values without the mouse, and leaves the grid at its ends. +- **Layouts a printed form has:** headers in two or three bands with units, cells spanning rows or columns, + blocks of rows per specimen with a mean, a minimum and a deviation under each, grids whose rows are fixed by a + standard rather than by data. +- **Paste and fill** from a spreadsheet, and **a mark on what changed** since the record was loaded. + +Two things decide the design. + +- **An entry grid is a form.** Its values are members of one record being edited, saved together, checked + together and derived from each other. The forms engine already holds drafts, encodes them exactly, keeps what + was typed across a reload and submits; a grid is a way to lay out an `ObjectArray` field, not a second editor. +- **It is still a table.** The renderer, the windows, the keys, the copy, the status line and the arrangement are + [`table.md`](table.md)'s. A grid of 30 specimens and a table of 100,000 designs scroll, focus and copy alike. + +## Two homes for an edit + +| | A grid of a form | Cells of a model's table | +|---|---|---| +| The rows are | Members of one record: an `ObjectArray` field, or fields laid out as a fixed grid | Records of their own: the rows of a `Table.` | +| An edit goes | Into the form's draft; the form submits | To an action, per cell or per row, at once | +| Derived values | The form's evaluation and derive call, or the document's expressions | The action's result and the table's change events | +| Mode | Client: every row is held | Server: a model's table always is | +| Size | Tens to a few thousand rows | Any size the table has | + +A table node is in one home for its lifetime, decided by what it names, as its mode is. + +## A grid of a form + +### Binding + +A form's `ObjectArray` field is drawn as a grid, inside the form or anywhere in its scope: + +- inside a `form` node, the field's overlay `{"widget": "grid", "grid": {…}}`: `widget` chooses the grid as the + field's control, as `x-widget: grid` on the field's schema does, and `grid` holds the table's properties below; +- anywhere the form is in scope, a `table` node with `form` (the form node's id) and `field` (the field's path) + in place of `rows`. + +The grid's rows are the field's `RowState`s, keyed by their stable keys. `ui::FormRowsSource` is the +`DataSource` over them, as `ValueRowsSource` is over a document's list: a cell is the member's encoded value +when its draft encodes, and an invalid cell when it does not, so sorting and filtering a grid follow the table's +rules. Sorting or filtering a grid changes what is shown and never the array's order or its members: the body +holds the rows in the order they were entered. A row added while the grid is sorted or filtered is shown at +the end of the view, and passes the filter, until the sort or the filter next changes, so the row being entered +does not jump or vanish under the cursor. For the same reason the row whose cell editor is open keeps the view +position it had, and stays in the view whatever the filter makes of its draft, until the edit is committed or +cancelled: its position, not its neighbours, since rows inserted or removed above it, or a new sort or filter, rearrange +the rows around it; then the sort and the filter place it, after the walk that the commit's key starts has moved on by view +position. A grid sorts and filters through a table's own header and menus: a column's +sort by its header, its filter button and values list, the cell menu's "Filter by this value" and "Exclude this +value", and the table menu's "Clear all filters", so a filter the user set shows on its column's header and is +cleared where any table's is. A display column neither sorts nor filters. + +A grid of a form takes `group`, with its headings and its summaries ([Summary rows](#summary-rows)), as a table +over `rows` does: a grid of specimens grouped by sample is one declaration. + +### Columns are fields + +A grid's column names a member of the row type: `{"id": "mass", "field": "mass"}`. The member's `FieldSpec` +gives the column its kind, its places, its units, its options and its bounds, so a grid needs no column +declaration beyond layout. A column without `field` is a display column: its `cell` or `value` expression is +read in the row's scope and it takes no edit. + +**Per row.** A column's field part may be an expression in the row's scope, naming a different member per row: +`{"field": {"if": [{"ref": "row.isChoice"}, "choice", "amount"]}}`. A row type that holds a value +of one kind for some rows and another kind for others has a member per kind, and the grid shows the one each row +uses. The kind of a value is the record's, never the grid's. + +A column also takes **overlays per row**, as a form field takes overlays: `decimals`, `unit`, `readonly`, +`options` (narrowing a choice's options), `placeholder`, each an expression in the row's scope. A row of a +specification grid that holds a value to one place and the next row to three says so here. + +On a grid column, `decimals` and `unit` are the field's overlays and mean what they mean on a `form` field: the +entry places, which are also the wire's `dp`, and the unit entered in. The column's display +([`table.md`](table.md#how-a-column-shows-its-cells)) follows them: a cell shows its value to the places its +field takes, so a grid never shows a value at places other than those it is entered with. The display-only +keys (`rounding`, `padPlaces`, `grouping`, `empty`, `labels`) keep their meaning on a grid. + +### Derived values + +A grid's derived cells come from three places, by who can compute them. + +- **The document's expressions**, for what the screen can compute from the values it holds: a column whose + `value` is `div(row.mass, row.volume)`, a summary row's `mean`. They are exact, follow every encoded draft at + once, and are display only: they are never sent. +- **Computed fields**, for a pure function of the record: members the action declares in `computedFields` + ([`../forms/forms.md`](../forms/forms.md#computed-fields)), on the action and, for a grid, on its row type. + The server recomputes them on every path and overwrites them on submit; the client asks for them while the + user is entering through the action's existing evaluation (`ActionDispatcher::evaluate`, the UI service's + `ui-evaluate`), which decodes a body, recomputes the computed fields and returns the recomputed body, with no + model instance, no journal entry and no state change ([`../core/registry.md`](../core/registry.md)). +- **Derived members**, for what needs the domain's data (a value looked up from the material, a limit from the + standard in force): members marked `derived()` in their type's field metadata, which the schema writes + `x-derived`. A computed field must be pure, so such a value cannot be one. A derived member is read-only in + the form, is not overwritten by `recomputeAll`, and is the model's to set when it executes the action: the + value the client holds is shown, never trusted. The form names its derive action with `derive`, an action of + the form's model that the application declares and registers as any action: + + ```cpp + /// The input of a derive action: the form's body as far as it encodes. + template + struct DeriveOf { Action body; }; + + /// The values of derived members, by path into the body that was sent. + /// Its JSON is {"values": [{"path": "specimens[3].density", "value": …}, …]}. + struct Derived { + struct Value { std::string path; glz::raw_json value; }; + std::vector values; + }; + + struct DeriveSieveAnalysis : forms::DeriveOf {}; + forms::Derived SieveModel::execute(DeriveSieveAnalysis const& derive); // `Loggable::No`, no effects + ``` + + It runs on the form's model instance (the form's `model` and `key`), declares no effect and is + `Loggable::No`, so a derive call is a read that leaves no trace. + +**The call.** After a cell's edit is committed ([The cell](#the-cell)), not per key, once the form's +`deriveDebounce` (a literal number of milliseconds on the `form` node, default 150) has passed with no further +commit, the form evaluates its body, and calls its derive action when it names one. + +- **The body as far as it encodes.** A member whose draft does not encode, or that is blank, is left out of the + body. A left-out member decodes to its default, as any body decodes; a computation that must tell "not + entered" from a value takes the member as `std::optional`, which is how the forms engine already represents a + nullable field. The domain computes what it can from what is there, as a lab sheet does with half its + fractions entered. +- **Loading the replies.** `FormSession::loadDerived` writes, from the evaluation's recomputed body, the computed + members, and from a derive reply, the derived members it names, and nothing else. Neither is a member the user + can edit, so a reply never replaces a draft the user typed, whatever was typed while it was in flight; and the + load moves no field's snapshot, so what the user typed stays an edit. A path is resolved against the rows as + they were when the call was sent (the session records the row keys of each `ObjectArray` at sending), so a + value lands on the row it was computed for even if rows were inserted or removed meanwhile, and a value for a + row since removed is dropped. The load is programmatic and causes no submission. +- **Order.** At most one evaluation and one derive call are in flight. A commit during them marks their replies + stale; the replies are still loaded, and then one more round is made with the newer body. Each round has a + sequence, and a reply older than one already loaded is ignored, so derived cells show at most one round trip + behind the last commit and never go back to an older result. +- While a round is in flight, derived cells draw muted. A failed round leaves the derived cells as they were, + marked stale, and the status line offers "Recalculate", which makes one more round. The failure is a standing + state, "Derived values could not be recalculated" with the entry "Recalculate": it lasts, through the hold of any + message and through a retry in flight, until a round succeeds, and the cells stay marked stale as long. + +### Submission + +The grid submits with its form, in the form's mode. In explicit mode the form's submit first commits an open +cell editor, so a value typed and not yet confirmed is sent with the rest. In automatic mode a committed cell +whose form becomes ready submits the body. A failed submission's field errors land on the cells they name +(`specimens[3].mass`). Computed members are recomputed by the server and derived members set by the model, +whatever the body holds. + +## Cells of a model's table + +A column of a model's table is editable when its description names the action that changes it: + +```cpp +/// One cell's change: the row and the new value of one member. Its schema carries `x-cellEditOf` with the +/// table's record; which column it edits is the column's `EditInfo`. +template +struct CellEdit { + RowId key; + T value; +}; + +/// Several members of one row changed together. `Values` is the application's struct of the row's editable +/// members, each optional: a member present is changed, an absent one is left as it is. Its schema carries +/// `x-rowEditOf` with the table's record. +template +struct RowEdit { + RowId key; + Values values; +}; + +struct EditInfo { + std::string action; // the action id, taking a CellEdit or a RowEdit of this table + std::string member; // for a RowEdit, the member of `values` this column edits; empty for a CellEdit + std::string readonly; // the id of a companion column whose `true` makes this row's cell read-only, or empty +}; + +struct TableColumn { + // … table.md's members … + std::optional edit; +}; +``` + +- The cell's field is the `value` member of a `CellEdit` action's input schema, or the named member of a + `RowEdit`'s `values`, so its kind, places, bounds and options are the action's. A `Measure` cell, in its own + unit, opens in its `Quantity` field's canonical unit, converted through the description's units; a cell the units + cannot convert (a unit they lack, another dimension) is read-only, as its value could not be shown in the unit it + would be written in. A `Measure` column whose field's canonical unit is not one of the description's units is + `SourceContract`. A column whose kind and whose + field's kind differ, or a `member` that `values` does not have, is `SourceContract`. +- **The action is the application's.** It declares `updatesTable` and returns the `ChangedRows` of the row, as + any action that changes a table does ([`table.md`](table.md#a-models-tables)). A `FailedRow` for the row, or a + `FieldError` naming `value`, settles the cell with that message. A row's commit may carry several cells: a + `FieldError` naming a cell's member (`value` for a `CellEdit`, the `EditInfo::member` for a `RowEdit`) is that + cell's; one that names no cell of the commit, a `FailedRow` included, is the error of every cell of the commit + that no named error reached; and a cell no error reached keeps its draft and takes no error. A commit that one + call cannot carry (a `CellEdit` cell beside `RowEdit` cells in `row` mode) is one call per action, and an error one + of them gives that names no cell is that call's cells'. +- **Committing** is `CellEdits`: edits to one row run one at a time, in order. A cell is stale from its commit + until the action replies. Then it shows the committed value (a column's own `cell` template shows the row's + value, which it reads from the record), marked modified, until the window next fetches + the row, which shows the row as the server has it; an edit that changes nothing, or that moves the row out of + the view, leaves nothing waiting. A draft that does not encode, or one waiting to be committed, is held by row + key and column, not by the window, so a row that scrolls out of the window and back finds its draft and its + error where they were, and a key change by `from` moves them ([`table.md`](table.md#rows-an-action-changed)). + `errorCount` counts them wherever the row is. A keyed refetch that names a row and returns none means the row + was deleted or left the filter: its drafts, errors and marks go, and so do its edits not yet sent. +- **A row at once.** A column whose `EditInfo` names a `RowEdit` collects the row's edits while focus stays in the + row and commits them together when focus leaves it, or on `Ctrl+Enter`. A refusal puts each `FieldError` on + its cell and, while the table has focus, moves focus back to the first refused cell: focus has left the row + by the time the reply arrives. A held cell whose row has become busy or locked, or whose value is no longer loaded, + when the row is sent is refused at the cell: it keeps its draft with the refusal as its error, and its next commit, + changed or not, sends it. This is for a record whose members are checked together, and + `editMode: "row"` on the table chooses it for all its columns. +- **Who may edit.** The action's authorisation is the rule: a principal the authoriser refuses for the action + sees the column read-only, which the client learns from the catalog's permitted actions. A row is read-only + per cell through `EditInfo::readonly`, and entirely while it is locked + ([`table.md`](table.md#how-a-column-shows-its-cells)). `TableColumn::edit` absent is read-only. +- A cell that is unloaded, or in a busy row ([`table.md`](table.md#rows-at-work-rows-that-failed)), takes no + edit: an edit of a value the user has not seen is an overwrite of whatever arrives. +- **A table's own edits make no row busy.** They are not registered as runs in the table's row states: a cell + being saved is stale, not busy, so a second cell of the row can be entered while the first is saving, and + its edit is queued behind it. A row is busy only through another run that names it, such as a document's + mutation or another table's action. +- **No row is held still.** An edit in a sorted or filtered column moves its row, or takes it out of the view, + when the window next fetches it. The walk moves by view position at the moment of the commit + ([Walking](#walking)), so entering a column of a sorted table continues down the rows that were below, and + does not follow the edited row. + +## The cell + +### The editor + +A cell's editor is the forms control for its field's kind, drawn inside the cell: a text input, a number input +with its places and unit, a check box, a dropdown for an `Enum` or a `Choice`, a multi-select for an `Array` of +options, a date or date-time input. A grid adds no control kind and changes none; a cell is a field with a +smaller frame. + +- **Choices that depend on the row.** A `Choice` field's `x-optionsDependsOn` names members of the same row + first, then the form's top-level fields. The options are fetched when the editor opens and cached by the + values they depend on, so a column of 300 rows over five materials makes five requests. +- **A check box** toggles with `Space` or a click and commits at once; it opens no editor. +- **Nullable numbers** are blank: a blank optional cell is no value and is left out of its row object, as the + forms engine encodes it. `Delete` on a focused cell makes it blank. + +### Entering and leaving + +| Gesture | Effect | +|---|---| +| Typing a character on a focused cell | Opens the editor with that character replacing the value | +| `F2`, `Enter`, double click on an editable cell | Opens the editor holding the value, caret at its end | +| `Enter`, double click on a read-only cell | Runs the table's `onActivate`, as on any table | +| `Enter` in the editor | Commits and moves by `enterMoves` ([Walking](#walking)) | +| `Tab`, `Shift+Tab` in the editor | Commits and walks forward or back | +| Arrow keys in the editor | Move the caret; `Alt+Down` opens a dropdown | +| `Escape` in the editor | Closes it and restores the draft the cell had when it opened | +| Focus leaving the table | Commits | + +A cell that is read-only opens no editor; typing on it says so in the status line. + +### Validation + +- **What was typed stays.** A draft that does not encode keeps its text, draws the error mark and shows the + forms error (`malformed`, `too-precise`, `below-minimum` and the rest) as its tooltip and in the status line + while the cell has focus. No dialog is opened and focus is not held: the user may walk on and come back. +- In a grid of a form the form is not ready while a cell does not encode, as for any field. In a model's table a + cell that does not encode is not committed. +- Rules beyond one value (`x-rules`, instance constraints, the server's checks) report through the form or + through the action's `FieldError`, on the cells they name. + +### Read-only and computed + +A cell is read-only when its field is `x-readonly`, `x-computed` or `x-derived`, a `readonlyWhen` rule holds, +the column's `readonly` overlay is true for its row, its `EditInfo::readonly` companion is true, the column has +no field or no edit action, the row is busy or locked, or the cell is unloaded. A read-only cell: + +- draws on the theme's read-only cell surface, so computed values read as computed; +- is skipped by the walk (`Tab`, `Enter`) and still reached by arrows and by a click, so it can be read, + selected and copied; +- takes no paste and no fill; a pasted value that lands on it is dropped and counted + ([Selecting cells](#selecting-cells-clipboard-and-fill)). + +Read-only, its surface and its place in the walk are one consequence of one fact, so they cannot disagree. + +### What changed + +A cell whose value differs from what the record held when it was loaded draws the theme's modified mark, and its +row's header draws the row's modified mark while any of its cells does. + +- In a grid of a form the comparison is per cell: the forms engine keeps, for each member of each row of an + `ObjectArray`, the draft it held when the form was last loaded, by row key (`FormSession::modified(path)`), as + it keeps a top-level field's. A row added since the load is modified as a whole. `refill` keeps comparing + top-level fields as it does; the per-cell record is what the marks and "Revert cell" read. +- In a model's table a cell is modified from its commit until the window next fetches its row. +- "Revert cell" in the cell's menu restores the loaded value (`FormSession::revert(path)`); "Revert row" restores + the row's. The element values `modifiedCount` and `errorCount` count such cells, and `modifiedRows` the rows. + +## Walking + +- **`enterMoves`**: `down` (the default: a column of measurements is entered top to bottom), `right`, or + `none`. +- **`walk`**: the order `Tab` follows, `rows` (along a row, then the next row; the default) or `columns` (down a + column, then the next column). The walk visits editable cells only, from the view position of the cell it + leaves. +- **The ends.** `Tab` on the last editable cell, and `Shift+Tab` on the first, leave the table to the next or + previous control of the screen's focus chain, so a grid sits in a form like any field. With `appendRows` a + `Tab` on the last cell, and `Enter` moving down from the last row, add a row instead. +- Arrow keys move to any cell, editable or not, and `Ctrl` with an arrow to the last cell in that direction, as + in [`table.md`](table.md#keyboard-focus-and-assistive-technology). + +**What the walk needs from the view tree.** Leaving the table moves focus to another node, which the view tree +cannot do yet: it is why the forms engine lists a grid widget as not supported. The view tree gains a focus +chain in document order and `focusNext`/`focusPrevious` from a node ([Neighbouring specs](#neighbouring-specs)); +step 1 of this design lands it. + +## Selecting cells, clipboard and fill + +A grid selects **cells**: `selectionMode: "cells"` is a rectangle of the view, extended with `Shift` and the +arrows or a drag, and the whole grid with `Ctrl+A`. A row header click selects its row, a column header's +selection gesture its column. It is the default for a grid of a form, and the design allows it on any table held +whole on the client; a model's table, which is in server mode, selects rows, and refuses `cells`. The code lowers +`cells` for a grid of a form only: on a table over `rows` it is refused when the document loads, and lowering it there +is deferred work. + +- **Its value.** `selection` and `onSelectionChange`'s `event` are `{"anchor": {"key", "column"}, "focus": + {"key", "column"}}`, the rectangle's two corners by row key and column id; the rectangle is the rows between + the two keys' view positions and the columns between the two ids' places in the layout. `null` is no + selection. A sort or a column move keeps the corners and so may change the rectangle, as a spreadsheet does. +- **Copy** writes the rectangle as [`table.md`](table.md#copy) writes rows: tab-separated display text. +- **Paste** (`Ctrl+V`) takes tab-separated text and writes it from the focused cell right and down, the block + keeping its shape. Each value is read as the cell's draft, in the user's locale, and encoded by the cell's + field, so a pasted "12,5" in a comma locale is 12.5 and a pasted "abc" in a number column is an invalid draft, + kept. A value that lands on a read-only or covered cell is dropped, and the status line says how many were. + Rows the block runs past are added when `appendRows` allows, up to the field's `maxItems`, and dropped + otherwise, said in the status line. +- **Fill down** (`Ctrl+D`) copies the first row of the rectangle into its other rows, editable cells only. +- **Clear** (`Delete`) blanks the rectangle's editable cells. +- A paste, a fill or a clear in a grid of a form is one change of the form: the round of derived values it + causes is one. + +## Rows of a grid + +A grid of a form adds and removes rows of its field. + +- `appendRows` (a literal flag) adds a row by the walk past the end, and offers "Add row" under the grid. +- The cell's and the table's menus offer "Insert row above", "Insert row below" and "Delete row" (or "Delete + rows" for a selection); `Ctrl+Shift+=` inserts below and `Ctrl+-` deletes, as in a spreadsheet. A deletion + happens at once, with no question first: the status line says "Deleted {n} rows" with "Undo". The offer ends at + the grid's next change (an edit, a paste, a fill, a clear, a revert or a row operation of the grid), or 6 s after + the deletion, the hold of a status-line notice, whichever comes first; once it ends, "Undo" restores nothing. A + derive round, which writes only computed and derived members, is no change of the grid's. +- The field's `minItems` and `maxItems` bound them: the entries are disabled at a bound, and say why. +- `rowsFixed` (a literal flag) offers none of them: the rows are the record's, such as one per sieve of a + standard series. + +Rows of a model's table are added and removed by the application's actions, through its menu entries +([`table.md`](table.md#the-applications-menu-entries)). + +## Layouts + +Each layout here is drawn by the mount and holds for any table it fits, editable or not. + +### Header bands + +```cpp +struct BandInfo { + std::string label; + std::string unit; // shown after the label: "Mass retained [g]"; empty for none + std::vector columns; // the column ids under the band + std::vector bands; // bands one level down, each over a subset of `columns` +}; +``` + +`bands` (`TableDescription::bands`, or the document's parts of the same shape) are headings over columns, +nested up to three levels, drawn above the column headers. A band one level down covers a subset of its +parent's `columns`. A column belongs to at most one band per level. + +- **Units.** A band's `unit` is shown after its label as a column's is, and a column under it whose unit is the + same does not repeat it, so a band "Mass retained [g]" over six sieve columns shows the unit once. +- **Under rearranging.** When the layout keeps a band's columns side by side, the band is drawn once over them. + When the user moves or hides columns so that they are not, the band is drawn over each run of its columns that + stands together, so a band never covers a column that is not its own. A band whose columns straddle the + pinned edge is drawn as two parts, one pinned, one scrolling. +- A band with no visible column is not drawn. A user does not form bands. A column group, user-formed or declared + ([`table.md`](table.md#column-groups)), draws as a one-level heading on its own line below the bands, with its + filter button, over its columns while they stand together; it is not a band, and is not drawn over each run of + its columns. +- A band's accessible name is read before each of its columns' headers: "Mass retained, sieve 4 mm". +- Bands are windowed with their columns: a band exists for the columns in the column window. + +### Spans + +A cell may cover cells beside it and below it. A span part is `{column, rows, columns}`: the cell in `column` +covers `rows` rows, itself included, downwards, and `columns` columns, itself included, to the right in the +layout; either count defaults to 1. + +- A table over rows gives its spans through `rowSpans` + ([`table.md`](table.md#the-document-table-node-on-the-engine)), whose parts take `columns` beside `rows`. A + fixed grid gives them on its cells ([below](#fixed-grids)), as `rows` and `columns` of the cell part. +- A span across a column the user has moved away or hidden is cut at that column. +- Spans are drawn only while the table is unsorted and under its windowing thresholds, as row spans are; a + fixed grid is always both. +- A covered cell is not focused, selected alone, walked or pasted into; the walk passes over it. + +### Summary rows + +`summaries` are parts `{key, label, position, cells}`: rows drawn after the table's rows (`position: "bottom"`, +the default) or before them (`"top"`), outside the order, the filter and the selection. + +- `cells` maps column ids to expressions read in a scope with `rows`, the records of the view's rows in view + order, and `column`: `{"fn": "mean", "args": [{"map": {"ref": "rows"}, "as": "r", "to": {"ref": "r.mass"}}]}`. + The expression language's `count`, `sum`, `mean`, `min`, `max`, `stdev(list, dp, mode?)` and + `rsd(list, dp, mode?)` are the aggregates; its exact arithmetic and its rounding modes are theirs. +- `rows` are the view's rows: a summary follows the filter, so it summarises what the user sees. +- A summary cell shows by its column's display and draws on the theme's summary surface. It is read-only, is + copied when a copy covers it, and is never pasted into. +- **Per group.** A `group` part takes `summaries` too: drawn after each run of the group, in a scope whose + `rows` are that run's. A grid of specimens grouped by sample shows each sample's mean, minimum, maximum and + deviation under its rows, and the table's own summaries under all of them. +- A summary row is a table over held rows' feature: a model-backed table refuses `summaries` and group + summaries, as it refuses `group`. A total over a whole model's table is the application's report. + +### Fixed grids + +Some grids have rows fixed by a standard or a specification, each row a different quantity: rows of tests and +columns of minimum, maximum and declared value; a key-value sheet of a sample's parameters. A **fixed grid** is a +table node with `layoutRows` in place of `rows`, and `form`, the id of the form node whose fields its cells +edit (absent for a fixed grid that shows values only): + +- `layoutRows` are parts `{key, label, cells}`, in order; keys are unique in the grid. `cells` maps column ids to + a cell part: `{field}` (a path of that form's fields, `limits.density.min`), `{value}` (an expression), or + `{text}`, with the column overlays, and `rows` and `columns` for a span. +- Each cell is its own field, so each takes its own kind, places and editor: one row's minimum is a decimal to + three places and the next row's a choice. +- A fixed grid is not sorted, filtered or rearranged by rows; its columns may still be hidden and resized. It + walks, selects, pastes and validates as any grid. +- **Blocks.** A part `{"forEach": "specimens", "rows": […]}` repeats its rows for each row of that + `ObjectArray`, in the block's own scope, where `row` is the specimen and a cell's `{field}` path is relative to + it. A block row's key is the specimen's row key and the part's key joined (`"/"`), so it is + stable while specimens are added and removed. A block of several fixed rows per specimen is one declaration. A + row's `label` is read once for every row of the block, so it does not read `row`; only its cells do. + +## Document vocabulary + +| Key | On | Meaning | +|---|---|---| +| `form`, `field` | `table` | A grid of a form's `ObjectArray` field, in place of `rows` | +| `{"widget": "grid", "grid": {…}}` | a `form` field overlay | The field drawn as a grid, with the table's properties | +| `layoutRows`, with `form` | `table` | A fixed grid, in place of `rows`; `form` names the form its cells edit | +| a column's `field` | grid column | The member the column edits; an expression for one member per row | +| a column's `value` | grid column | A display column's expression in the row's scope | +| a column's `decimals`, `unit`, `readonly`, `options`, `placeholder` | grid column | Overlays per row, expressions in the row's scope | +| `derive`, `deriveDebounce` | `form` | The form's derive action; milliseconds of no commit before a round, default 150 | +| `editMode` | `table` | `cell` (the default) or `row`, for a model's table | +| `enterMoves`, `walk` | `table` | The walk ([Walking](#walking)) | +| `selectionMode: "cells"` | `table` | A rectangle of cells | +| `appendRows`, `rowsFixed` | `table` | Which row operations a grid offers | +| `bands` | `table` | Header bands | +| a span part's `columns` | `rowSpans` part, fixed-grid cell | A span across columns | +| `summaries` | `table`, `group` | Summary rows | +| Element values `modifiedCount`, `modifiedRows`, `errorCount`, `editing` (the cell being edited, `{key, column}` or `null`) | `table` | | + +Every key is optional, and a table that names none of them is what [`table.md`](table.md) describes. + +## Invariants + +1. **One field model.** A cell's draft, encoding, error and bounds are its field's, from the forms engine; a + grid holds no value the form does not. +2. **Typed text survives.** No commit, evaluation, derive reply, refill or change event replaces a draft the + user changed since it was loaded, until that draft is submitted, committed or reverted. +3. **Derived values never run backwards.** A reply older than one already loaded is not loaded, and a loaded + value lands on the row it was computed for or nowhere. +4. **Read-only is one rule.** A cell is skipped by the walk, refuses an edit, a paste and a fill, and draws as + read-only exactly when [Read-only and computed](#read-only-and-computed) says it is read-only. +5. **The record's order is the record's.** Sorting or filtering a grid of a form never changes the order or + the content of the field's array. +6. **No edit of an unseen value.** No edit is committed for an unloaded cell, a busy or locked row. +7. **A paste is its cells.** A paste writes exactly the drafts a user would have typed into the editable cells + under the block, and says how many values it dropped. +8. **A span covers what it says.** A covered cell is never focused, walked, selected alone or pasted into. +9. **The server decides derived values.** A computed or derived member the client sends is never the value the + server keeps. + +## API surface + +| Header | Holds | +|---|---| +| `table/edits.hpp` | `CellEdit` and `x-cellEditOf`, `RowEdit` and `x-rowEditOf`; `checkEdits`; `CellEdits` committing a row's cells as one request in `row` mode, and holding drafts by row key and column, moved by a key change. | +| `table/description.hpp` | `EditInfo` and `TableColumn::edit` (`edits.hpp` includes this header, so `EditInfo` is declared here); `TableDescription::bands` and `BandInfo` ([`table.md`](table.md#api-surface)). | +| `forms/derive.hpp` (new) | `DeriveOf`, `Derived`; the `derived()` field metadata and `x-derived`. | +| `forms/engine` | `FormSession::loadDerived`, the round's debounce, sequence and row-key mapping, over `evaluate` and the derive action; per-cell snapshots of `ObjectArray` rows, `modified(path)`, `revert(path)`; `computedFields` on a row type, recomputed by `recomputeAll`; options of a `Choice` depending on its row. | +| `ui/form_rows.hpp` (new) | `FormRowsSource`: a `DataSource` over an `ObjectArray` field's rows. | +| `ui/grid.hpp` (new) | The cell editor host, the walk, cell-range selection and its value, paste, fill and clear, row operations; summary rows and fixed grids' lowering, with blocks. | +| `ui/view.hpp`, `ui/mount.hpp`, `ui/backend.hpp` | The focus chain and `focusNext` / `focusPrevious`. | +| `ui/interpreter.hpp` | The lowering of a grid, a fixed grid and an editable model column; the keys of [Document vocabulary](#document-vocabulary) and its element values. | +| `ui/view.hpp`, `ui/mount.hpp` | Bands, spans and summary rows in the mount; the read-only, modified, stale and locked cell and row marks. | +| `qt_quick` and the terminal backend | Editors in cells; the marks; bands and spans. | + +## Tests + +| Condition | Test | Layer | +|---|---|---| +| A grid is a form | A grid over an `ObjectArray` of three rows: typing "12,5" in a comma locale gives the body `12.5` exactly; a draft with too many places is kept, marked and keeps the form unready. Mutation: a grid that encodes with its own parser. | `tests/test_ui_grid.cpp` | +| Read-only is one rule (grid) | A computed member, a derived member and a `readonlyWhen` cell are each skipped by `Tab`, refuse typing, drop a pasted value and draw the read-only surface. Mutation: the walk testing `x-readonly` only. | `tests/test_ui_grid.cpp` | +| Read-only is one rule (model table) | An unloaded cell, a busy row, a locked row and an `EditInfo::readonly` cell refuse an edit and are skipped by the walk. Mutation: the busy test left out of the rule. | `tests/test_ui_table_model_*.cpp` | +| The walk | `enterMoves: down` fills a column; `Tab` on the last editable cell moves focus to the next control; with `appendRows` it adds a row; `walk: columns` goes down first; after an edit that moves its row in a sorted model table, `Enter` lands on the row that was below. Mutation: `Tab` wrapping to the first cell, which never leaves the grid. | `tests/test_ui_grid.cpp`; `tests/qt_quick` | +| Derived values | A commit evaluates once after `deriveDebounce` and calls the derive action with the body as far as it encodes; a commit during the round yields one more; computed and derived members load, onto the rows they were computed for after a row was inserted above them, and a member typed meanwhile stays as typed and modified; an older reply is ignored; a failed round marks the cells stale and "Recalculate" runs one more. Mutation: `loadDerived` resolving paths against the current rows, which writes a value onto the wrong row. | `tests/test_ui_grid.cpp` | +| The server decides | A submitted body with a forged computed and derived member: the server keeps `recomputeAll`'s value and the model's. Mutation: `recomputeAll` skipping row members. | `tests/forms/test_forms_derive.cpp` | +| Kind per row | A column whose `field` expression names `choice` for one row and `amount` for the next opens a dropdown and a number input, and encodes each by its own field. Mutation: the column's field resolved once for every row. | `tests/test_ui_grid.cpp`; `tests/qt_quick` | +| Choices per row | Options depending on a row member are fetched once per distinct value. Mutation: a fetch per row. | `tests/test_ui_grid.cpp` | +| Paste, fill, clear | A 3 × 4 block over a read-only column keeps its shape, drops and counts those values, adds rows to `maxItems` and reports the rest; fill down and clear touch editable cells only; one paste is one derive round. Mutation: a paste that shifts values past a read-only cell. | `tests/test_ui_grid.cpp` | +| Cell selection | `selection` is the two corners by key and column; `Shift`+arrows extend it; `cells` on a model's table is refused. Mutation: corners stored as view positions, which a sort moves to other rows. | `tests/test_ui_grid.cpp` | +| Rows of a grid | Insert and delete at `minItems` and `maxItems` are disabled; a deletion removes the rows at once and offers "Undo"; `rowsFixed` offers none. Mutation: bounds unchecked. | `tests/test_ui_grid.cpp` | +| A sorted grid keeps its record | Sorting a grid by a column and editing a row submits the array in its entered order with the edit in place; an added row shows at the end until the sort changes. Mutation: a source that reorders the field's rows. | `tests/test_ui_grid.cpp` | +| Submission | An explicit submit with a cell editor open sends the typed value; a field error `specimens[3].mass` lands on that cell. Mutation: submit before the editor commits. | `tests/test_ui_grid.cpp` | +| What changed | Typing in one cell marks that cell and its row, not its neighbours; "Revert cell" restores the loaded value; a derive reply moves no snapshot. Mutation: a mark per `ObjectArray`, which marks every cell. | `tests/test_ui_grid.cpp` | +| Cells of a model's table | An edit commits through the column's action, is stale until the reply and modified until the row's next fetch, and shows a `FieldError` on refusal; `row` mode commits once when focus leaves the row and a refusal brings focus back to the first refused cell; a second cell of a row whose first edit is saving takes an edit; a draft survives its row scrolling out and back, and follows a `from`; a principal refused the action sees the column read-only. Mutation: drafts held by the window, which loses them on scroll. | `tests/test_ui_table_model_*.cpp`; `tests/net/test_push_tables.cpp` | +| Bands | A band over three columns draws once; moving one away draws it over two runs; across the pinned edge it draws as two parts; hiding all three draws none; the band's unit is not repeated by its columns. Mutation: a band drawn over its first and last column's span, which covers a foreign column. | `tests/test_ui_mount.cpp`; `tests/qt_quick` | +| Spans | A cell spanning two rows and three columns covers them; the walk passes over covered cells; a paste onto a covered cell drops the value; moving a covered column cuts the span. Mutation: covered cells left focusable. | `tests/test_ui_mount.cpp`; `tests/test_ui_grid.cpp` | +| Summary rows | A grid's `mean` and `stdev` follow every committed value exactly and follow the filter; group summaries are per run; a model-backed table refuses `summaries`. Mutation: summaries over the source rows, which ignore the filter. | `tests/test_ui_grid.cpp` | +| Fixed grids | A `layoutRows` grid of four parameters with different kinds per cell walks, pastes and validates per cell; a `forEach` block repeats per specimen with keys that survive inserting a specimen above. Mutation: block keys by position, which move every row's state on insertion. | `tests/test_ui_grid.cpp` | + +## What this does not do + +- **It does not lay out printed reports.** A table drawn on a report page, filled by the report and split across + pages, is a report's design, not an interactive table's. +- **It has no formula cells.** No cell holds an expression a user typed, and there are no references by cell + address. Computation is the server's (computed fields and derived members) or the document's (an expression + column or a summary row). +- **It does not undo.** "Revert cell" and "Revert row" restore the loaded value, a deleted row offers "Undo" + until the next change, and the form's `reset` restores the record; a history of edits is not kept. +- It does not paste into, fill or clear a model's table, which selects rows, not cells: a bulk change of a + model's rows is an action over a selection ([`table.md`](table.md#acting-on-rows)). +- It does not derive values for a model's table on the client: its derived values arrive with the row. +- It does not hold an edited row still in a model's table. +- It does not let a user form header bands. + +## Alternatives considered + +- **A grid with its own cell store**, filled and read back by the screen. Every screen then writes the copy in + and out, the encoding is the screen's, and the dirty state is a second bookkeeping beside the form's. The + form already holds the record. +- **One derive mechanism for both pure and domain values.** A computed field must be pure and is overwritten on + submit; a value from the domain's data needs a model and is the model's to set. Folding both into computed + fields breaks the purity the server relies on; folding both into a derive action makes every form with a sum + declare an action. `evaluate` already serves the pure half. +- **Recomputing on the client by rules in the schema.** A lab computation is the domain's code, with its + standards' rounding, and is needed on the server to save anyway. The server runs it; the document's + expressions cover what is display only. +- **Deriving on every key.** A request per character, and values that change under the cursor while a number is + half typed. A commit is the moment a value is meant. +- **Loading derived values with `refill`.** `refill` keeps or replaces whole top-level fields, and a grid is one + such field: once any cell is typed, every derived member of every row would be kept as it was. Writing only + members the user cannot edit needs no comparison at all. +- **A cell kind chosen by the grid**, overriding the record's type. The same value would then encode one way in + the grid and another in the body. A member per kind keeps the record honest; the grid chooses which to show. +- **Holding focus on an invalid cell**, or a dialog on a refusal. The user loses the place they were going to, + and a dialog per cell turns a column of entries into a column of confirmations. +- **Skipping read-only cells by a per-cell flag.** Separate flags for read-only, its colour and its place in the + walk disagree the first time one is forgotten. +- **Pasting around read-only cells**, shifting values into the next editable cell. The pasted block then lands + in cells it did not come from. +- **Pasting into a model's table, one commit per cell.** Thousands of serial round trips, edits of rows the + client does not hold, and a refetch per change event; a bulk change is an action over a selection. +- **Holding an edited row still in a server-mode table.** The window would show a row at a place the server no + longer reports, which [`table.md`](table.md#invariants)'s window rules forbid; moving the walk by position + gives the entry behaviour without it. +- **Cell-selection corners by view position.** A sort would move the selection onto other rows. +- **Summary rows as rows of the data.** They would be sorted, filtered, selected and submitted. +- **Bands that move columns together.** A user reordering columns would drag several at once without having + chosen to; a band follows the layout instead. + +## Failure modes + +| Situation | Behaviour | +|---|---| +| A draft that does not encode | Kept, marked, its error in the tooltip and the status line; the form is not ready, or the cell is not committed. | +| An evaluation or a derive call fails | Derived cells keep their values, marked stale; the status line offers "Recalculate". | +| A reply arrives after a newer one | Ignored. | +| A derive reply names a path that is not a derived member | That value is dropped and reported once. | +| A column's kind and its edit field's kind differ, or a `member` that `values` lacks | `SourceContract` when the description is built. | +| A column `field` naming no member of the row type | Refused when the document loads; an expression naming none is reported once and the cell is read-only. | +| An edit of an unloaded cell, a busy or a locked row | Refused at the cell; nothing is sent. | +| A `FieldError` or `FailedRow` for an edited cell | The cell keeps the committed draft and shows the message. | +| A paste onto read-only or covered cells, or past the last row without `appendRows` | Those values are dropped; the status line says how many. | +| Insert or delete past `maxItems` or `minItems` | The entry is disabled and says why. | +| `summaries` or a group's summaries on a model-backed table | Refused when the document loads. | +| `selectionMode: "cells"` on a model's table | Refused when the document loads. | +| `editMode` on a table that is not a model's table | Refused when the document loads. | +| A span over a column the user moved or hid | Cut at that column. | +| A band nested past three levels, a band naming no column, a child band over a column its parent lacks, or a column in two bands of one level | Refused where the bands are read. | +| Two `layoutRows` parts with one key | Refused when the document loads. | +| `form` and `rows` both on a table, `layoutRows` with `rows` or `field`, or a `{field}` cell in a fixed grid without `form` | Refused when the document loads. | +| A `layoutRows` key holding a `/`, which joins a block row's keys | Refused when the document loads. | +| `sort`, `group`, `summaries`, `rowSpans`, `appendRows`, `rowsFixed` or `key` on a fixed grid, or `layoutRows` on a model's table | Refused when the document loads: a fixed grid's rows are its parts, in order. | +| A fixed-grid cell under an id the column parts lack, naming none or more than one of `field`, `value` and `text`, or giving `decimals`, `unit`, `options` or `placeholder` with no `field` (`readonly` is taken by any cell); a `rows` or `columns` that is not a literal count from 1; a fixed grid's column part naming a `field` or a `value` | Refused when the document loads. | +| A block without `form` or a block inside a block | Refused when the document loads. | +| A `forEach` that is no list of records of the form, or a `{field}` that is no field of the form (of the row type, in a block) | Refused when the document loads while the catalog has the form action's schema; otherwise reported when the grid is lowered, and the grid drawn as muted text. | +| Two overlays in one document giving one form field different literal units (a fixed-grid cell's `unit`, a grid column's `unit` over the same member) | Refused when the document loads: a field is entered in one unit. Units that expressions give cannot be compared when the document loads, and are not: after each load every grid that gives the field a unit gives it again, in the order the grids' overlay effects run, and the field is entered in the unit the last of them gave, which settles once each has given it; no order among them is promised, and a document should not rely on one. | +| A block row's `label` reading `row` | Refused when the document loads: a row's label is read once, for every collection row. | + +## Neighbouring specs + +This document is the design. The specs below describe the code, so each takes its part when the step that +builds it lands, and until then says nothing of it. + +| Spec | Takes | With step | +|---|---|---| +| [`table.md`](table.md) | Points here for editing; `TableColumn::edit` and `TableDescription::bands` among its members | 1 | +| [`../ui/view_tree.md`](../ui/view_tree.md), [`../ui/backend_contract.md`](../ui/backend_contract.md) | The focus chain and `focusNext` / `focusPrevious` | 1 | +| [`../forms/engine.md`](../forms/engine.md) | The grid widget leaves "Not supported"; per-cell snapshots, `modified`, `revert` | 1 | +| [`../forms/engine.md`](../forms/engine.md) | Rounds of derived values and `FormSession::loadDerived`; `deriveDebounce`; a `Choice` whose options depend on its row | 2 | +| [`../forms/forms.md`](../forms/forms.md) | `computedFields` on a row type, recomputed on every path, as an exception to "computed fields are top-level only"; the `derived()` metadata and `x-derived`, which `recomputeAll` does not touch | 2 | +| [`../core/registry.md`](../core/registry.md) | `DeriveOf` and `Derived`; `evaluate` recomputing row members | 2 | +| [`../ui/document.md`](../ui/document.md), [`../ui/interpreter.md`](../ui/interpreter.md) | The keys of [Document vocabulary](#document-vocabulary) on `table`, `form`, `group` and a field overlay, and their lowering | 1 to 6 | +| [`../qt_quick/backend.md`](../qt_quick/backend.md) | Editors inside cells, the cell and row marks, bands and spans | 1, 4 | + +## Delivery order + +| Step | Lands | Gates | +|---|---|---| +| 1 | The focus chain in the view tree. `FormRowsSource`; a grid of an `ObjectArray` field with the forms editors in cells, validation at the cell, read-only as one rule, the walk, per-cell modified marks, submission. Needs [`table.md`](table.md)'s steps 4, 6 and 9a. | "A grid is a form", "Read-only is one rule (grid)", "The walk" (its grid cases), "A sorted grid keeps its record", "Submission", "What changed" | +| 2 | Derived values: rounds over `evaluate` and the derive action, `loadDerived`, `computedFields` on row types, `derived()`; choices depending on their row; kind and overlays per row. | "Derived values", "The server decides", "Kind per row", "Choices per row" | +| 3 | Cell-range selection, paste, fill, clear; row operations. | "Cell selection", "Paste, fill, clear", "Rows of a grid" | +| 4 | Bands, spans, summary rows and group summaries. | "Bands", "Spans", "Summary rows" | +| 5 | Fixed grids, with blocks per row of an `ObjectArray`. | "Fixed grids" | +| 6 | Cells of a model's table: `CellEdit`, `RowEdit`, `row` mode, stale, modified and refused cells, drafts held by key. Needs [`table.md`](table.md)'s steps 4 and 9b (busy and locked rows, `FailedRow`). | "Cells of a model's table", "Read-only is one rule (model table)", "The walk" (its model-table case) | diff --git a/docs/spec/table/engine.md b/docs/spec/table/engine.md index d3ab205d3..abba57590 100644 --- a/docs/spec/table/engine.md +++ b/docs/spec/table/engine.md @@ -49,10 +49,9 @@ or the reactive runtime. | `filter.hpp` | `FilterEntry`, `Combine`, `ColumnFilter`, `GroupFilter`, `FilterSpec`, `CompiledFilter`, `compileFilter`, `compileFilterGuarded`, `FilterRun` | | `view_change.hpp` | `ViewOp`, `ViewChange`, `diffViews`, `applyViewChange` | | `engine.hpp` | `Engine`, `EngineOptions`, `EngineStats`, `ReorderPolicy`, `ColumnLayout` | -| `query.hpp` | `PageRequest`, `TableQuery`, `Page`, `TotalKind`, `QueryLimits`, `validate`, `escapeLikePattern`, `ApplyOptions`, `PageRows`, `apply`, `QueryPlan`, `planQuery`, `RowsSource`, `PageWindow` | -| `plan_conformance.hpp` | `ModelPage`, `PlanModel`, `ConformanceOptions`, `standardCorpus`, `conformanceFailures` | +| `query.hpp` | `PageRequest`, `TableQuery`, `Page`, `TotalKind`, `QueryLimits`, `validate`, `ApplyOptions`, `PageRows`, `apply`, `RowsSource`, `PageWindow` | | `selection.hpp` | `TableMode`, `SelectionMode`, `Selection`, `TableCounts`, `counts` | -| `edits.hpp` | `EditRequest`, `FieldError`, `EditCommit`, `CellEdits` | +| `edits.hpp` | `EditRequest`, `FieldError`, `EditCommit`, `CellEdits`; a model's table's `CellEdit`, `RowEdit`, `EditCell`, `RowEditRequest`, `RowEditCommit`, `checkEdits` | ## Rows: sources and snapshots @@ -194,6 +193,24 @@ for its lifetime. The initial view is every row in source order. one column stays visible, `reset` restores the defaults, and `rebuild` adopts a new column list keeping what remains. +It also holds what the user forms over the columns, in the same members +`value()` writes and `apply` reads: + +- **Groups.** `formGroup(label, columns)` forms a group of 2 to 16 of the + layout's columns, none already in a user-formed group, and returns its id, + the first of `g1`, `g2`, … no group has (`InvalidSpec` otherwise); + `removeGroup(id)` removes one; `groups()` lists them. Whether the columns + are of one kind is the caller's check: the layout knows only ids. +- **Display units.** `setUnit(column, dimension, unit)` sets the unit a + column shows one dimension in, and `nullopt` clears it; `units()` maps a + column to a unit id per dimension. + +`apply` and `rebuild` fit both as they fit the rest: a column the table lacks +leaves its group and loses its units, a column stays only in the first group +that holds it, a group left with fewer than two or more than 16 columns, or +repeating an earlier group's id, is dropped, and `reset` keeps groups and +units. + ## Execution and threading Every recomputation is a `detail::ViewJob`: a snapshot, the key columns it may @@ -248,7 +265,8 @@ order, then diff) it runs in steps. A job never names the engine. Notifications are coalesced: the first one in an owner turn posts a flush; the flush takes the source's new snapshot and handles everything notified since. -With no owner executor the flush runs inside the notification. +With no owner executor the flush runs inside the notification. `Engine::flush()` runs it at once, for a caller +that changed the source and reads the view in the same turn (a grid of a form, which takes in its rows when it walks). - **Updated** rows are repaired: their keys are rebuilt on copies of the key columns, they are filtered, sorted among themselves and merged into the @@ -297,15 +315,14 @@ edited included; the next repair holds them again. `apply(rows, key, query, options, kinds)` does the same over typed rows and returns a `Page`. Text order is the server's collator; a client in server mode does not re-sort a page. -- A model that holds its rows in a database pages them there: `planQuery(query, columns, limits, mayRead, services, - translatable)` is `validate`, the model's own refusals, the guarded compile and a projection of the compiled filter - into a `QueryPlan` the model translates into its query, and `Page::totalKind` says whether a total is the count or a - lower bound (`AtLeast`). `apply` stays the reference: `conformanceFailures` runs a corpus through `apply` and the - model's translation and reports every disagreement. `compileFilterGuarded` is the one compile step `apply`, - `Engine` and `planQuery` share, so a collator or date parser that throws is `ServiceFailed` in all three. The - design is [`database_pages.md`](database_pages.md). -- `escapeLikePattern` is for a database-backed server that maps `contains` to - SQL `LIKE`: it keeps `%` and `_` ordinary. +- A model whose rows live in a database reads them as a `DataSource`, whole or lazily by column, and the server + sorts, filters, pages and counts them with `apply`; `Page::totalKind` says whether a total is the count or a lower + bound (`AtLeast`). `compileFilterGuarded` is the one compile step `apply` and `Engine` share, so a collator or date + parser that throws is `ServiceFailed` in both. +- A table whose rows are cheap and whose slow columns load later marks the unloaded cells `Unloaded`: an unloaded cell + sorts after the empties, a filter over it is three-valued, and its row is undecided rather than rejected. A column + names the data level its cells need, a query names the columns it shows, and a `Page` says which of its cells are + still coming. The design is [`table.md`](table.md). - `TableError` serialises with its code by name (`"unsupportedOperator"`), so a server returns it as the action's typed error. - `PageWindow` is the client's view of a server-mode table: `visible(first, @@ -352,6 +369,36 @@ patches the row through the `RowPatcher`. With an engine, a row is held (`beginEdit`) from its first commit until its last edit settles. A completion after the `CellEdits` is destroyed is ignored. +`CellEdits(RowEditCommit)` is a model's table's committer, with no patcher and +no engine (`editing.md`, "Cells of a model's table"). `commitRow` sends a +`RowEditRequest`, the cells of one row, through the injected commit; a row's +requests run one at a time in order, and a cell is `stale` while a request +naming it is queued or out. A success marks each cell of the request +`modified` until `rowFetched` says the window fetched the row again, which also +drops the drafts that success sent; a cell still stale keeps its marks, since +the row fetched does not hold its edit yet. A refusal is a list of +`FieldError`s: one whose `column` is a cell's `EditCell::member` (its column +when the member is empty) lands on that cell, one that names no cell of the +request, or nothing, on every cell of the request that no named error reached, +and a cell no error reached takes none. A success settles a cell's draft only +while it is the draft the request was made with: one typed since stays. + +Drafts and their errors are held by row key and column (`setDraft`, `draft`, +`clearDraft`), not by the window: a row that scrolls out and back finds them. +`moveRow` moves a row's drafts, errors, marks and queued requests to its new +key; `rowAbsent` drops them, and the requests not yet sent, for a row a keyed +refetch found gone, while the one out settles unheard; `keepColumns` drops +every column a new description lacks. `errorCount` and `modifiedCount` count +across rows. `onRowSettled` hears each settled request with the row's key and +whether it was refused. + +`checkEdits(description, schemaOf)` checks each column's `EditInfo` against its +action's input schema: the field (`value` of a `CellEdit`, the member of a +`RowEdit`'s `values`) must exist and be of a kind the column's kind is edited +with. `Table..describe` runs it over the schemas the server serves +(`TableRuntime::schemaOf`), and refuses a description that does not pass with +`SourceContract`. + ## Schema integration - A member type with `static constexpr std::string_view schemaMarker() noexcept` @@ -436,6 +483,8 @@ against `wire::decode` both ways. | A reset that removes a sorted or filtered column | That sort key or filter entry is dropped. | | A server query over a bound | `LimitExceeded` (the limit itself is clamped). | | A commit's completion after its `CellEdits` is gone | Ignored; the destructor ended the row's engine edit. | +| A row commit's completion after its row went absent | Settles unheard: no mark, error or draft is left. | +| A column's edit field missing, or of a kind its column is not edited with | `SourceContract` from `checkEdits`; `describe` is refused. | ## Design decisions @@ -457,19 +506,19 @@ against `wire::decode` both ways. - With no worker, a recompute's diff is one owner step (about 30 ms for an insert into 100,000 rows), and applying a `Deferred` repair lays out and - diffs on the owner (10 to 55 ms at 100,000 rows). + diffs on the owner (10 to 55 ms at 100,000 rows). A document's `rows` + table runs its engine this way, in owner steps of 4 ms, so these single + steps are where it can miss a frame. - `RowsSource` cannot name a date column's text format. - There is no `QueryRowsSource` (a source over a `morph::reactive` query's rows, diffing a refetch by key). It is the one header of this module that would include the reactive runtime. -- The document interpreter does not yet lower a model-backed `table` node onto - this engine ([`../ui/interpreter.md`, "Not yet lowered"](../ui/interpreter.md#not-yet-lowered)); - the engine's renderer list model and its mounting measurement belong there. ## Cross-references - `docs/superpowers/specs/2026-10-08-table-engine-design.md` — the program-level design this module implements. +- [table.md](table.md) — the one table every surface uses: descriptions, the pipeline, unloaded cells, caches, configuration and budgets. - [../core/callback_scope.md](../core/callback_scope.md) — the lifetime gate on every completion. - [../core/executor.md](../core/executor.md) — owner and worker executors. diff --git a/docs/spec/table/table.md b/docs/spec/table/table.md new file mode 100644 index 000000000..34f99c6b1 --- /dev/null +++ b/docs/spec/table/table.md @@ -0,0 +1,3672 @@ +# `morph::table` — the table + +Design spec for the one table every surface of morph uses: what a table is, how a model offers one or many, the +single pipeline from a model's rows to the screen, slow columns and the caches that hold them, where sort and +filter run, what a user can configure, and the performance all of it is held to. Read [`engine.md`](engine.md) +first, for the engine this builds on. + +## Contents + +- [Goal](#goal) +- [A table is a description](#a-table-is-a-description) +- [The pipeline](#the-pipeline) +- [Sources](#sources) +- [The client table model](#the-client-table-model) +- [The renderer](#the-renderer) +- [Every surface on the pipeline](#every-surface-on-the-pipeline) +- [The unloaded cell](#the-unloaded-cell) +- [Semantics of an unloaded cell](#semantics-of-an-unloaded-cell) +- [Data levels](#data-levels) +- [Partial pages](#partial-pages) +- [Keyed queries](#keyed-queries) +- [Arrival](#arrival) +- [The window under changes](#the-window-under-changes) +- [Caching layers](#caching-layers) +- [Where sort and filter run](#where-sort-and-filter-run) +- [Configuring a table](#configuring-a-table) +- [Acting on rows](#acting-on-rows) +- [Values with units](#values-with-units) +- [Performance](#performance) +- [Invariants](#invariants) +- [API surface](#api-surface) +- [Tests](#tests) +- [What this does not do](#what-this-does-not-do) +- [Alternatives considered](#alternatives-considered) +- [Failure modes](#failure-modes) +- [Open questions](#open-questions) +- [Neighbouring specs](#neighbouring-specs) +- [Delivery order](#delivery-order) + +## Goal + +The goal is one table implementation, complete and fast, that every surface reuses. Three things define it. + +- **A table is generic.** It is a description a model builds at run time and rows that fit it, not a C++ row + type. Any model can offer a table, or several. +- **One pipeline.** Every surface that shows rows in columns goes through `morph::table`: the same order, the + same filters, the same window, the same renderer. +- **Held to a size.** 100,000 rows and 300 columns, natively and in a browser, with budgets and a benchmark for + every layer. + +### Why one pipeline + +Rows in columns come from four kinds of source: a list of values a document holds, a collection's rows, a +model's table paged by the server, and a typed list action's pages. Each is a source of the one pipeline, and +none has ordering code of its own. + +| What one pipeline gives | Without it | +|---|---| +| One text order on a screen | Two tables side by side order the same text differently, one by a collator's key and one by a fold inside each comparison. | +| A repair when a row changes | A changed row sorts the whole list again, and folds text once per comparison instead of once per row. | +| A window at any size | A screen over a server's pages holds one page, and a header sort orders that page instead of the table. | +| Work off the painting thread where there is one, in bounded steps where there is not | A sort of 100,000 rows blocks the frame it runs in. | +| A table from a description | Every table needs a row struct and an action written for it. | + +`forEach` and `grid` lay rows out without columns, sort nothing and are not tables. + +### Slow columns + +A row can be cheap to read while some of its columns cost a second query per row. Without a way to say "not loaded +yet", a server either holds every page until all of its columns are read, or sends the unloaded cells as empty +cells, which the engine then sorts, filters and counts as real empty values while the client polls for the rest. + +Three things are needed together, because each is useless without the next: a cell state that is neither a value +nor empty; a name on each column for the load it depends on, so a query's columns say which loads it needs; and a +reply that says which of its cells are still coming, with a push when they arrive. + +**The name.** The state is `Unloaded`, and this document says "unloaded cell". `pending` already means "a request +is in flight" on `Engine::pending()`, `PageWindow::pending()`, a cache entry and a `table` element's `pending` +value, which documents read; those keep their name and their meaning. The two are different facts: an unloaded +cell may have no request in flight at all (its level is not wanted, or its load failed), and a table that is +`pending` may hold no unloaded cell. + +## A table is a description + +A table is not a C++ type. It is a **description**, built by a model when it is asked, and rows that fit it. A +model offers no table, one, or many, and what a table's columns are may depend on who asks. + +```cpp +struct TableColumn { + ColumnInfo info; // id, kind, comparator, format, level, dimensions + std::string label; + std::string group; // a declared column group's id, or empty + bool sortable = true; + bool filterable = true; + bool shown = true; // the default visibility + ColumnDisplay display; // how a cell's value becomes its text; see "How a column shows its cells" + std::string tone; // the id of a companion column holding this cell's tone, or empty + std::string tooltip; // the id of a companion column holding this cell's tooltip, or empty + std::optional edit; // the action that edits its cells on a model's table; see editing.md +}; + +struct ColumnGroupInfo { + std::string id; + std::string label; + std::vector columns; // 2 to 16 column ids of one kind +}; + +struct TableCapabilities { + bool keys = true; // keyed queries + bool distinct = true; // distinct values + std::uint32_t maxSortKeys = 8; // set by the framework from `ServedTable::limits` +}; + +struct TableDescription { + std::string id; // unique in the process, across every model: "designs" + std::string label; + std::vector columns; // in the declared order + std::string key; // the id of the column that is the row's key + std::vector groups; + std::vector bands; // header bands over columns: {label, columns, bands} (editing.md) + std::vector levels; // every level a column names, base excluded + std::vector units; // the units its `Measure` columns may hold + std::string rowTone; // the id of a companion column holding each row's tone, or empty + std::string rowLock; // the id of a companion column holding why a row is locked, or empty + TableCapabilities capabilities; + std::string revision; // set by the framework: a hash of everything above +}; +``` + +Everything this design says about a table is said of its description: its levels, its groups, its units, which +columns sort and filter. A client draws a table from the description alone, with no compile-time knowledge of +it. The model leaves `revision` empty; the framework fills it from the description's canonical JSON, so two +descriptions are equal exactly when their revisions are. + +### A model's tables + +A model serves a table by returning what the framework needs to run it: + +```cpp +struct TableContext { + session::Context const& session; // who asks +}; + +struct ServedTable { + TableDescription description; + /// The rows the caller may see, held in memory or read lazily: `apply` runs over it. + std::shared_ptr source; + /// The slow levels, one per level the description names. + std::vector> levels; + /// Whether the caller may read a column; empty allows every column of the description. + std::function mayRead; + /// Names everything about the caller that changes the view beyond the query: the row scope and the + /// collation. Empty when every caller sees the same rows in the same order. + std::string scope; + /// The collator, date parser, custom comparators and unit registry this caller's order uses. + Services services; + QueryLimits limits; +}; + +class DesignModel { +public: + table::ServedTable designs(table::TableContext const& context); + table::ServedTable recipes(table::TableContext const& context); +}; + +BRIDGE_REGISTER_TABLE(lims::DesignModel, "designs", &lims::DesignModel::designs) +BRIDGE_REGISTER_TABLE(lims::DesignModel, "recipes", &lims::DesignModel::recipes, table::rowScoped) +``` + +- The model's function runs per request, on the model's strand, with the caller's session, so a description may + differ by principal: columns a user's country adds, columns a role may not see. It returns shared, immutable + things and is expected to be cheap; the description of a table whose columns do not vary is built once. +- **The framework does the rest**, and none of it on the model's strand. When the function returns, the + framework takes the source's snapshot, and then on the server's table executor + (`ServerConfig::tableWork`, a pool) validates the query against the description and `limits`, finds or + computes the view ([The view cache](#the-view-cache)), reads the level snapshots, builds the reply, and wants + what the reply showed as unloaded. A model writes no paging, sorting, filtering, keyed or distinct-value code. +- **Services are the caller's.** `services` is what makes text order by the caller's locale. Left empty it is the + default `Services`, whose collator orders by code point; a table with text columns that users sort sets a + collator. Two callers with different collators have different `scope`s. +- **The row scope is the model's, and it is applied before the framework sees a row.** `source` holds only + rows the caller may see. Nothing downstream filters rows by principal: a level + cache, the view cache and a reply all work on the rows they are given, which is why a cached value cannot + cross a scope. `scope` names the scope so that callers who see the same rows share a view. +- **What a row scope costs.** A model whose callers all see the same rows returns one shared source. A model + with row scopes keeps one source per scope, built when the scope is first asked for and shared from then on; + `table::scoped(source, keys)` makes one from a shared source and the scope's row keys, without copying a cell. + Building a source per request at 100,000 rows is a full pass per request and defeats the view cache, whose key + holds the source's snapshot. +- **Rows in a database are a source too.** A model whose rows live in a database serves them as a `DataSource` + it reads, whole or lazily by column, and the server sorts, filters, pages and counts them with `apply`. The + database is never asked to order or filter a view: one order on every surface needs one comparator, the + table's, and slow levels, unloaded cells, column groups and values with units are the engine's. +- **A table is always C++ code.** Every table is a registered function of a C++ model; nothing on the server + defines a table from a document or from data alone. What is generic is the table's shape, which that function + decides when it runs. A model's set of table ids is fixed when it is registered; a table's columns are not. + +**Actions per table, made by the registration.** `BRIDGE_REGISTER_TABLE(Model, "designs", …)` registers: + +| Action id | Takes | Returns | +|---|---|---| +| `Table.designs` | `TableQuery` | `GenericPage`: a page, a keyed reply or distinct values, as the query asks | +| `Table.designs.describe` | nothing | `TableDescription` | +| `Table.designs.resolve` | `ResolveRequest` (a `RowSelection` and a `SelectionPolicy`) | `SelectedRows` ([Acting on rows](#acting-on-rows)) | + +**A table id is unique in the process**, not only in its model. The action ids carry the table's id and no +model, and an action id names one action type: the effects registries are keyed by it, and an id registered by +two action types fails every effects lookup of the process. Two models that each register a table `"rows"` +are therefore refused when the registries resolve, with "action `Table.rows` is registered by two action types; +give each its own id". + +One generic action taking a table id in its body was the alternative, and loses on every count that matters: + +- **Authorisation** is per model type and action id. An action per table lets a principal read one table of a + model and not another with the authorizer as it is. +- **The catalog** lists actions; a table per action appears in it, with its effects and the record it holds, + without a second directory of tables. +- **The client's cache key** is the action and its body; an action per table keeps two tables' entries apart + without the cache reading bodies. +- **Effects** are declared per action. + +A typed list action that takes a `TableQuery` and returns a `Page` remains a table: it is the same contract, +read against a description the client builds from the node's columns or the action's view document +([The client table model](#the-client-table-model)), since a client sees an action's request schema and never +its reply's. + +**Changing a row is the application's action.** The registration makes no edit action. A model changes a row +through an action of its own, which declares its effect on the table and returns the keys it changed. A column +whose description names such an action (`TableColumn::edit`) is edited in place with an editor for its kind, +as [`editing.md`](editing.md#cells-of-a-models-table) specifies; the table's own actions change nothing. + +**The table's record.** Each registered table is a keyed record named `.` +(`DesignModel.designs`), registered by `BRIDGE_REGISTER_TABLE` beside the table's actions. A record is +registered under a C++ type, and a table has one: `table::TableOf<&DesignModel::designs>`, a tag type made from +the table's function, which is distinct for each table and is no row struct. The registration specialises it +with the model and the id, so everything that names a table in C++ names its function, and a function no +registration names does not compile as a table. The record is what a client watches, what an action's effects +name, and what a level cache announces. + +Registration options after the function are the record's: + +| Option | Effect | +|---|---| +| `table::rowScoped` | The record is registered with `privateKeys`. Required when callers see different rows: a change event then reaches each watcher without keys, except the writer's own, so no watcher learns the key of a row outside its scope. | +| `table::derivedFrom` | A change of any of the records is a change of the table's record, as for any derived record. | + +A row-scoped table pays for its privacy: an arrival that a level cache announces has no caller, so it reaches +every watcher without keys, and each refetches its visible pages instead of its rows +([The window under changes](#the-window-under-changes)). A table that is not row-scoped sends keys to every +watcher the authoriser admits. + +```cpp +struct ChangedRow { RowId key; std::optional from; }; // `from`: a key the action changed +struct FailedRow { RowId key; std::string message; }; + +/// The rows of one table that an action changed, and those it failed to. Its JSON is +/// {"rows": [{"key": …, "from": …}, …], "failed": [{"key": …, "message": …}, …]}. +template +struct ChangedRows { + std::vector rows; + std::vector failed; +}; + +struct RenameDesignResult { + table::ChangedRows<&lims::DesignModel::designs> designs; +}; + +BRIDGE_REGISTER_EFFECTS(lims::RenameDesign, ::morph::effects::updatesTable<&lims::DesignModel::designs>) +BRIDGE_REGISTER_EFFECTS(lims::ImportDesigns, ::morph::effects::changesTable<&lims::DesignModel::designs>) +``` + +- `changesTable` is a whole-table change. +- `updatesTable` names rows. An `updates` effect is resolved against the action's result: the result walk + matches each slot to a record by its C++ type, and the keys are collected only at the paths where the result + holds that record. `ChangedRows` is that slot. Its walk reports `TableOf` at its `rows` member with + the key member `key`, so the keys of one table are collected as any record's are, and `updatesTable` on + an action whose result has no `ChangedRows` is refused when the registries are resolved. +- **An action that changes two tables returns two members**, one `ChangedRows` per table, and declares both + effects. One untyped list of keys could not say which table a key belongs to. +- `from` and `failed` are what a screen shows of an action's outcome per row + ([Acting on rows](#acting-on-rows)). The walk collects a `from` as a changed key beside its `key`; a failed + row's key is not collected, since the action did not change it. +- Watches, admission, fan-out, coalescing and `announce` are the record machinery's: a table is one more + record. + +**The table's action holds the record opaquely.** Which records an action's result holds is found by walking +the result's type, and a `GenericPage` has parallel `keys` and `rows` arrays, not objects with a key member. So +the registration states that `Table.` holds the table's record with no path. That statement admits a watch +of the record to a principal who may run the action, and tells a client cache that it cannot find rows in the +value: an entry whose record is held opaquely is marked by every change of the record, keyed or not, and +nothing is merged into it ([The client's caches](#the-clients-caches)). + +### Typed rows are a convenience + +A row struct still describes a table, by reflection: + +```cpp +BRIDGE_REGISTER_TABLE(lims::SampleModel, "samples", table::typed(&lims::SampleModel::sampleRows)) +``` + +`table::typed` builds the description from the row type: columns and kinds from its members, labels and +units from its schema, levels and groups from `columnLevels()` and `columnGroups()`, the key from its record. It +serves the rows through a `RowsSource`. Wherever this document shows a typed form (`columnLevels()`, +`LevelLoaded`, `Page`), it is this layer; the contract underneath is the description, the +`DataSource` and the generic page. + +A row type cannot carry a unit registry, which is the application's run-time knowledge +([Measures and the unit registry](#measures-and-the-unit-registry)). A model whose typed table has a +`MeasureValue` member declares one more function, which the framework calls when it serves the table: + +```cpp +std::shared_ptr tableUnits(table::TableContext const& context); +``` + +Its registry resolves the members' unit ids and gives the description its `units`. A typed table with a +`MeasureValue` member whose model declares no `tableUnits` is a `SourceContract` error. + +### Rows on the wire + +```cpp +using GenericRow = std::vector; // one cell per entry of the page's `columns` + +struct GenericPage { + std::string revision; // the description's + std::vector columns; // the columns of each row, in the description's order + std::vector keys; // each row's key + std::vector rows; + // … the members of Page other than `rows`; see "Partial pages" … +}; +``` + +A page of a generic table is row arrays under one header: + +```json +{ "revision": "9f2c", + "columns": ["id", "name", "net", "share", "weight", "dose"], + "keys": [101, 102], + "rows": [[101, "Alpha", [1250, 100], [3, 1000], [3, 10, "kg"], [5, 1, [1, 1000]]], + [102, "Beta", null, null, [200, 1, "g"], [250, 1]]], + "total": 9093, "totalKind": "exact", "offset": 0, + "unloadedRows": [{"index": 1, "levels": ["recipe"]}], + "undecided": 0, "awaiting": [] } +``` + +- `columns` names the columns of each row array: the ones the query asked for + ([Data levels](#data-levels)), in the description's order. `keys` holds each row's key whether or not the key + column is among them, so a reader finds a row without knowing which column is the key. +- A cell is written by its `Cell` alternative: + + | Cell | JSON | + |---|---| + | empty | `null` | + | integer; a date as days, a date-time as seconds | an integer | + | `double`, in a `Number` column only | a number with a fraction or an exponent, so `2.0` and never `2`; NaN and the infinities, which JSON has no number for, as the strings `"nan"`, `"inf"` and `"-inf"` | + | text | a string | + | boolean | `true` or `false` | + | exact value (`Rational`) | `[numerator, denominator]`, scaled to the value's decimal places where that fits: 12.50 at two places is `[1250, 100]`, and a reader takes the places back from a denominator that is a power of ten | + | `QuantityCell` | `[numerator, denominator, [factor numerator, factor denominator]]`: the amount in the cell's own unit and its factor to the column's canonical unit. A factor of 1 is left out, which is also how a plain `Rational` in a `Quantity` column reads. | + | `Measure` | `[numerator, denominator, unit id]`, the unit's string id | + | unloaded | `null`, with the row and level named in `unloadedRows` | + + The column's kind, from the description, says how to read a cell; nothing is guessed from the JSON. The third + element tells a quantity from a measure only as a check, since the kind already does. A cell that does not + read as its column's kind is an invalid cell on the client, as it is on the server. +- An unloaded cell costs nothing per cell: the state is per row and level. +- Every other member is the typed page's, with the same meaning. +- `revision` is the description's. A client holding another revision fetches the description again and resets + its window: the columns changed under it. On a screen the table is mounted again over the new columns, under + the same element state, because a mounted table's columns are set once: it keeps its window, sort, filters + and selection, and loses its realized cells and scroll offset. +- **Why rows and not columns.** Column arrays would be the same bytes. A reply is read by row: a keyed reply + replaces rows, and a reply carries a few rows as cheaply as a page. +- **Size.** A row object repeats every column's id, which is most of the 21 bytes a cell costs in a typed page. + Row arrays drop them (W5), and a query that names the forty columns in or near view instead of all 300 + carries an eighth of the cells (W1). +- A typed table served through `table::typed` is written in this form, its cells read by the row's cell + readers. + +### A table on the server + +- **A `DataSource` per table and scope.** The engine and `apply` take a `DataSource` and `ColumnInfo`s and need + no row type; a generic table is that, with nothing in between. +- **Level caches** are keyed by table record, level and row key. Two tables of one model that show the same + rows, by the same key, share one cache: the cache names both records (`LevelCacheOptions::records`), is + invalidated by a change of either, and announces an arrival on both. One load serves both tables. +- **Announcing and invalidating** are by table record, with the row keys of that table. +- **A table whose columns depend on the session** builds its description in its function. Its rows may be one + `DataSource` with every possible column, narrowed by `mayRead`. The level caches hold raw values for a column + list that does not depend on the caller ([The server level cache](#the-server-level-cache)) and are shared. + +### How a column shows its cells + +A cell crosses the wire as its exact value; the client turns it into text, in the session's locale, by the +column's display. Order, filters and distinct values always use the exact value, never the text. + +```cpp +/// The expression language's two modes and names (`"halfEven"`, `"halfUp"`), so a value a document rounds and +/// the same value a column shows agree. +enum class Rounding : std::uint8_t { + HalfEven, // 0.125 at 2 places is 0.12 + HalfUp, // half away from zero: 0.125 at 2 places is 0.13, the rule most test standards prescribe +}; + +struct ValueLabel { + std::string operand; // a value as a filter entry takes it: "true", "3", "V" + std::string text; // what the cell shows for it +}; + +struct ColumnDisplay { + /// Places shown for an `Integer`, `Decimal`, `Quantity` or `Number` cell. Absent shows the value's own places + /// (a `Rational`'s declared places, a `double`'s shortest round trip). + std::optional decimals; + Rounding rounding = Rounding::HalfEven; + /// With `decimals`, whether fewer places are padded with zeros: 2 places shows 1.5 as "1.50". + bool padPlaces = true; + /// Digit grouping by the locale: 12,500. + bool grouping = false; + /// What an empty cell shows: "–", "n/a". Empty shows nothing. + std::string empty; + /// The unit of a plain numeric column, shown in its header; a `Measure` column's units are its cells'. + std::string unit; + /// A `Date` or `DateTime` column's pattern; empty takes the session's. + std::string date; + /// Text for particular values: codes, booleans in words. A value no entry names shows as `decimals` says. + std::vector labels; +}; +``` + +- **Where it is formatted.** On the client, by `ui::formatCell(cell, column, format)`, the one function every + backend, the copy, the status line and the filter menu call. `format` is the session's `ui::FormatContext`, + which carries the locale's numbers, its date patterns and the display zone. The server sends no text for a + value it can send exactly; a model that formats on the server sends a `Text` column, which then sorts and + filters as text. +- **Rounding is for showing.** 0.125 shown at two places under `HalfUp` is "0.13", and a filter + `eq 0.13` does not match it: the filter compares the exact value. A filter menu's condition field accepts + more places than the column shows for that reason. +- **The values list** formats each `DistinctValue` by the column's display. Two values that show alike (0.124 + and 0.123 at two places) stay two entries, because ticking one must not match the other; the menu shows the + value's full places for entries whose texts collide. +- **`labels`** change the text and nothing else. A column of `Bool` shows "available" and "not available", and + its values list shows those texts; it still orders false before true. Ordering by a label's text is a `sortBy` + over a column that holds it. +- **Empty, unloaded and invalid differ on screen.** `empty` is shown for an empty cell only. An unloaded cell + draws its placeholder ([Cells](#cells)), an invalid one an error mark whose tooltip says the value could not be + read. +- **A `Measure` column** shows each cell in its unit and to that unit's decimals ([Display](#display)), so + `decimals` and `unit` on it are a `SourceContract` error. +- **The header** shows `unit` after the label, as the backend draws a unit ("Mass [kg]" or the unit on a second, + muted line); the header's accessible name is "Mass, kg", and "Copy with headers" writes "Mass [kg]". +- **A document's column parts** `decimals`, `rounding`, `padPlaces`, `grouping`, `empty`, `unit`, `date` and + `labels` override the description's for that column, and are the only source on a table over `rows`. + +**Tone and tooltip.** A cell may carry a tone (`neutral`, `info`, `ok`, `warn`, `err`) and a tooltip, and a +row a tone. A model that decides them names **companion columns**: ordinary `Text` columns of the description, +usually `shown: false`, whose cell for a row is the tone's name or the tooltip's text. + +- `TableColumn::tone` and `tooltip` name a cell's companions, `TableDescription::rowTone` the row's. A + companion that names no column, or one that is not `Text`, is `SourceContract`. +- **They travel with their column.** A query that names a column names its companions too, and one that draws + any row names the `rowTone` companion, so a tone or a tooltip costs a cell of the rows in view and nothing for + columns out of the window. A companion may have a level, which makes an expensive tooltip a `display` level + loaded for the rows in view only. +- **A document overrides them.** A column's parts `tone` and `tooltip` are expressions in the row's scope; the + node's `rowTone` is one already. They win over the description's companions, whose columns are then not + fetched for them. A range rule ("weight ratio above 0.5 is `err`") is one of these two places: the model's + companion or the document's expression. The description holds no rule language of its own. +- **Drawing.** A cell with a tone is tinted with the theme's tone surface, and keeps its selection and focus + marks over it. A tooltip shows on hover after the theme's delay and on keyboard focus at once, and is the + cell's accessible description. A cell with a tooltip draws the theme's mark for "more here", so a user knows to + hover. +- **Companions are not columns a user arranges.** A column that the description names as a `tone`, `tooltip`, + `rowTone` or `rowLock` companion is never shown and is not listed in the column chooser or the header menus; + it sorts and filters only where its own `sortable` and `filterable` say so, through a document's `sort` or + `filters`. +- **An unknown tone name** shows no tone and is reported once for the column, as `rowTone` is. +- **A locked row.** A row whose `rowLock` companion holds text is locked: it draws the theme's locked hatch, its + text is the row's tooltip ("Being edited by another user"), and it takes no cell edit + ([`editing.md`](editing.md)). It can be selected and copied; whether an action accepts a locked row is the + action's rule, and a `FailedRow` says so when it does not. + +## The pipeline + +```text + in-document rows a collection's rows a model's table + (a list of values) (the session's reply) (description; TableQuery → GenericPage) + │ │ │ + ValueRowsSource VectorSource ViewCache, LevelCache, apply ← server + │ │ │ pages, keyed rows, change events + └────────── table::Engine ───┘ PageWindow ← client + (client mode: sort, filter, (server mode: the pages around + repair, off-thread where possible) the visible rows) + │ │ + └──────────────── TableRows ───────────────┘ + rows by view index, counts, changes + │ + the mount: realizes rows and columns in view + │ + MorphTable (Qt Quick), the terminal table +``` + +There is one of each stage. A surface chooses a source; the action's shape chooses the mode +([Where sort and filter run](#where-sort-and-filter-run)); everything below `TableRows` is shared. + +## Sources + +- **`ValueRowsSource`**, in the UI layer, is a `DataSource` over a document's list of values + ([below](#a-documents-rows-as-a-source)). +- **`VectorSource`** holds a collection's rows, as [`../forms/engine.md`](../forms/engine.md) specifies. +- **A model's table** ([A table is a description](#a-table-is-a-description)) is the server-mode source: its + `Table.` action takes a `TableQuery`. The framework answers through `apply` over the table's `DataSource`, + or through a translated plan; a slow level is served from a `LevelCache`. + +### A document's rows as a source + +`ValueRowsSource` turns a list of document values into typed cells, and turns a change of the list into the +smallest row changes. + +- **Columns are built when used.** The source has a column for each column of the node that can be sorted or + filtered, and builds a column's cells only while the column is in the sort chain, has a filter, or has a + values list open. A column no one uses holds no cells, so a table of 300 filterable columns is not held + twice. A column's cells are dropped when its last use ends. +- **A cell is a derived value.** A column's cell for a row is the column's `sortBy` evaluated in the row's + scope, or the row's field of the column's `id`. Each is a tracked computation: when the row, or anything else + its `sortBy` reads, changes, that cell is derived again and the source notifies `Updated` for that row alone. + A change to what one `sortBy` reads for every row derives the column again and notifies `Reset`. +- **A new list is matched by key, then by cell.** A row whose value is the same object as before is kept + without being read. A row whose value is another object (a refetched list shares no storage with the previous + one) has its cells of the columns in use derived and compared with the cells held, and is `Updated` only when + one differs, or when the row's value differs in a field no column in use reads: what the table shows of the + row is then read again, and the row keeps its place, since its keys did not change. The cells compared are those + of the columns in use, so deriving costs rows times columns in use, never rows times fields; a row's value is + compared whole only when its cells are equal. Keys the previous list lacks are `Inserted`, keys the new one lacks + are `Removed`; a list that both adds and drops keys, or reorders the rows it keeps, is a `Reset`. +- **Kinds.** A column part's `kind` (a literal: `text`, `integer`, `decimal`, `number`, `date`, `dateTime`, + `bool`) decides the column's kind. Without it the kind is inferred from every non-null cell of the column: + all integers is `Integer`; integers and exact decimals together is `Decimal`, an integer being an exact + decimal; all timestamps is `DateTime`; all booleans is `Bool`; all text is `Text`. Any other mix + takes the kind of the first non-null cell, `Decimal` when that is an integer and a decimal is among the cells, + and a cell not of that kind is invalid: it sorts last and is reported once at the `sort` path. So integers, + decimals and one text are a `Decimal` column with one invalid cell, and a text followed by numbers is a `Text` + column whose numbers are invalid. A change that alters the inferred kind is a `Reset` of that column. +- **`Number` only by name.** A document value holds no `double`: a number with a fraction that reaches `rows` + through the query cache is already an exact decimal. So inference never yields `Number`, and a column is + `Number` only through a literal `kind: "number"`. +- **Timestamps to the second.** A timestamp becomes a `DateTime` cell of whole seconds, rounded down (toward + negative infinity, so −1 ms is −1 s), as a model's `DateTime` column holds it. Two timestamps within one second + tie and keep their source order, so a `rows` table orders them as a model's table does, where the expression + language's `sort` orders them to the millisecond. +- **Text order.** The source orders text with a collator whose sort key is the default collator's fold followed + by the text itself, which is the expression language's order for text: case-folded first, then by its own + bytes. `null` is an empty cell and sorts last in either direction, as the expression language's `sort` places + it. +- It keeps each row's value beside its cells for the row's scope. +- **Groups.** A grouped table's runs are adjacent rows whose `by` is the same element as the run's first row's, as + the interpreter's `group` and `runs` compare them: numbers by value (`1`, `1.0` and `1.00` are one run, a + quantity equals one of another unit that converts to it), lists and records element by element, `null` only + `null`. A run's key is its first row's `by`. A run whose heading record changed while the runs kept their places + is an `Updated` of its first source row, so its heading is read again. + +## The client table model + +`ui::TableRows` is what the mount reads, whatever the source: + +```cpp +using SortChain = std::vector; + +struct TableTotal { + std::int64_t rows = 0; + table::TotalKind kind = table::TotalKind::Exact; + bool known = false; // false until a server-mode table's first reply +}; + +struct TableRowRef { + table::RowId const& key; + /// The row as a record keyed by column id. A field is read from the held cell when it is asked for. + Value const& row; +}; + +struct TableCountsView { + TableTotal view; + std::optional source; // rows before the filter, where the model knows it + std::int64_t undecided = 0; + bool pending = false; // a sort, filter or fetch is in flight + std::vector awaiting; // levels the order still waits for + std::vector failed; // levels whose load failed for a row the table shows or orders by +}; + +class TableRows { +public: + virtual ~TableRows() = default; + [[nodiscard]] virtual TableTotal total() const = 0; + /// The row at a view index, or nothing while it is not fetched. + [[nodiscard]] virtual std::optional row(std::int64_t index) const = 0; + /// The levels not loaded for the row at a view index, and which of them failed. + [[nodiscard]] virtual table::UnloadedLevels unloadedLevels(std::int64_t index) const = 0; + /// Tells the model which rows and which columns are in or near view; a server-mode model fetches them. + virtual void visible(std::int64_t first, std::int64_t count, std::span columns) = 0; + /// The keys of a range of view rows, for a range selection; completes when every key is known. + virtual async::Completion, table::TableError>> + keysOf(std::int64_t first, std::int64_t count) = 0; + /// Where the row with a key is in the view, fetched or not: its view index, or nothing when the view lacks it. + virtual void locateRow(table::RowId key, std::stop_token stop, std::function done) = 0; + virtual std::expected setSort(SortChain sort) = 0; + virtual std::expected setFilter(table::FilterSpec filter) = 0; + [[nodiscard]] virtual TableCountsView counts() const = 0; + /// Called after the rows changed, with the operations that turn the old view into the new one. + virtual void onChange(std::function handler) = 0; +}; +``` + +- **`EngineRows`** wraps an `Engine` over a `ValueRowsSource` or a `VectorSource`. Every row is present; + `visible` does nothing; `keysOf` completes at once, and `locateRow` answers from the engine's view; a change is + the engine's `ViewChange`. +- **`WindowRows`** wraps a `PageWindow`, the table's description and the session. `visible` returns fetches, + which it sends through the session's read that makes no cache entry; replies go to `accept` and `patch`; the + table record's change events go to `refresh` and `invalidate` + ([The window under changes](#the-window-under-changes)). A change is the diff of the rows it held against the + rows it holds, by key. `locateRow` is a keyed fetch naming no columns, whose reply's `indices` give the row's + view index: a reply with no row says the view lacks the key, and one that holds the row without its index is + `InvalidValue`, an answer the rows could not give, not an absence. It owns the two timing rules the window itself has no clock for: when a fetch is sent + while the user scrolls, and how often an awaited order is fetched again. + +The mount's windowing, which decides the realized rows and columns of a large table, calls `visible` with both +ranges. The mount applies a `ViewChange` to its keyed rows as it applies a new list, so a row keeps its widget, +its native state and its selection when it moves. + +**A row is a lazy record.** A document reads a row as `row.name`, whichever way the table is served. In server +mode the record is a view over the row's held cells: reading a field converts that one cell, so a row of 300 +columns of which twenty are drawn converts twenty cells. + +**Which columns a table fetches.** A server-mode table asks for the columns it draws and the columns its +expressions read: + +- the columns in the renderer's column window ([The renderer](#the-renderer)); +- for each of those, the columns its `cell`, `tone` and `tooltip` expressions read as `row.`, found when the + document loads, or, where the document gives none, its `tone` and `tooltip` companions + ([How a column shows its cells](#how-a-column-shows-its-cells)); +- the columns `rowTone` (or the description's `rowTone` companion), `rowLabel`, `onActivate` and the table's menu + entries read, for every row; +- every column, when an expression reads the row in a way the loader cannot follow (`row[name]`, or the row + passed whole to a function); the loader reports that once as a warning naming the node, since it turns the + column window off for the wire. + +A field read of a column the window does not hold for that row reads as absent and asks the window for the +column, so an expression the loader misjudged costs a fetch and not a wrong value. + +A model-backed `table` node names a `model` and a `table` (the table's id), or a `model` and the `action` of a +typed list action. It lowers to a `WindowRows`: the description comes from the table's `describe` action, +through the query cache, and gives the node its columns, so a node that declares no `columns` shows the table +as described, and one that declares some lays those out and takes the rest of each column from the +description. Its `body` is the query's fixed part, its header sorts and its `filters` set the query's `sort` and +`filters`, and `highlightKey` is a keyed query for that row's view index. A typed list action is read into the +same window, and its description is built on the client, because a client's catalog holds an action's request +schema and never its reply's: the columns are the node's `columns` parts, or else the `v-columns` of the +action's view document, with the key from the node's `key`, the view document's `v-rowKey`, or `id`. A column's +kind is the node part's literal `kind`, else the view document's, else inferred from the first reply's rows and +then fixed for the window's life. The query is written into the request's one member marked `x-table`. A node +whose action has no such member, or which has neither `columns` nor a view document, is refused when the +document loads. The reader turns each row object into cells; it returns whole rows whatever `columns` says. + +## The renderer + +A table realizes a widget only for cells whose row and whose column are in or near view. Both windows are the +mount's, so every backend has them: Qt Quick's `MorphTable` and the terminal's table draw what the mount +realizes. + +### When a table is windowed + +```cpp +struct Virtualization { + std::size_t threshold = 2000; // rows: at or above it, rows are windowed + std::size_t overscan = 10; // rows kept realized beyond the visible range, each side + std::size_t columnThreshold = 40; // visible columns: above it, columns are windowed + std::size_t cellThreshold = 20'000; // rows × visible columns: above it, both are windowed + std::size_t columnOverscan = 4; // columns kept realized beyond the visible range, each side + std::size_t realizePerFrame = 240; // cells created or rebound in one frame at most +}; +``` + +A table under all three thresholds realizes everything, as a short table does. A table of 1,999 rows and 300 +columns is over `cellThreshold` and is windowed both ways; without that bound it would realize 600,000 cells. +A server-mode table is always windowed by rows. + +### The column window + +- **Which columns.** The pinned columns ([Columns](#columns-order-visibility-pinning-width)), then the visible + columns that intersect the horizontal viewport, then `columnOverscan` columns each side. The window runs over + the visible columns in layout order. +- **Extents live in the mount.** The mount holds each visible column's width and the running sum of their + offsets (`ColumnExtents`). Finding the columns at a scroll position is a binary search, and a backend is given + the offsets and widths of the columns in the window and the total width. No per-frame work reads every + column. +- **Widths.** A column's width comes from its header, its declared width, and the cells measured while it was + in the window. As for rows, a windowed table's content widths only grow; a width the user set does not change. A + stretch column is the exception: its width follows the table's viewport and the widths measured so far by the + rules of the backend contract's "Table cells", so it narrows as well as widens. +- **Anchoring.** When a column to the left of the first fully visible unpinned column grows, the horizontal + scroll offset grows by the same amount in the same frame, so the columns in view do not move. +- **The header is windowed too.** A header cell and a group heading exist for the columns in the window only. +- **A hidden column has no header, no width and no cells.** + +### Cells + +- **Recycling.** A cell that leaves either window goes to a pool and is rebound to the next cell that enters. + Cells drawn by the default cell of one role share a pool, whatever their column; a column with its own + `cell` template has a pool of its own. A row that scrolls in therefore creates no widgets once the pools are + warm, and a column that scrolls in rebinds the cells of the column that left. +- **A frame's budget.** One frame creates or rebinds at most `realizePerFrame` cells. Cells beyond it draw as + blank placeholders of their column's width and are realized over the following frames, nearest the centre of + the viewport first. A fling or a drag of the scroll thumb therefore passes over placeholders and never waits + for realization; rows the view only passes are not realized at all. +- **Row height.** A row's height is the tallest its realized cells measure, and does not shrink when the + column window moves: a wrapped cell that scrolls in sideways may make its row taller, and one that scrolls out + does not make it shorter. Measured again in the same window, a row takes what it measures. A row that leaves the row window forgets its height; an unrealized row + counts as the mean of the measured heights. When a row above the first visible row grows, the vertical offset + grows with it. A table whose columns all have `wrap: false` has one row height and skips the measurement. +- **A row not fetched yet** draws as a placeholder row of the estimated height. +- **An unloaded cell** draws a placeholder of a fixed width in its column's alignment. A cell whose level + failed to load draws an error mark with the same width, and the status line offers "Retry" + ([The status line](#the-status-line)). +- The levels a server-mode table asks for are those of the columns it fetches + ([Data levels](#data-levels)), so a level shown only far to the right is not loaded until the user scrolls to + it. + +### Keyboard, focus and assistive technology + +Windowing must not change what a keyboard or a screen reader can reach. + +- **Focus is a row key and a column id**, not a widget. The focused cell's row and its column stay realized + while the table has focus, whatever the windows: one row and one column beyond them at most. When the focused + row leaves the view, focus moves to the row now at its view index, or the last row. +- **Keys.** Arrows move the focused cell; `Home` and `End` go to the first and last visible column of the row; + `Ctrl+Home` and `Ctrl+End` to the first and last row of the view; `Page Up` and `Page Down` move by the rows + in view. `Ctrl+A` and `Shift` with the arrows select as they do on a short table. +- **Over rows not fetched.** Moving to a view row the window does not hold moves focus to that index: the + window fetches it, the placeholder row holds focus and is announced as loading, and the row takes the focus + when it arrives. With a total that is a lower bound, `Ctrl+End` goes to the last row known. +- **Counts.** The table reports its row count as the view's total when that is exact and as unknown when it is + a lower bound, and its column count as the visible columns. Every realized row and cell reports its view row + and its column's place in the layout, so "row 5,012 of 9,093" is read out although fifty rows exist. +- **Range selection in server mode.** A backend that selects a range itself needs every key in row order + (`setExistingKeys`), which a server-mode table does not have. There the backend reports the gesture as two + view rows and the lowering resolves it through `TableRows::keysOf`: rows the window holds give their keys, + and the rest are fetched as pages that name no columns, which carry keys alone. A range of more than + `SessionOptions::maxRangeRows` (10,000) rows is refused with a message in the status line. `Ctrl+A` selects + the view as a whole ([Acting on rows](#acting-on-rows)), which needs no keys. +- **Selection in server mode** is a set of keys, or the view less a set of keys. A set of keys is not pruned by + the filter, which the client cannot evaluate; `selectedCount` counts the keys, or the view's total less them. + +## Every surface on the pipeline + +Every surface that shows rows in columns is on the pipeline. + +| Surface | On the pipeline | +|---|---| +| A document `table` over `rows` | `ValueRowsSource` → `Engine` → `EngineRows`. | +| A document `table` over a model's table (`model` and `table`) or a typed list action (`model` and `action`) | The description from the catalog's `describe` action, rows through a `PageWindow` as `WindowRows`. | +| A forms `collection` or `master-detail` | Its `VectorSource` feeds an `EngineRows` through the same table lowering. | +| A `rows` table bound to a typed page's `rows` | A client-mode table over one page, on the query cache; declared as model-backed it gets a window. | +| `PageWindow` | The server-mode client cache of every model-backed table. | +| `forEach`, `grid`, the expression language's `sort` | Not tables. | + +### The document `table` node on the engine + +Each property of the node, and where it is served. "Rows table" is a table over `rows`; "model-backed" is one +over `model`. + +| Property | Served by | Notes | +|---|---|---| +| `rows` | `ValueRowsSource`, matched by `key` | A changed row is repaired, not sorted again. | +| `model` with `table` or `action`, `body`, `mode` | `WindowRows`, over the table's description | `table` is the id of one of the model's tables. | +| `columns` on a model-backed table | The description's columns, overridden per id by the node's parts | Optional there: absent, the table shows what its description says. | +| `columns`, `cell`, `role`, `align`, `valign`, `width`, `wrap`, `shrink`, a column's `kind` | The mount and the backend; `kind` by `ValueRowsSource` | Cells exist for columns in the window only. | +| `sort`, `sortable`, `sortBy`, `onSortChange` | `TableRows::setSort`; `sortBy` is the column's cell. `Shift`+click and the header menu build a chain ([Sort chains](#sort-chains)) | Values of one kind order as the expression language orders them. A cell not of its column's kind is invalid, sorts last and is reported once at the `sort` path. | +| `pageSize`, `page` | A slice of the engine's view | Refused on a model-backed table, whose window pages. | +| `group` (`by`, `heading`) | The run index is a hidden leading sort key computed by `ValueRowsSource`; headings are placed by the lowering after paging | Rows table only. | +| `rowSpans` | The lowering, on the page's rows | Drawn only unsorted and below the windowing thresholds. Rows table only. | +| `selectionMode`, `selection`, `onSelectionChange`, `selectColumn`, `selectAllLabel`, `rowLabel` | The lowering, by key; select-all selects the view through `Selection::selectAll` | A model-backed table has ranges through `keysOf`, and its select-all is a selection of the view ([Acting on rows](#acting-on-rows)). | +| `cellMenu`, `headerMenu`, `retainChanged`, `headerEnabled`, `maxSortKeys` | The lowering ([Acting on rows](#acting-on-rows)) | Served on every table; `retainChanged` has no effect on a table that cannot retain ([Rows an action changed](#rows-an-action-changed)), and `maxSortKeys` is a `rows` table's only. | +| A column's `decimals`, `rounding`, `padPlaces`, `grouping`, `empty`, `unit`, `date`, `labels`, `tone`, `tooltip` | `ui::formatCell` and the mount ([How a column shows its cells](#how-a-column-shows-its-cells)) | Override the description's per column. | +| `rowTone`, `onActivate` | The row's scope | Their columns are fetched for every row. | +| `empty` | Shown while the view is empty | On a model-backed table it waits for the first reply, and is not shown while rows are undecided. | +| `filters`, `onFiltersChange`, a column's `filterable` | `TableRows::setFilter`, as a `FilterSpec`; set from the header menu ([Filters from the header](#filters-from-the-header)) | Served on every table. | +| `layout`, `onLayoutChange`, `configurable`, a column's `locked` | `ColumnLayout` ([Columns](#columns-order-visibility-pinning-width)) | Every table has the header and table menus unless `configurable` is `false`. | +| `status` | The status line ([The status line](#the-status-line)) | A literal: `true`, `false`, or absent for the default. | +| `persist` | The table's persisted state ([Persisted state](#persisted-state)) | A literal. | +| `highlightKey` | A keyed query for the row's view index, then `visible` around it | Model-backed only. | +| Element values `selection`, `selectedCount`, `sort`, `viewCount`, `pending`, `page`, `pageCount`, `pageFirst`, `pageLast` | `TableRows::counts` and the page slice | On a model-backed table `viewCount` is the reply's total, with `viewCountKind` (`exact` or `atLeast`) and `undecided` beside it. Every table has `layout`, `visibleColumns`, `hiddenCount`, `filters`, `awaiting`, `failed`, `selectionSet` and `busyCount` ([Acting on rows](#acting-on-rows)). | + +A document that uses none of `layout`, `status`, `persist`, a column's `kind` or `locked` loads and orders as it +does without them, with two visible differences that are intended: its tables have header and table menus, and +a table with a state store restores its arrangement. + +The engine's additions for configuring a table are `oneOf`, `distinctValues`, and widths and pinning in +`ColumnLayout`. Everything else is in the UI layer: `ValueRowsSource`, the two `TableRows`, and the lowering +that reads them. + +### Collections and master-detail + +A `CollectionSession` keeps its rows in a `VectorSource` and leaves sorting, filtering and selection to the +engine. Its list is an `EngineRows`, and a `collection` or `master-detail` node lowers its table through the +same lowering as a document `table`, so the interpreter draws a collection's rows with the table every other +screen has. The chrome around the table (header, confirm, editor) is its own lowering and is not part of this +design. A collection is always in client mode: its `v-query` is executed with an empty body and its rows arrive +whole. A collection too large for that is a model's table shown by a `table` node. + +### Screens over a server's pages + +A screen that binds a `rows` table to a `Page`'s `rows` shows the page the query fetched, as a client-mode +table over those rows: a header sort orders the page. To get a window, a header sort that orders the table and +row fetches on arrival, it declares the table with `model` and `table` or `action`. The framework does not +guess that a `rows` expression is a page: an expression can be anything, and a table that changed mode because +of the shape of an expression would be the surprise this design removes. + +### What the interpreter does for a table + +The interpreter does not sort, filter or page a table. It builds the node's `TableRows`, reads rows from it by +view index, and does what is the document's around them: group headings, row spans, selection across pages, the +status line and the element values. The order of a table is the engine's on every surface. The expression +language's own `sort` function is not a table and orders as it does. + +## The unloaded cell + +`Cell` has an alternative for a value that is not loaded: + +```cpp +/// A cell whose value is not loaded yet. It is neither a value nor empty. +struct Unloaded {}; + +using Cell = std::variant; // `Measure`: see "Values with units" +``` + +`CellState` has `Unloaded`, after its other values. `KeyColumn::read` maps an `Unloaded` cell to +`CellState::Unloaded` before +it looks at the column's kind, so every kind treats it alike, and stores no key for it. + +Why a cell alternative inside the engine: + +- **No second call to forget.** A cell is read only through a `RowSnapshot`, as a `Cell`. An unloaded state carried + in the `Cell` reaches key building, `Engine::cellAt` and a renderer on a `DataSource` together with the value's + absence. +- **Atomic with the snapshot.** A snapshot is immutable; a cell and its "loaded" state cannot disagree across + threads when they are one object. +- **Arrival needs no new source API.** A level arriving is the row's cells changing from `Unloaded` to values: + `VectorSource::updateRow` or `RowPatcher::patchRow`, a new snapshot sharing every other chunk, and + `RowChange{Updated}`. `TableSnapshot`, `VectorSource`, `RowPatcher`, `ColumnSink` and `ChangeKind` are unchanged. +- **Finer than a level when needed.** A level is the unit of loading, but nothing forces every cell of a level to + arrive together. + +Cost: every reader of `Cell` must know the alternative. `Cell` does not grow (an empty struct is smaller than +`QuantityCell`), and placing `Unloaded` after the existing alternatives keeps every one's index. `displayText` +is the one `std::visit` over a `Cell`; its last branch formats the value, so the new alternative does not compile +until it has a branch. + +**The wire is a second channel.** A page says which cells are unloaded beside its rows, per row and level +([Partial pages](#partial-pages)): a generic page holds `null` in an unloaded cell, and a typed row holds whatever +the server left in the member. A table node reads the page through a window, which always reads `unloadedRows`. +A reader that takes a typed page's `rows` and nothing else shows an unloaded member as empty; that is left as a +stated limit of typed pages read outside a table, because closing it means changing every row type +([Alternatives](#alternatives-considered)). + +## Semantics of an unloaded cell + +### Unloaded cells in the order + +`compareKeys` ranks a cell before it compares keys: valid first, then empty and invalid (which tie), then unloaded +(which tie). The rank ignores the key's direction, so unloaded cells are last ascending and descending. `RowOrder` +still breaks every tie by source row, so the order stays strict and total and every sort stays stable. + +Unloaded is ranked after empty, and does not tie with it, so an unloaded cell is never placed among the empties +it might not belong to. Under a single sort key the rows whose place is unknown are one tail at the end of the +view. Under a chain, a row with an unloaded cell in a later key is last among the rows that tie on the keys +before it, so there is one such tail per run of equal earlier keys. + +### Unloaded cells in filters + +A filter over unloaded cells is three-valued. `CompiledFilter::evaluate` returns `Match::Yes`, `Match::No` or +`Match::Unknown`: + +- A column filter on an unloaded cell is `Unknown`, whatever its entries: `isEmpty` and `notEmpty` included, because + whether the cell is empty is not known, and `exclude` included, because whether an exclude entry matches is not + known. On any other cell it is `Yes` or `No` exactly as `passes` decides. +- A group is decided by its quantifier over its columns' answers, by the table in + [Column groups](#column-groups). A plain group is `Yes` when any of its columns is `Yes`; otherwise `Unknown` + when any is `Unknown`; otherwise `No`. +- A row is `No` when any column filter or group is `No`; otherwise `Unknown` when any is `Unknown`; otherwise `Yes`. + +So a row is rejected by what is known even while other cells load, and admitted by a group as soon as one loaded +column matches. `FilterRun` drops a row at the stage that answers `No`; a row a stage answers `Unknown` stays a +candidate, marked, and runs through the later stages, any of which may still reject it. + +A row that evaluates `Yes` is in the view. A row that evaluates `Unknown` is **undecided**: it is not in the view, +it is not rejected, and it is counted. `Engine::undecidedRowCount()` and `Page::undecided` report the count, so a +table's status line says "40 rows still loading" under an empty or short view rather than "no rows". + +Undecided rows are held out of the view, not shown in it, for three reasons. A filter that shows rows it may +reject lets a user select and act on rows that do not match. The count of such a view is an upper bound, which +`TotalKind` cannot say, while the count of the decided rows is a lower bound, which `AtLeast` says. And it keeps +the engine's rule in one sentence: a cell matches an operator only when the cell is known to. + +### Totals + +`total` counts the rows in the view. When `undecided` is not zero the view may still grow, so the total is a lower +bound and `totalKind` is `AtLeast`; with no undecided rows `apply` reports `Exact`. Above `QueryLimits::totalCap` +`apply` does not count the view and omits `total`, and a window keeps the total it already knows. A client shows +"12 so far, 40 loading" while rows are undecided, and the cap followed by "or more" ("100,000 or more") when +the view is past the cap and the page carries no total. A +sort on an unloaded column changes no membership and leaves the total `Exact`. + +### Unique values + +An unloaded cell is not a value and is not the empty value. `distinctValues` +([Filters from the header](#filters-from-the-header)) leaves out a row whose cell in the +column is unloaded, and a row another column's filter leaves undecided, and reports `partial = true` when it left +any out, so a filter menu built from the list can say that more values may appear. A `oneOf` entry on an unloaded +cell is `Unknown`, as every operator is. + +### Selection and edits + +- A `Selection` holds `RowId`s and is unaffected by what a row's cells hold. A row with unloaded cells can be + selected. `selectAll(engine)` selects the view, so it does not select undecided rows. With `pruneOnFilter`, a + selected row that becomes undecided has left the view and is pruned, as any row leaving the view is. +- `CellEdits::commit` refuses an edit of a cell that is `Unloaded` in its engine's view: the cell gets the + `FieldError` "not loaded yet" and the injected commit is not called. An edit of a value the user has not seen is + an overwrite of whatever arrives. A `CellEdits` without an engine cannot check, and the server's action is then + the only guard. +- An edit of a loaded cell in a row whose other cells are unloaded commits as usual. The commit's settled row may + still hold `Unloaded` cells. + +### On arrival + +Arrival is an update. The source publishes a snapshot in which the row's cells hold values and notifies +`RowChange{Updated, rows}`; the engine's repair does the rest. A repair's input holds the previous undecided rows +beside the previous view (`JobInput::previousUndecided`), because a dirty row may have been in either, and its +result holds the new ones (`JobResult::undecided`). + +- The rows' keys are rebuilt on copies of the key columns, and each row is evaluated again. +- A row that was undecided and is now `Yes` enters the view at its sorted place (`Inserted`), and the rows below + it shift by one. One that is now `No` produces no view operation. +- A row that was in the view is merged into the order at its true place (`Moved`) and reported `Changed`. +- `Engine::onUndecidedChange` receives the new count whenever it changed, after `onViewChange` when the same job + changed the view, and on its own when the job changed nothing else. Without it a row going from undecided to + rejected would leave "40 rows still loading" on screen. +- Under `ReorderPolicy::Deferred` a row that was in the view keeps its displayed index until the view settles, as + any updated row does. A row entering from the undecided set was not displayed and takes its true place at once, + so `Deferred` stops displayed rows from jumping and does not stop them from shifting. + +A cell may also go from a value back to `Unloaded` (a server dropping what it loaded). That is the same update in +the other direction: the row moves to the unloaded tail, or becomes undecided and leaves the view. + +## Data levels + +A **level** is a named unit of loading. A column of a table's description names the level its cells need: + +```cpp +struct ColumnInfo { + std::string id; + ColumnKind kind = ColumnKind::Text; + std::string comparator; + std::string format; + /// The data level the column's cells need. Empty is the base level, which every row has when it exists. + std::string level; +}; +``` + +Levels are strings, like column ids, so a table whose columns depend on the session names levels the same way. + +**A cell of a base-level column is never `Unloaded`.** No level names such a cell, so no load would resolve it. It +is a defect of the source and is refused, not shown: key building fails its job with +`TableErrorCode::SourceContract` naming the column (from `apply` as the returned error, from an `Engine` through +`onError`, the view staying as it was). + +A table's description says each column's level, and its `levels` lists them. A typed row declares its levels +once, on the row type, and `table::typed` puts them in the description: + +```cpp +struct ColumnLevel { std::string_view column; std::string_view level; }; + +struct DesignRow { + // … members … + static constexpr std::array columnLevels() noexcept { + return {{{"component", "recipe"}, {"quantity", "recipe"}}}; + } +}; +``` + +`RowsSource` fills `ColumnInfo::level` from that declaration, and the row's schema carries `x-level` on each +named property, which `deriveColumns` copies to a collection's column as it copies `x-comparator`. An entry +naming a column the row does not have is refused where the columns are reflected. + +Which levels a row has loaded is not a property of the description. A generic table's level columns are read +from the level's cache ([The server level cache](#the-server-level-cache)): a row the cache does not hold has +`Unloaded` cells there. A typed table says it with a predicate: + +```cpp +/// Whether `level` is loaded for `row`. Empty means every level is loaded. +template +using LevelLoaded = std::function; +``` + +`RowsSource` and the typed `apply` take a `LevelLoaded` after `comparators`. A cell of a column whose +level it refuses is `Unloaded`; the member's own value is not read. + +A query says which columns the reply carries: + +```cpp +struct TableQuery { + std::vector sort; + FilterSpec filters; + PageRequest page; + /// The columns the reply carries, by id. Absent means every column the caller may read; empty means none, + /// and the reply then holds keys alone. + std::optional> columns; + /// When set, the reply holds only the view's rows with these keys (see "Keyed queries"). + std::optional> keys; + /// When set, the reply holds a column's or a group's distinct values and no rows (see "Filters from the + /// header"). + std::optional distinct; + /// The user asked for failed loads to be tried again: the level caches load the failed keys this query + /// needs without waiting out their retry delay. + bool retry = false; + /// Rows the view keeps although the filter rejects them (see "Acting on rows"). + std::vector retain; +}; +``` + +**The query names columns, and the levels follow from them.** A client names the columns it draws and reads +([The client table model](#the-client-table-model)); the server sends those cells and loads the levels those +columns need. This is the one definition of what a view "shows": the columns its query names. Two things rest +on it. + +- **Bytes.** A page of 200 rows and 300 columns is about 1.27 MB as row objects and takes 15 ms to decode + natively; in a browser that decode runs on the thread that paints, for the twenty columns the user can see. A + page of the forty columns in or near view is an eighth of it (W1, W2). +- **Loads.** A level is loaded for a page's rows only when a named column needs it, so a level whose columns + are all out of the column window is not loaded by scrolling down. + +The query cache is not involved: a window's fetches make no cache entry +([The client's caches](#the-clients-caches)), so a column that scrolls into view changes no cache key. The +window holds, for each page, the columns it has, and fetches the ones it lacks. + +`validate` bounds `columns` by `QueryLimits::maxColumns` (512), puts it in the description's order and removes +duplicates. A name that is no column is `UnknownColumn`, and one the caller may not read is +`ColumnNotReadable`, as for a sorted or filtered column. A client that is refused either way holds a stale +description: it fetches the description again, fits its layout to it and asks once more. + +```cpp +struct LevelsNeeded { + /// Levels of the sorted and filtered columns: the view's membership and order depend on them for every row. + std::vector order; + /// Levels of the columns the query names: needed only for the rows of the reply. + std::vector display; +}; + +[[nodiscard]] LevelsNeeded levelsNeeded(TableQuery const& query, std::span columns, + std::function const& mayRead = {}, + Services const& services = {}); +``` + +- `order` is the levels of exactly the columns `apply` builds keys for: every sort key's column, every filtered + column that has an entry, each column of a group that has an `include` entry on which at least one of those + entries compiles (as `compileFilter` decides it, with `services`, so by the column's kind and the operand), and + the column or group of a distinct request. A group without an `include` entry, or a group's column on which no + entry compiles, reads no cell and adds no level; nor does a filter that does not compile, since `apply` refuses + its query. +- `display` is the levels of the columns in `query.columns`, or of every column the caller may read when + `columns` is absent: a client that does not say what it shows is assumed to show everything. +- Both are sorted, without duplicates, and never hold the base level. A level may be in both. +- The function reads no rows. It is called on the query `validate` returned, with the services `apply` is + given. + +The two lists differ in how much a server must load. An `order` level is needed for every row the rest of the +filter does not reject, because any of them may enter or move. A `display` level is needed for the rows of the +reply only. A server loads nothing else: a view with no column of a level named, sorted or filtered does not +need the level, and its load never starts. A client-mode table calls the same function with its engine's sort +and filter and the columns of its column window. + +A query is a request, not a subscription: nothing tells the server that a client removed the sort or filter that +needed an `order` level. The level cache finishes the loads it was asked for; what it loaded stays useful to the +next query that needs the level. + +`apply` reads cells only of the sorted and filtered columns, and the reply's writer reads cells only of the +named columns for the reply's rows, so a source may produce every other cell lazily or not at all. + +## Partial pages + +A reply says which of its cells are still coming. The members below are a typed `Page`'s; a `GenericPage` +([Rows on the wire](#rows-on-the-wire)) carries the same members with the same meaning beside its `columns`, +`keys` and `rows`. + +```cpp +/// A row of a page with levels that are not loaded. +struct UnloadedRow { + std::int64_t index = 0; // into Page::rows + std::vector levels; // sorted, without duplicates, never the base level + std::vector failed; // the subset of `levels` whose load failed; usually empty +}; + +template +struct Page { + std::vector rows; + std::optional total; + std::int64_t offset = 0; + TotalKind totalKind = TotalKind::Exact; + /// The rows of this reply that have unloaded levels, ascending by index. A row not listed is fully loaded. + std::vector unloadedRows; + /// Rows the filter can neither admit nor reject until a level loads. They are in no page. + std::int64_t undecided = 0; + /// The order levels with a load wanted or in flight for at least one row. Not empty means the order and + /// the membership of the view may change without any row being edited. + std::vector awaiting; + /// The order levels whose load failed for at least one row, and is not being tried again yet. + std::vector failed; + /// A keyed reply only: the view row of each of `rows`. + std::vector indices; + /// A distinct-values reply only; `rows` is then empty. + std::optional distinct; + /// The indices of rows the view retains although the filter rejects them (see "Acting on rows"). + std::vector unmatched; + /// Changes whenever the view's membership may have changed; a selection of the view records it. + std::string viewRevision; +}; +``` + +- A cell of row `i` in column `c` is unloaded exactly when `c`'s level is in the `levels` of the `UnloadedRow` + with `index == i`. A generic row holds `null` there; the member of a typed row holds whatever the server + left, and a client does not read it. +- `unloadedRows` lists the unloaded levels of the levels the reply needed (`order` and `display`), not every + level of the table: a level no named column has is not looked up, so its state is not known to the reply. +- **A failed load is still unloaded.** A cell whose load failed has no value, so the engine treats it as any + unloaded cell: it sorts last and its filter is `Unknown`. What differs is what the client is told, so a table + can stop saying "loading": the level is in the row's `failed`, and for an order level in `Page::failed` + instead of `awaiting`. `awaiting` and `failed` together are the order levels that leave rows unloaded. +- The members beyond `rows`, `total`, `offset` and `totalKind` are absent-tolerant: a `Page` read without them + is a fully loaded page. A server writes them as the example in [Rows on the wire](#rows-on-the-wire) shows: + `unloadedRows`, `undecided` and `awaiting` always; `failed`, `indices` and an `UnloadedRow`'s `failed` only + when not empty; an optional member such as `distinct` only when set. A reader takes each as present, empty + or not, or absent. + +`PageRows`, what `apply(DataSource const&, …)` returns, carries `totalKind`, `undecided`, `awaiting`, `failed` +and, for a keyed query, `indices`. The framework builds a generic page from it and takes each row's unloaded +levels from the level snapshots it read; the typed `apply` copies the same members into a `Page` and builds +`unloadedRows` from its `LevelLoaded`. + +```cpp +/// What is not loaded for one row: views into the page or window that holds the row. +struct UnloadedLevels { + std::span levels; + std::span failed; +}; +``` + +A `PageWindow` keeps each held row's unloaded levels (`unloadedLevels(index)`), and the `undecided()`, +`awaiting()` and `failed()` of the latest page reply; `reset` clears them. Unloaded cells do not make a page +incomplete: an unloaded row is a row the server has sent. + +## Keyed queries + +A query with `keys` set asks for specific rows of the view through the table's own action, so the model's +scope and authorisation apply to it as to a page. + +- The view is the one a page of the same sort, filter and `retain` has. The reply's `rows` are the view's rows whose key + is in `keys`, in view order, with the query's `columns`; `indices` holds each one's view row; `unloadedRows` + describes them. A key that is not in the view (the row was removed, is rejected, or is undecided) has no row + in the reply. +- `page` does not apply; `validate` refuses a keyed query with a non-zero `page.offset` as `InvalidSpec`, one + that also sets `distinct` as `InvalidSpec`, and more than `QueryLimits::maxKeys` (1,000) keys as + `LimitExceeded`. Each text key is bounded by `QueryLimits::maxTextLength`. +- **A keyed reply carries the view's `total`, `totalKind`, `undecided`, `awaiting` and `failed`**, as a page + does. A window does not adopt them: keyed replies can arrive out of order, and only page replies, which a + revision orders, set the window's totals. It compares them with its own, and a difference tells it that rows + it did not ask about have entered or left the view + ([The window under changes](#the-window-under-changes)). +- The server answers a keyed query from the view it has cached for the sort and filter + ([The view cache](#the-view-cache)): a key's view row is a lookup, not a sort. +- A client whose keyed fetch is refused with `Unavailable` falls back to `invalidate`. + +## Arrival + +No part of the path polls. Each step is caused by the one before it. + +1. **The level cache** ([Caching layers](#the-server-level-cache)) finishes a load for some rows and stores the + values. A read of the cache from that moment returns them. +2. **An engine on a source fed from it** (a client-mode table, or a server that keeps one) is given the rows as + `RowChange{Updated, rows}` and repairs them, as in [On arrival](#on-arrival). Its `ViewChange` names exactly the + rows that entered, moved or changed. +3. **The server tells the watchers.** The table is a registered record + ([The table's record](#a-models-tables)), and the cache announces the rows that arrived, after it stored + them: + + ```cpp + /// Reports a change to rows of `record` that no execute made. Callable from any thread. + /// `keys` absent reports the whole type. An unregistered record is refused and nothing is sent. + std::expected RemoteServer::announce(std::string_view record, + std::optional> keys); + ``` + + `announce` builds its `effects::Changes` with the helpers an execute's changes are built with, so the record's + derived records are included and more than `effects::kMaxChangeKeys` keys become a whole-type change. It posts + to the server strand and runs `fanOut` with no caller, as a time fact does: watches, re-authorisation and + coalescing apply unchanged, and a time-fact reporter naming the record is asked again. An announced change is + not handed to the change observers, so an arrival never invalidates the cache that announced it. The level is + not in the event: the keys are enough, and a client asks for what it shows. + + Keys cross as JSON. `table::changeKeys(std::span)` writes an integer key as a JSON number and a + text key as a JSON string; `table::rowIdOf(glz::raw_json const&)` reads one back, and an event key that is + neither makes the client treat the event as a whole-type change. The table's key column and the keys an + action's `ChangedRows` names must write the same JSON for the same row; a test of each table holds them to it. + + A row-scoped table's record has `privateKeys`, and an announcement has no caller, so it reaches every + watcher without its keys: each watcher refetches its visible pages instead of its rows. That is the price of + not telling a watcher the key of a row it may not see. It is one page request per watcher per coalesced + event, answered from the view cache. + + A load that fails is announced the same way, once, with the failed keys, so a client stops showing them as + loading. +4. **The client's cache** takes the event. A window answers with a keyed fetch for the event's keys, or with + page fetches ([below](#the-window-under-changes)); the query cache marks the entries concerned and they fetch + their page again ([Caching layers](#the-clients-caches)). +5. **The server answers** the keyed query or the page through the same action, from the view cache and the + level cache: nothing is loaded again, and the view is computed again only when the arrival was of a level + it orders by, once for all its watchers. +6. **The window patches** the rows in place and reports their view rows; the renderer reports exactly those rows + as changed. + +The record's `changes` events are not only arrivals. An action that edits a row declares `updates` or `changes` on +the same record, and its event reaches the same caches. A client cache therefore treats every event alike and +never assumes an event is an arrival. + +## The window under changes + +A window holds the rows of a model-backed table around the visible rows, and for each page the columns it has +fetched. `PageWindow` is the window of every `table` node: a row's key is its entry of the page's +`keys`. `PageWindow` holds a typed page's rows for a C++ client, with a `RowKey` function for the key +and no column window, since a typed row is whole. + +```cpp +struct PageFetch { + PageRequest request; + std::vector columns; // the columns asked for; a held page asks for the ones it lacks + std::uint64_t query = 0; + std::uint64_t revision = 0; +}; +struct RowsFetch { + std::vector keys; + std::vector columns; + std::uint64_t query = 0; + std::uint64_t sequence = 0; +}; +enum class Refresh : std::uint8_t { Nothing, Rows, Pages }; +struct RefreshPlan { Refresh kind = Refresh::Nothing; RowsFetch rows; }; + +explicit PageWindow(std::int64_t pageSize = 200, std::size_t maxPages = 8, RowKey key = {}, + std::size_t maxKeys = 1000, std::size_t maxColumns = 96); + +std::vector visible(std::int64_t first, std::int64_t count, std::span columns = {}); +std::vector superseded() const; // fetches in flight for pages no longer near the visible rows +void cancelled(PageFetch const& fetch); +RefreshPlan refresh(std::span keys); // a keyed change of the table's record +RefreshPlan owed(); // after each accept +void invalidate(); // a whole-type change, a resync, a refused keyed fetch +bool accept(PageFetch const& fetch, Page reply); // false when the reply is ignored +std::vector patch(RowsFetch const& fetch, Page reply); +``` + +The window has no clock and sends nothing: it returns what to fetch, and `WindowRows` decides when +([When a fetch is sent](#when-a-fetch-is-sent)). + +### Pages and columns + +- A held page stores its cells by column, so a column that scrolls into the column window is added to the page + and one that has left it is dropped without touching the others. A window holds at most `maxColumns` columns + a page; over that, the columns farthest from the column window go first, and never a column the latest `visible` + named. `visible` takes the first `maxColumns` of the columns it is given, so a wider set cannot be dropped and + fetched again without end. +- `visible(first, count, columns)` covers the visible rows and one page either side. For a page it does not + hold, or holds stale, it returns a fetch of the whole page with `columns`. For a page it holds complete but + without some of `columns`, it returns a fetch of the same rows naming only the columns the page lacks. One + fetch per page is in flight at most. +- `accept` of a column fetch adds the columns when the reply's `keys` are the page's keys, row for row. When + they are not, the rows moved between the two fetches, and the window invalidates. +- `accept` of a page reply whose `total`, `totalKind` or `undecided` differ from the window's adopts them and + marks every other held page stale: the view changed between two replies, whatever the events said. An absent + `total` is neither adopted nor a difference. +- **A view that shrank holds nothing past its end.** When the total the window holds is exact, a held row at or + past it is dropped (a page wholly past it goes, the page it falls in is cut and is complete), and a fetch in + flight for a page wholly past it is forgotten, so its late reply is ignored. Otherwise such a page is never + fetched again, and its first key would be a probe no reply answers. +- `superseded()` returns the fetches in flight for pages that are no longer within one page of the visible + rows. The client cancels them through their stop tokens and tells the window with `cancelled`. + +### `refresh(keys)`: rows or pages + +- `Pages` (it calls `invalidate`) when the window has no key function; when `awaiting()` is not empty, because + nearly every arrival then moves rows; or when the keys it would ask for exceed `maxKeys`. +- Otherwise `Rows`, asking for **every key of the event**, held or not, and for one **probe** per run of held + rows: the key of the run's first row. A held row with no unloaded level is asked for too: the event may be an + edit. +- `Nothing` when the window holds no row. +- While any page fetch is in flight, it also records the event's keys. + +An event's keys are asked for whether or not the window holds them because an edit can bring a row the window +has never seen into its pages, and the author of an action cannot know how each client has sorted. The reply's +view rows say what happened ([`patch`](#patchfetch-reply)). + +**`owed()`** closes the race between an event and a page reply. The reply to a page fetch and the event for a +change leave the server separately and arrive in either order, so an event can precede the reply whose rows it +concerns. After each `accept` the client calls `owed`, which returns `Rows` with the keys recorded while the +fetch was in flight. The recorded keys are dropped when no page fetch is in flight, and whenever the plan is +`Pages`: that invalidation leaves every reply still in flight older than the window, so the refetch that follows +covers every recorded key. Kept, they would invalidate again at every `accept` while two pages are in flight, with +no event behind it. + +### `patch(fetch, reply)` + +`patch` replaces a held row when the reply has a row with its key at the view row the window holds it at, +updates its unloaded levels, and returns the view rows it replaced, ascending. It calls `invalidate` instead +when the reply shows that rows shifted: + +| The reply shows | Meaning | +|---|---| +| A requested key the window holds has no row | The row left the view. | +| A key the window holds is at another view row | The row moved, or a row above it entered, left or moved across it. The probes are held keys, so this catches a shift caused by a row the window does not hold. | +| A key the window does not hold is at a view row inside a held page | A row entered the pages. | +| `total`, `totalKind` or `undecided` differ from the window's | A row entered or left somewhere in the view. Checked only on the reply to the latest keyed fetch sent, so an old reply cannot report an old total. | + +Why this is enough: a change that leaves every held row at its view row, with the same content, and leaves the +totals as they were, changes nothing the window shows. Any other change moves a held row, which a probe or a +requested key reports; or brings an unheld key into a held page, which its view row reports; or changes a +total. A check that fires wrongly, because a keyed reply and a page reply crossed, costs one page fetch and +ends there, since the refetched page agrees with itself. + +Each `RowsFetch` has a sequence, and the window remembers the latest sequence that asked for each held key: a reply +row whose key a later fetch has asked for is ignored, missing or not, so an out-of-order reply cannot put older +values over newer ones. A reply of an older query is ignored. `patch` never changes which rows are held or +their order. Only a held key is remembered, and it is forgotten when it leaves the held pages, so the memory +never outgrows the held rows: a row for a key the window does not hold is ignored outside the held pages and +refetched inside them, whatever its sequence. + +### `invalidate()` + +`invalidate` takes a new revision and marks every held page stale. It keeps the held rows showing and keeps the +fetches in flight. + +- `visible` returns a whole-page fetch, tagged with the current revision, for each stale page around the visible + rows that has no fetch in flight. +- `accept` takes a whole-page reply whose revision is not older than the page's held content, and replaces the + page. The page is complete only when the reply's revision is the current one; otherwise it stays stale and the + next `visible` fetches it again. A reply older than the held content, or of an older query, is ignored. +- So a window invalidated more often than a round trip takes still advances by one reply per round trip, and is + current one round trip after the last event. The client calls `visible` after every `accept`. + +### When a fetch is sent + +`WindowRows` owns two delays. Neither asks for anything because time passed: each only holds back or merges a +request that a scroll or an event caused. + +- **Scrolling.** A fetch for a page next to a held page is sent at once: that is ordinary scrolling, and the + held margin hides the round trip. So is the page of the first visible row while no page is held: the first + query's page, and the first after a sort or filter, since nothing is passing over it. A fetch for a page + farther away (a drag of the scroll thumb, a fling, `Ctrl+End`) is sent when the visible rows have stayed + within one page for `SessionOptions::tableSettle` (80 ms). Columns follow the same rule sideways. Every fetch `superseded()` returns is cancelled. A drag of the + thumb across 100,000 rows therefore sends a fetch where it rests, not five hundred on the way. +- **An awaited order.** While `awaiting()` is not empty, every event invalidates. `WindowRows` sends the first + refetch at once and the next no sooner than `SessionOptions::tableAwaitedRefetch` (250 ms) after it, so a + watcher of a level that loads for a minute fetches its visible pages four times a second at most, and once + more after the last arrival. A loader announces per batch of rows, not per row. + +## Caching layers + +A value that is slow to load is loaded once and kept until something says it is wrong. Five layers hold what a +table shows on the way to the screen, and one notification, the table record's change event, refreshes all of +them. + +| Layer | Holds | Key | Bound | What removes or refreshes a value | +|---|---|---|---|---| +| Server level cache, `table::LevelCache` | The loaded values of one level, as the loader returned them, for every principal | table record, level, row key | `maxBytes`, least recently used first | `invalidate`; an action's effects on a record in `invalidatedBy`; eviction at the bound | +| Server view cache, `table::ViewCache` | The order and the undecided rows of a view | table record, `ServedTable::scope`, validated sort and filter | `maxBytes`, least recently used first | A new snapshot of the source; a new generation of an order level | +| Client query cache, the interpreter's `Session` | Whole replies of a query: a table's description, a distinct-values list, a page read by a `rows` table | model type, instance token, action, canonical body | `keepUnused` after the last query leaves | A change event marks it and it fetches again; `resync`; a move onto it after `staleTime` | +| Client `PageWindow` | The pages of a model-backed table around the visible rows, the columns each holds, each row's unloaded levels | query, then page index | `maxPages` (8) of `pageSize` (200) rows, `maxColumns` (96) columns | A change event (`refresh`, `invalidate`); `reset` on a new sort or filter | +| Renderer | The realized cells and the column widths measured from them | row key and column id | The two windows | The mount's diff of the rows it is given | + +Nothing below the server level cache ever causes a level to be loaded twice: a client cache that fetches again is +answered from the level cache. + +### The server level cache + +The framework owns the cache; the model supplies only the function that reads the values. + +```cpp +enum class LevelRead : std::uint8_t { Loaded, Unloaded, Failed }; +enum class LevelUse : std::uint8_t { Display, Order }; + +/// One state of a level. Immutable: nothing it returns changes while it lives, and holding it blocks no one. +class LevelSnapshot { +public: + virtual ~LevelSnapshot() = default; + /// Writes the row's cells for the level's columns, in the order of `LevelSource::columns()`. + [[nodiscard]] virtual LevelRead read(RowId const& key, std::span out) const = 0; + /// Differs between two snapshots that differ in any value. + [[nodiscard]] virtual std::uint64_t generation() const = 0; +}; + +/// What the framework needs of a level, whatever the type of its values. +class LevelSource { +public: + virtual ~LevelSource() = default; + [[nodiscard]] virtual std::string_view level() const = 0; + /// The level's columns. The same for every caller. + [[nodiscard]] virtual std::span columns() const = 0; + [[nodiscard]] virtual std::shared_ptr snapshot() const = 0; + /// Says the keys are needed. `Unavailable` when an order use cannot fit (rule 10). + virtual std::expected want(std::span keys, LevelUse use, bool retry = false) = 0; +}; + +struct LevelCacheOptions { + std::vector records; // the table records it serves; one, or several that share rows + std::string level; + std::vector columns; // the level's columns, for every caller, in a fixed order + std::size_t maxBytes = 256U << 20U; + std::size_t expectedBytes = 0; // a value's size before any is stored; 0: 64 bytes a column + /// Records whose change invalidates values. Default: `records`. + std::vector invalidatedBy; + exec::IExecutor* loads = nullptr; // where the loader runs; never the server strand + std::size_t batch = 64; // most keys handed to one loader call + std::chrono::seconds orderLease{60}; // how long an order use keeps its keys from eviction + std::chrono::seconds retryAfter{30}; // before a failed key is loaded again; doubles to `retryMax` + std::chrono::seconds retryMax{600}; + std::function clock; // empty: the steady clock +}; + +struct LevelCacheStats { + std::size_t hits, misses, loaderCalls, loadedKeys, failedLoads, droppedLoads, invalidatedKeys, evictedKeys, + leasedKeys, refusedOrders, bytes; +}; + +template +class LevelCache final : public LevelSource, public effects::IChangeObserver { +public: + /// Reads the level for `keys`. Called on `options.loads`; may block. It returns a value for every key it + /// read, including a row that has nothing at this level, whose value is then empty. A key it returns no + /// value for failed; throwing fails every key of the call. + using Loader = std::function>(std::span keys)>; + using SizeOf = std::function; // deep bytes + using Cells = std::function out)>; // in `columns` order + + LevelCache(LevelCacheOptions options, Loader loader, SizeOf sizeOf, Cells cells); + /// For `Value` = `std::vector` only: the value is the cells, and its size is their deep size. + LevelCache(LevelCacheOptions options, Loader loader); + + void invalidate(std::span keys); + void invalidateAll(); + void onLoadFailed(std::function)> handler); + [[nodiscard]] LevelCacheStats stats() const; +}; + +using CellLevelCache = LevelCache>; +``` + +**What a value is laid out against.** A level's columns are `LevelCacheOptions::columns`: one list for every +caller, declared when the cache is made. A generic value is one cell per entry of that list, in its order; a +typed value is turned into the same cells by `Cells`. A caller's description may hold fewer of the level's +columns than the list, in another order; the framework maps each of the caller's columns to its place in the +list by id and passes it through `mayRead`. A cached value is never laid out against a description, because +descriptions differ by caller and the cache is shared. + +**Size is deep.** `maxBytes` bounds what the values own, not `sizeof(Value)`: a `std::vector` of twenty +cells is 24 bytes by `sizeof` and about 1.1 kB in truth. `CellLevelCache` measures cells and their texts +itself. A cache of another value type is given `SizeOf`; there is no shallow default. + +**How the framework uses it**, for every query of a table: `levelsNeeded` on the validated query; a snapshot of +each needed level; the view, from the view cache or `apply`, over base columns from the table's source and +level columns from the snapshots, `Unloaded` where a snapshot holds no value; the reply; then `want` with the +keys the reply needed: the reply's rows for a `display` level, every row the filter did not reject for an +`order` level. The reply is built entirely from the snapshots taken at its start, so its rows and its +`unloadedRows` describe one state of each level. + +Rules: + +1. **Hit.** A key the cache holds is served to every query, page, session and client until it is invalidated or + evicted. No age expires it. +2. **One load.** `want` starts a load only for keys neither held nor in flight. Queries that need the same rows + while a load runs wait for that load's arrival event like any other client. +3. **Order of work.** Keys are loaded in batches of `batch`, `Display` keys before `Order` keys and the most + recently wanted first, so the rows a user is looking at now come before the rows a sort needs eventually. +4. **Raw values, scoped reads.** The cache holds what the loader returned and knows no principal. A value reaches + a reply only through a row of the caller's own source and a column `mayRead` allows, both decided before the + cache is read. A level whose values differ by principal is not one level: it is declared as one level per + scope, or not cached. +5. **Invalidation is explicit**, and there are three sources. + - The application calls `invalidate(keys)` or `invalidateAll()`. + - An action's effects. The server hands every change an execute or a time fact derived to each attached + observer, on the server strand, before it queues the change's events. A keyed change of the row's own record + invalidates those keys; a whole-type change of it invalidates the level. The action's own event is the + notification, so the cache announces nothing. + - A change of another record in `invalidatedBy` (a recipe, when the level is a design's recipe data). Its keys + are not row keys, so the whole level is invalidated, and the cache announces the table's record without keys, + because no event for the table's record exists yet. +6. **An effect invalidates every level of the rows it names.** Effects name records, not levels, so a change to a + row is taken to change everything derived from it. That over-invalidates by one row's reload per edited row. A + level that does not depend on the row's own record says so by leaving the record out of `invalidatedBy`. +7. **A load in flight does not land stale.** Each row has a generation that an invalidation advances. A load + remembers the generation of each key when it starts and stores a value only where it is unchanged; the rest + are dropped and counted, and the query that follows the invalidation's event wants them again. +8. **Stored, then told.** A load publishes its values before it announces their keys; an invalidation removes + its values before any event for it is queued. A client that fetches because of an event therefore reads the + state the event is about. +9. **Bound.** Over `maxBytes`, the least recently used values that no order lease holds are evicted. An evicted + value is absent, its cells are unloaded in the next reply, and that reply's `want` loads it again. An + eviction sends no event: the clients that hold the value hold a correct one. +10. **An order use is leased, and refused when it cannot fit.** A sort or filter needs the level for every + candidate row at once. + - `want(keys, Order)` gives each key a lease until `orderLease` from now. A leased value is not evicted, so + a view that is ordering by the level does not lose rows to another query's loads, and two order uses + cannot evict each other in turn. A query that needs the level for order renews the lease and becomes one + more holder of it; `unwant`, which a query refused by another level calls, ends one holder, and the lease + ends with its last. A view's order keys are one kept set (`wantSet`), as are a distinct request's (the + "every row" entry of [The view cache](#the-view-cache)), and its lease is the set's: the + set holds a count of the queries holding it and a lease end. The first query of a set is fitted and + protects every key of the set, a chunk at a time under the writer mutex, by a per-key count of the sets + protecting it; that is the only pass over the keys. A repeat while the set's lease runs is one more holder + and a longer lease, under the lock, touching no key, unless the cache's count of set events (a protected + key removed, a protected failure's delay passed) has moved since that set last looked, when it also queues + the keys the set misses; each set compares its own last-seen count, so one set's repeat consumes no other + set's event. A fit also releases the sets no query has wanted since the level's generation moved past the + one they were last wanted at: a view is found only at its level's generation, so their views are + superseded. An accepted set's keys count in the level's bound. `unwant` of the set is one + holder fewer; the set's protection is taken off its keys, a chunk at a time under the lock, only with its + last holder or when its lease has run out. A repeat that arrives while the set's fitting `want` runs waits + for it, and is then a repeat, or fitted itself when that want was refused. A key is kept from eviction + while its own lease runs or a set protects it. A level no query has ordered by for `orderLease` is + evictable again. Leases are compared with the clock when a request reads them; nothing is scheduled. + - The cache decides whether the use fits before it loads: the keys times the mean size of its stored values + (`expectedBytes` while it holds none), plus the bytes other leases hold, against `maxBytes`. Over it, + `want` returns `Unavailable`, the framework refuses the query naming the column, and nothing is loaded. + The second of two order uses that do not fit together is the one refused, while the first's lease lives. + - Sizes are not known before a load. When leased values come to exceed `maxBytes` while they load, the cache + stops loading for order, drops the leases, ends every set, and announces the table's record without keys; + the next query meets the estimate, which is now measured, and is refused. + - A `Display` load that finds nothing evictable is stored over the bound and is the first evicted. The + overshoot is at most one batch for each page being answered. +11. **A failed load is remembered.** A key the loader returned no value for is `Failed` in every snapshot until + it is loaded, and is announced once, with its key, so that clients stop showing it as loading. `want` does + not load a failed key again until `retryAfter` has passed since the failure, doubling with each failure in + a row up to `retryMax`; the delay is read from the clock when a query wants the key. `want(…, retry: true)`, + which a query carrying `TableQuery::retry` makes, loads the failed keys it names at once. An invalidation + clears the failure with the value. A failed key is not in `awaiting`, so a level that cannot be read does + not make every window refetch on every event. +12. **Snapshots are immutable, and nothing waits on a reader.** The values are held in shards by key hash, each + an immutable sorted vector behind a shared pointer. The shard count is a power of two that doubles as the + cache grows, so a shard averages at most 64 rows and a change copies little beyond the rows it touches. A + published state is the shard pointers and a generation behind one shared pointer, and a snapshot holds it. + A store, an eviction, a removal and the observer call prepare their new state from the published one with + no lock held (the shard copies, the scans and sorts, the re-spread), then take a writer mutex only to check + that nothing was published meanwhile, preparing again if it was, and to publish; the state is published + under a second mutex held for the pointer swap alone, and a reader takes only that one. A `want` takes its + keys 1,024 at a time under the writer mutex and releases it between chunks; inside a chunk each key is + classified, leased and queued at once, so an eviction's publish sees every lease given before it and a key + removed before its chunk is queued again. A reply may hold a snapshot for as long as its `apply` takes, + 40 ms at 100,000 rows, and the server strand's observer call still returns in the time its keys take, plus + one chunk of a want at most. A held value's recency and order lease (its end and its number of holders) are + atomics on its slot, and the lease of a key not held yet is kept, under the writer mutex, until the key is + stored; none of these is part of a snapshot's state. A whole-level invalidation publishes empty shards. +13. **Threads.** `snapshot`, `want` and `invalidate` may be called from any thread. The loader runs on `loads`. + The observer call runs on the server strand and only removes entries: it does not load, wait or call out. + +The server learns of a cache through `RemoteServer::attach(std::shared_ptr)`, which the +application calls after it constructs the server. `attach` gives the observer its announce sink +(`effects::AnnounceSink`, a function taking a record name and optional keys, holding the server weakly), and +registers it for derived changes. `IEnvelopeService::bound` is not used for this: it runs at the first envelope a +service answers, which may be long after the first page, or never. + +### The view cache + +Sorting and filtering 100,000 rows takes 33 to 46 ms. Without a cache every request pays it: each page of a +scroll, each keyed fetch, and, while an order level loads, every watcher once per arrival. The server therefore +keeps the views it has computed. + +```cpp +struct ViewCacheOptions { + std::size_t maxBytes = 64U << 20U; // across the server's tables; the views, not the snapshots they keep + std::function onCompute; // called on the computing thread as each computation starts +}; +``` + +An entry keeps the snapshot it was computed over alive, and `maxBytes` does not count that snapshot: an entry for +a sort nobody asks for again holds its rows until it is evicted or found invalid. Each request carries how +recently its snapshot was pinned and the generation of each order level it read. An entry is replaced only by one +at least as new in every part; a request that is older in any part computes its view without displacing the entry, +so a straggler never undoes a newer view. + +- **Key.** The table's record, `ServedTable::scope`, and the validated query's sort and filter in canonical + form. `page`, `columns`, `keys`, `distinct` and `retain` are not in it: every page, every column set and every + keyed fetch of one sort and filter read one entry. A query with `retain` merges its retained rows into the + entry's view per request ([Rows an action changed](#rows-an-action-changed)), so sessions that retain + different rows still share one sort. +- **Valid while** the table's source has the snapshot the entry was computed from and each of the view's order + levels has the generation it read. A request finds an entry, compares those, and uses it or computes again. + An entry is never repaired in place. +- **Holds** the view's order as source rows (4 bytes a row), the undecided rows, `total`, `awaiting` and + `failed`, and, built at the first keyed query, the view row of each source row (4 bytes a row). A view of + 100,000 rows is 400 kB, or 800 kB once a keyed query has asked. A view whose query sorts or filters by a + level also keeps the keys of its rows and undecided rows, the set its order levels are wanted with: + `sizeof(RowId)` a row, plus a text key's heap buffer, counted against the bound like the rest. A distinct + request wants its order levels for every row, so the cache also holds one "every row" entry per table record + and `ServedTable::scope`, keyed under a query no sort or filter writes, valid while the table's source has the + snapshot it was made from and whatever the levels' generations: its rows and their keys, so the distinct + requests over one snapshot share one kept set and repeat it. +- **One computation.** Requests that need the same entry while it is computed wait for that one computation. So + fifty watchers of one view that refetch after an arrival cost one `apply`, not fifty. +- **Where it runs.** Finding, computing and reading an entry, and encoding the reply, run on + `ServerConfig::tableWork`, over immutable snapshots. Neither the model's strand nor the server strand + waits for a sort. +- **Bound.** Over `maxBytes` the least recently used entries go. An entry is also dropped when it is found + invalid. +- **What it does not hold.** Cells: a reply reads them from the source and the level snapshots. Distinct + values: a values list runs the filter again without the column's own entry, and its reply is cached by the + client's query cache. + +A scoped table whose `scope` is left empty would share views between callers who see different rows. The +framework cannot see that from the outside, so `table::rowScoped` and an empty `scope` together are refused +when the table is first served, as `SourceContract`. + +### The client's caches + +Both client caches hold pages until a change event marks them. Neither refetches because time passed. + +**The query cache** is told three things about a result that holds records, none specific to tables. The first +two a holder type declares, as a type declares `schemaMarker()`: + +```cpp +static constexpr auto openMembers() noexcept; // Page: "awaiting", "distinct" +static constexpr std::string_view partialMember() noexcept; // Page: "unloadedRows" +``` + +The result walk that records where an action's result holds each record also records these two members' paths, +and the catalog carries them as `ActionRecordInfo::open` (a list: the entry is open while any is set) and +`ActionRecordInfo::partial`. The cache reads the values at those paths and knows nothing else about the result's +shape. A member counts as set when it is a non-empty array, an object, `true`, or a number other than zero. The +third is `ActionRecordInfo::opaque`, which a registration states when a result holds a record at no path +([The table's record](#a-models-tables)). + +- **An open entry is marked by every change of its record.** While `open` is set, a row the entry does not hold + may come to belong to it, so a keyed event marks the entry whether or not it holds one of the keys. This is what + makes an undecided row that becomes admitted refresh the page it now belongs to. +- **A partial entry is not merged into.** While `partial` or `open` is set, an `updates` effect on the record acts + as `changes` for that entry: it is marked and fetched again. A merge replaces rows by key and cannot update a + sidecar indexed by position, so it would leave a merged row's unloaded state describing the row it replaced. The + cache applies the same downgrade to the effects of a discarded `latest` reply. +- **An opaque entry is always both.** The cache finds an entry's rows by the record's key member at the + record's paths, and a `GenericPage` has neither. Every entry of a `Table.` action (a page a document + query reads, a distinct-values list) is marked by every change of the table's record and is never merged + into. A table's description is an entry of `Table..describe`, which holds no record: it is replaced when + a reply names another `revision`. +- **An opaque entry keeps fractions.** A `Value` holds no JSON number with a fraction or an exponent, and an + ordinary action's reply that has one is refused. A page's `Number` cells are such numbers, so the reply of an + opaque entry is decoded by a table-aware variant of `valueFromJson`: a number with a fraction becomes the + decimal `Value` its shortest text spells (`table::parseDecimal`), and one that does not parse as a decimal + becomes its text. Every other action keeps the strict rule. A document's `rows` bound to such a page + therefore hold decimals, and a column of fractional numbers there infers as `Decimal`. + +**A window's fetches are not queries and make no entry.** The session has a read for them and a way to watch +without an entry: + +```cpp +/// Runs a read action and resolves with its reply's JSON text, or fails as an entry's fetch fails. Makes no +/// cache entry and reads none. A stop request sends the wire's `cancel` for the call, where the server takes +/// one, and drops the reply in either case. +async::Completion +Session::read(std::shared_ptr const& channel, std::string const& actionId, Value const& body, + ::core::async::StopToken stop = {}); + +/// Watches `record` for as long as the returned holder lives, and hands its events to `handler` on the +/// runtime's owner. Resolves when the server has the watch. +async::Completion +Session::watchRecord(std::string const& record, std::function handler); +``` + +- A watch is counted per holder, as it is per entry: the session's watch set names a record while any entry or + any holder needs it. +- **Watch, then fetch.** `WindowRows` sends its first page fetch after `watchRecord` resolves, as an entry + watches before it fetches, so no change between the reply and the watch is missed. +- **`read` resolves with text, not a `Value`.** A page's `Number` cells are JSON numbers with fractions, which + a `Value` cannot hold, so the caller decodes the text against the table's description + (`table::readGenericPage`) and every cell keeps its exact value. +- `read` does not route its reply through the cache's effects: a read has none, and the caller's own change + events reach it like anyone's. +- On reconnect and on `resync` the session calls each holder's handler with a whole-type change. + +**Freshness.** + +- `staleTime` decides whether moving onto an entry fetches. Such a fetch re-reads a page and is answered from the + server's caches: it costs a page, never a load. A table with levels needs no `refreshEvery`, and one that + has it still loads nothing twice. A `PageWindow` has no stale time. +- On reconnect and on `resync` the session sends its watch set again and marks every entry stale; a window is + invalidated. Events missed while disconnected are covered by those fetches. +- Offline, a held page shows as it was, its unloaded cells unloaded. No arrival reaches it until the connection + returns, when the reconnect rule applies. + +**Column widths.** The Qt Quick table measures a column from its realized cells, and in a windowed table a +column's width only grows. An unloaded cell draws a placeholder of a fixed width, so a level arriving widens each +of its columns at most once, to its widest realized value, and never narrows one. + +### Which client cache a screen uses + +A `rows` table bound to a query's page reads through the query cache. With the rules above it is correct and +push-driven: an arrival marks the entries concerned, each fetches its page again, and the mount's keyed rows +repaint only the rows whose content changed. What it pays is the transfer: a page of 200 rows and 300 columns +for an arrival of twenty rows ([Performance](#performance), W7 against W4). + +A model-backed `table` reads through a `PageWindow` ([The client table model](#the-client-table-model)): the +node owns a window, feeds the mount's visible range to `visible`, sends the window's fetches through the +session, and gives the mount the window's rows. An arrival there transfers the rows that arrived. + +### A persistent tier + +Loaded values do not survive a server restart: the cache starts empty and loads on demand. A tier that keeps them +needs a durable generation per row, written with the data it describes, or a restart serves values an action +invalidated while the server was down. That is a storage design, not a cache option, and is not part of this one. +`LevelCache` keeps its storage behind its own members so that a tier can be put under it. + +## Where sort and filter run + +morph has two modes. In client mode an `Engine` sorts and filters a `DataSource` the client holds entirely. In +server mode a table's action takes a `TableQuery`, the server sorts, filters and pages, and the client holds +pages. A table over rows the document holds, and a collection, are in client mode; a model's table is in server +mode. + +A browser client is the Qt WebAssembly build, which is single-threaded. That decides three things: + +- **No worker.** An `Engine` there runs its jobs as steps on the owner thread, the one that paints. A step's + size is set for the browser, not for native code: the size that takes 4 ms natively is divided by the factor + B2 measures, so a step keeps to half a frame where the code is slower. The work is not done in parallel with + painting, and a recompute's diff and a `Deferred` repair's layout are one step each, 10 to 55 ms natively at + 100,000 rows ([`engine.md`, "Not here yet"](engine.md#not-here-yet)). Client mode in a browser is therefore + held to the bound of rule 4 below, 20,000 rows, and B1 holds the worst step at that size. +- **A 32-bit address space.** The heap cannot exceed 4 GiB and is usually configured lower. +- **Slower code.** WebAssembly runs this kind of code slower than native; the factor is measured by benchmark B2 + and taken as 1.5 to 3 until it is. + +**What the table weighs.** A `Cell` is as large as its largest alternative, two `Rational`s, about 56 bytes. A +`VectorSource` of 100,000 rows and 300 columns is 30 million cells: about 1.7 GB before any text. A page of rows +costs about 21 bytes a cell on the wire (212 bytes for a row of ten small cells), so the whole table is about +630 MB of JSON: over a minute at 100 Mbit/s before it is parsed. Holding the table in a browser is not slow, it +is impossible; and a table with a slow level is not held by the server in full either. A window of 1,600 rows is +480,000 cells and about 10 MB of JSON if every column is sent, and 64,000 cells and about 1.3 MB for the +forty columns in or near view, spread over eight replies. + +**The rule.** Where sort and filter run follows from what the client holds, and what the client holds follows +from the action's shape: + +| The source | Mode | Sort, filter, totals, distinct values, the undecided set | Selecting all | +|---|---|---|---| +| A model's table: its action takes a `TableQuery` (the schema carries `x-table`) | Server | On the server, once for each view and state of its data | A selection of the view, which an action resolves on the server ([Acting on rows](#acting-on-rows)) | +| Rows the client holds entirely: a document's `rows`, a collection's reply | Client | An `Engine` on the client | `Selection::selectAll` | + +A table is in server mode, and must be, when any of these holds: + +1. the server pages it, because the rows are too many to send; +2. a column that can be sorted or filtered has a level other than the base one: a client cannot order by values + it does not hold, and the level cache is on the server; +3. the rows a principal may see are decided per request; the server filters those rows in either mode, and client + mode is then possible only over the scoped result; +4. it has more than 20,000 rows or more than 1,000,000 cells. Under that, the whole table is at most about 21 MB + of JSON and 56 MB of cells, which a browser holds, and a three-key sort with a filter over 10,000 rows takes a + few milliseconds on one thread. + +The action's shape decides, not the application at run time and not the framework by measuring the data. A table +that changes mode when it grows past a threshold changes its text order (a server orders by its own collator and +a client does not re-sort a page), its selection behaviour and its totals on the day it grows. The author chooses +once by writing a paged action or a plain list. The framework checks the choice: a document table over a plain +list whose result exceeds the bound in 4 is reported as a warning naming the table, as the document's other +warnings are, and a client-mode sort or filter on a column with a level is refused. + +**What the user waits for** in server mode, at 100,000 rows and 300 columns, in a browser. The server figures are +measured natively on the engine; the rest are estimates until the named benchmarks run. + +| Action | Path | Time | +|---|---|---| +| Click a header to sort | request, `apply` (sort one key: 33 to 46 ms measured), encode a page, reply, decode, repaint | about 150 ms on a 50 ms round trip (B3) | +| Type in a text filter | debounce (250 ms), then request, `apply` (text filter: 9 ms measured), reply, decode, repaint | about 350 ms after the last key (B3) | +| Scroll into pages not held | request, a read of the cached view, reply | about 110 ms a page; the held margin of one page each side hides it at reading speed | + +A text filter is debounced through the query's `debounce`, so a word typed quickly is one request, not one per +key. The table keeps showing its rows, with the header marking the sort in flight, until the reply replaces them. + +**Hybrids.** Two were considered and one is kept for later. + +- *Sorting or filtering the held rows locally while the reply is in flight* is rejected. The window holds a slice + of the old order. Its local re-sort is not a slice of the new order, so the rows move once to a wrong place and + again to the right one, and a local filter shows a subset of 1,600 rows as if it were the subset of 100,000. +- *Local work when the window holds the whole view* (an `Exact` total no larger than the rows held, nothing + awaited) is sound: a filter that leaves 300 rows could be re-sorted with no request. It needs an `Engine` on the + client with the server's collator and a rule for handing back to the server when the view grows. It is not + specified here; the 150 ms above is the cost of leaving it out. + +## Configuring a table + +A user arranges a table: the order, visibility, pinning and widths of its columns, a chain of sort keys, and +filters set from each column's header. All of it is state of the client's table, in three values, each of which +a document may bind (then it is controlled, as `selection` is) or leave to the table: + +| Value | Shape | Held by | +|---|---|---| +| `layout` | `{"order": [id…], "hidden": [id…], "pinned": n, "widths": {id: units}}`, and where used `"groups"` ([Column groups](#column-groups)) and `"units"` ([Display](#display)) | `table::ColumnLayout` | +| `sort` | `[{"column", "direction"}…]`, most significant first | `TableRows::setSort` | +| `filters` | A `FilterSpec`: column filters and group filters | `TableRows::setFilter` | + +It works the same in client and server mode: layout reaches the server only as the columns a query names; sort +and filters go where the mode puts them. + +### Columns: order, visibility, pinning, width + +- **Reorder.** Dragging a header moves its column. With the header focused, `Ctrl+Shift+Left` and + `Ctrl+Shift+Right` move it, and the header's menu has "Move left" and "Move right". `Alt` with an arrow is + not used: in a browser it is Back and Forward. The selection column and a group heading are not columns and + do not move. +- **Hide and show.** The header's menu has "Hide column"; the table's menu opens a column chooser, a list of every + column with a check box, in order, with the same move actions as "Move up" and "Move down", which stop where + "Move left" and "Move right" do. At least one column stays visible. +- **Pin.** The first `pinned` columns of the layout do not scroll sideways: they stay at the leading edge, and + are always in the column window. The header's menu has "Pin column", which moves the column to the end of + the pinned ones, and "Unpin". The selection column is always pinned and is not counted. Pinned columns may + take at most half the table's width; while the table is narrower than that allows, the last pinned columns + scroll with the rest, and the stored count is not changed. At 300 columns this is what keeps a row's name + beside whichever of its values the user has scrolled to. +- **Resize.** Dragging a header's trailing edge sets the column's width in units; a width the user set stays as + set, whatever the cells measure. A stored width is the content's, as a declared fixed width is: each backend adds + its own padding around it (`TableMeasure::padding`: Qt Quick's cell padding, the terminal's gap), so a stored + layout means the same on every backend. Double-clicking the edge removes it, and the column takes its declared + width again. +- **Reset.** "Reset columns" restores the declared order, visibility, pinning and widths. + +`ColumnLayout` holds the order and the hidden set, with `setWidth(id, std::optional)`, `widths()`, +`setPinned(n)`, `pinned()`, and `value()` and `apply(value)` for the stored shape. + +**A layout survives a changed table.** Ids are the columns' string ids. One rule fits a layout to a table's +columns, whether the layout is a stored one (`apply`) or the table's own when its description takes a new +revision (`rebuild`): + +- an id the table does not have is dropped, from `order`, `hidden` and `widths` alike; +- a column the layout does not mention takes its declared visibility, and is placed after the nearest column + before it in the declared order that the layout does place, or first when there is none, so a new column + appears where its author put it, as its author declared it, and not at the end; +- `pinned` is clamped to the visible columns; +- if that leaves no column visible, the first declared column is shown. + +**Persistence.** The layout is part of the table's persisted state ([Persisted state](#persisted-state)). + +**Document vocabulary.** `layout` (the value; bound, it is controlled), `onLayoutChange` (after a user's change, +with `event` the new layout), `configurable` (a literal: `true`, the default, `false`, or a list of `reorder`, +`hide`, `pin`, `resize`), and on a column `locked` (a literal flag: the user cannot move, hide, pin, unpin or +resize it). `locked` is not called `fixed`: `fixed(n)` is a column's width sizing. Element values: `layout`, +`visibleColumns` (ids in order) and `hiddenCount`. Every key is optional. + +**With levels.** A hidden column that is neither sorted nor filtered is not in the column window, so no query +names it and its level is not loaded for it. Showing it fetches that column for the held pages. + +**With the column window.** Hiding a column returns its realized cells to their pool and creates none; moving +one creates none unless it moves into the window. + +### Sort chains + +The engine, `TableQuery` and the document's `sort` take a list of keys; what a user needs is a way to build one. + +- A plain click on a sortable header sorts by that column alone, ascending, or descending when it already is + the chain's first key, ascending. +- `Shift`+click adds the column as the last key, ascending; on a column already in the chain it flips that key's + direction and keeps its place. `Shift+Enter` and `Shift+Space` on a focused header do the same. +- The header's menu has "Sort ascending", "Sort descending", "Add to sort" and "Remove from sort", so the chain + can be built without a modifier key, on a touch screen included. +- The table's menu opens a sort dialog: the keys in order, each with its column, its direction, move up, move + down and remove, and "Add key". +- Every header in the chain shows its direction; with more than one key each also shows its place in the chain, + from 1. A header's accessible description says "sorted ascending, key 2 of 3". +- A chain has at most `maxSortKeys` keys: 8 by default, and up to 32 where a model's table's `limits` raise it, + which the description carries as `TableCapabilities::maxSortKeys` so the client knows the bound; a table over + `rows` takes it as the literal `maxSortKeys` on the node. A key costs one comparison only between rows that tie on every key before it, so a long + chain costs little more than a short one; the default is what a header shows legibly. At the bound, adding a + key is refused with a message in the status line, not by dropping the first key. + +`sort` and `onSortChange` keep their shapes. `Table::sort` carries the whole chain to the backend. + +### Filters from the header + +A filterable column's header has a filter button, drawn filled while the column has a filter and named so for +assistive technology ("Name, filtered"). It opens a menu with three parts. + +1. **Values.** A search field over a list of the column's distinct values, each with a check box and the number + of rows that have it, under "(Select all)" and, when the column has empty cells, "(Blanks)". Typing narrows the + list; "(Select all)" then means the values the search shows. +2. **Conditions**, by the column's kind, each one `FilterEntry`: + + | Kind | Conditions | + |---|---| + | `Text` | equals, does not equal, contains, begins with, ends with; match case | + | `Integer`, `Key`, `Decimal`, `Quantity`, `Number` | =, ≠, <, ≤, >, ≥, between | + | `Date`, `DateTime` | the same, with a date picker; and the values list as a tree of years, months and days | + | `Bool` | the values list alone | + | `Custom` | is empty, is not empty | + + Two conditions may be joined by "and" or "or" (`combine`). +3. **Clear filter.** The table's menu has "Clear all filters". + +A column is filterable when it has an `id` and the document does not say `filterable: false`. `filters` is served +on every table, bound or held by the table, with `onFiltersChange`. + +**The value-set operator.** `FilterEntry::oneOf` is a list of operand texts: + +```cpp +struct FilterEntry { + // … the existing operators … + /// Matches a cell whose value equals any of these. Each is parsed for the column's kind, as `eq`'s operand is. + std::optional> oneOf; +}; +``` + +- It matches as `eq` does, against any member: text by fold unless `caseSensitive`, numbers exactly. It never + matches an empty or invalid cell, and is `Unknown` on an unloaded one. +- Ticked values are one `oneOf` entry in `include`; "(Blanks)" ticked adds an `isEmpty` entry beside it, which + `combine: any` joins. Unticking a few values of many is the same entry in `exclude`. A menu sends whichever side + is smaller, so unticking one value of 50,000 sends one value; when the two sides are equal it sends the + unticked side, an exclude, so unticking one of two values sends one excluded value. +- `compileFilter` parses the members once into a set; a row is matched by one lookup, whatever the set's size. +- `QueryLimits::maxSetValues` (10,000) bounds one entry, `maxQuerySetValues` (20,000) the members of every set + of one query together, and `maxQuerySetBytes` (1 MiB) their text; over any of them is `LimitExceeded`. The + entry bound alone would allow a query of millions of values across its columns. When both the ticked and the + unticked side exceed it, the menu disables the list and says so: the user narrows with a condition. + +**Distinct values.** + +```cpp +struct DistinctRequest { + std::string column; + /// In place of `column`: a declared group's id, for values pooled over its columns. + std::string group; + /// Narrows to values whose text contains this, folded; empty for all. + std::string search; + /// For `Date` and `DateTime`: `Value`, or the bucket to count by. + DateBucket bucket = DateBucket::Value; // Value, Year, Month, Day + std::int64_t offset = 0; + std::int64_t limit = 200; +}; + +struct DistinctValue { + std::string text; // as the cell shows it + std::string operand; // as a filter entry takes it + std::int64_t count = 0; +}; + +struct DistinctValues { + std::vector values; // in the column's ascending order + std::int64_t distinct = 0; // values matching `search`, before offset and limit + TotalKind distinctKind = TotalKind::Exact; + std::int64_t blanks = 0; // rows whose cell is empty + std::int64_t invalid = 0; // rows whose cell is invalid; they are under no value + bool partial = false; // rows left out because a cell was unloaded +}; + +[[nodiscard]] std::expected +distinctValues(DataSource const& source, TableQuery const& query, DistinctRequest const& request, + ApplyOptions const& options = {}); +``` + +- **Which rows.** The rows that pass `query.filters` with the named column's own entry in `filters.columns` + removed. So each column's list shows what the other columns' filters leave, and a value the column's own filter + unticked stays in the list to be ticked again. Groups stay applied as they are. +- **Which values.** Valid cells, grouped by the key the column sorts and filters by: text that folds alike is one + value, shown as its first row's text. Empty cells are counted in `blanks`. Invalid cells are not values and + are counted in `invalid`; the menu says under the list how many cells could not be read, and offers nothing + to tick for them. +- **Unloaded.** A row whose cell in the column is unloaded, and a row another column's filter leaves undecided, is + in no count, and sets `partial`. The menu then says the list may grow. +- **Order and bound.** Values are in the column's ascending order. `limit` is clamped to `QueryLimits::maxLimit`; + `distinct` is counted up to `QueryLimits::totalCap` and is `AtLeast` at the cap. A column of 100,000 distinct + values is paged and searched, never sent whole. +- **Dates.** With a bucket, a value is a year, a month or a day, its `operand` the two ends of a `between`; the + menu draws the tree by asking for years, then the months of an opened year, then its days. The tree's filter + is include-only: it opens with every box unticked and no "(Select all)" (or with the buckets a stored filter + covers ticked), ticking a year or a month covers the buckets under it, and Apply sends one `between` per + ticked bucket under `combine: any`, with `isEmpty` beside them when "(Blanks)" is ticked; with nothing ticked + it clears the column's values filter. Buckets that touch (the next begins the day, or the second, after the + previous ends) are merged into one `between` first. A selection still over `QueryLimits::maxEntries` (32) + entries applies nothing, and the menu says "Too many dates to list; filter with a condition". +- **Levels.** The column's level is an `order` level of the request: it is needed for every candidate row. +- **Client mode.** `Engine::distinctValues(request)` answers from the key columns the engine holds. +- **Server mode.** `TableQuery::distinct` carries the request through the table's own action, so the model's + scope applies; the reply is a `Page` with no rows and `Page::distinct` set. +- **Validation.** `validate` holds a distinct request to the query's rules. Exactly one of `column` and `group` + is set. The column, or every column of the group, exists and the caller may read it (`UnknownColumn`, + `ColumnNotReadable`): a values list is a read of the column. `search` is at most `maxTextLength` bytes and + `offset` at most `maxOffset`. A query that sets both `keys` and `distinct` is `InvalidSpec`. In the filter, a + group's `exclude` entries count toward `maxEntries` with its `include` and are bounded by `maxTextLength` as + they are, and so is every member of a `oneOf`. +- **Caching.** A distinct reply is kept by the table's rows (`WindowRows`), keyed by the query's body, so reopening a + menu costs nothing; each table keeps its own, and they are not shared between tables. At most 64 replies are kept, + the oldest going first. `Page` declares `distinct` as an open member beside `awaiting`: any change of the table's + record drops them, because any row may change a count, and so do a reconnect and a new revision; a reply asked for + before such a change answers its menu and is not kept. + +Top-N filters are not included: "the ten largest" is a property of the view's order, not of a cell, and belongs +with a ranking function over the view. + +### Column groups + +Several columns can hold the same kind of thing: `companyA`, `companyB` and `companyC` each hold a company. A +**column group** names them, so one filter asks about all of them: "a company is F", "F and S are both there", +"at least two of them are F or S". The columns stay ordinary columns, shown, hidden, sorted and filtered one by +one as well. + +**Declaring a group.** A typed row declares its groups once, beside its levels: + +```cpp +struct ColumnGroup { std::string_view id; std::span columns; }; + +struct DesignRow { + static constexpr auto columnGroups() noexcept; // {"company", {"companyA", "companyB", "companyC"}} +}; +``` + +`DataSource::groups()` returns them (empty by default); the row's schema carries `x-column-group` on each member +property, and `deriveColumns` copies it. A document table over `rows` declares `groups` as parts +`{id, label, columns}`. A group has 2 to `QueryLimits::maxGroupColumns` (16) columns of one kind, and a column +is in at most one declared group; a declaration that breaks either is refused where the columns are read. + +A user may also form a group: the column chooser has "Group columns…", which offers columns of one kind and asks +for a name. Such a group is part of the layout (`"groups": [{"id", "label", "columns"}]` in its stored shape) and +is fitted to the table as the layout is: a column the table lacks leaves the group, a column stays only in the +first group that holds it, and a group left with fewer than two or more than 16 columns, or repeating an earlier +group's id, is dropped, with any filter on it. The column chooser lists the groups a user formed, each with +"Remove group", which removes the group and any filter on it. + +**Drawing a group.** A group draws as a one-level heading on its own line above the column headers and below any +header bands ([`editing.md`](editing.md#header-bands)), its label over its columns and its filter button at its +end, while its columns stand together in the layout. It is not a band: a group whose columns the user moved apart +is not split into runs as a band is. + +**The filter.** `GroupFilter` is the engine's filter over several columns, with a name, a quantifier, a mode +and excludes: + +```cpp +enum class GroupMode : std::uint8_t { + Columns, // count the columns whose cell satisfies the entries + Together, // every entry is found, each in a column of its own +}; + +struct ColumnCount { + enum class Kind : std::uint8_t { Any, All, AtLeast, Exactly } kind = Kind::Any; + std::int64_t n = 1; // for AtLeast and Exactly +}; + +struct GroupFilter { + std::string group; // a declared group's id; or + std::vector columns; // the columns themselves + GroupMode mode = GroupMode::Columns; + ColumnCount match; // Columns mode only + Combine combine = Combine::Any; // Columns mode: how one column's cell must satisfy `include` + std::vector include; + std::vector exclude; +}; +``` + +In JSON a group is `{"group" | "columns", "mode", "match", "combine", "include", "exclude"}`, with `match` one of +`"any"`, `"all"`, `{"atLeast": n}` and `{"exactly": n}`. A filter that sets only `columns`, `combine` and +`include` is the plain group: the entries match on any of the columns. + +Write k for the number of columns and say a column *satisfies* the entries when its cell matches any of them +(`combine: any`) or every one of them (`combine: all`), by the rules of a column filter: an empty cell matches +nothing but `isEmpty`, and an invalid cell nothing but `notEmpty`. + +- **`Columns` mode.** Count the columns that satisfy the entries. The row passes when the count is at least 1 + (`any`), k (`all`), at least n, or exactly n. +- **`Together` mode.** The row passes when the entries can be given a column each, no column twice, such that + each entry matches its column's cell. `match` and `combine` are not used. It takes at least 2 include entries + and at most as many as the group has columns, so at most 16. + A group with no include entry is an exclude-only group in either mode: only its `exclude` decides. +- **`exclude`.** The row is rejected when any column's cell matches any exclude entry: "none of the companies is + X". +- Groups combine with each other and with column filters by AND, so "F somewhere and S somewhere, in the same + column or not" is two `any` groups. + +The cases, as filters on the group `company`: + +| Wanted | Filter | +|---|---| +| At least one of the columns is F | `{"group": "company", "include": [{"eq": "F"}]}` | +| F and S are both there, in two of the columns | `{"group": "company", "mode": "together", "include": [{"eq": "F"}, {"eq": "S"}]}` | +| At least one of F, S, T in any of the columns | `{"group": "company", "include": [{"oneOf": ["F", "S", "T"]}]}` | +| At least two of the columns hold F or S | `{"group": "company", "match": {"atLeast": 2}, "include": [{"oneOf": ["F", "S"]}]}` | + +The second and the fourth differ, which is why both exist: + +| `companyA`, `companyB`, `companyC` | any is F | F and S together | at least 2 are F or S | exactly 1 is F | +|---|---|---|---|---| +| F, S, X | yes | yes | yes | yes | +| F, F, X | yes | **no** | **yes** | no | +| S, F, F | yes | yes | yes | no | +| F, X, Y | yes | no | no | yes | +| X, Y, Z | no | no | no | no | + +Entries are any `FilterEntry`, not only values: "two of the three dates are after 1 May" is `atLeast: 2` with a +`gt` entry. + +**Deciding `Together`.** It is a matching between entries and columns, found in C++ for each row; no store is +asked to express it. The engine reads each of the row's k cells once and gets, per cell, the set of entries it +matches (for value entries one lookup of the cell in a map from value to entries; a condition is tested per +entry), then looks for a matching that covers every entry by augmenting paths over those bit sets. With at most +16 entries and 16 columns one row costs at most 16 augmentations of at most 16 steps, and a row whose cells +match no entry is rejected after the k reads. + +**Unloaded cells.** An entry on an unloaded cell is `Unknown`, so a column may satisfy the entries, not satisfy +them, or be unknown. Write y for the columns that satisfy and q for the unknown ones. + +| Quantifier | Yes when | No when | Otherwise | +|---|---|---|---| +| `any` | y ≥ 1 | y + q = 0 | `Unknown` | +| `all` | y = k | y + q < k | `Unknown` | +| `atLeast n` | y ≥ n | y + q < n | `Unknown` | +| `exactly n` | y = n and q = 0 | y > n, or y + q < n | `Unknown` | +| `together` | a matching covers every entry using known matches only | none does even counting every unknown cell as matching every entry | `Unknown` | +| `exclude` | (rejects) a known cell matches | no cell matches and none is unknown | `Unknown` | + +So `atLeast 2` over three columns is `Yes` with two known matches and the third unloaded, `No` with no match and +one unloaded, and `Unknown` with one match and one unloaded. A row is decided as soon as its known cells decide it, +and invariant 1 holds for groups as for columns. + +**The menu.** A group has a filter entry of its own: in the table's menu, in each member column's header menu +("Filter Company, 3 columns…"), and, while its columns stand side by side in the layout, as a header over them +with its own filter button. Its menu is a column's, with two additions: + +- the values list is pooled: `DistinctRequest::group` names the group, a value's count is the rows that have it + in at least one of the group's columns, "(Blanks)" is the rows with an empty cell in at least one of the + group's columns, which are the rows ticking it admits (an `isEmpty` entry under `any`), and the rows + considered are those passing every other filter, this group's own removed. A row with an unloaded cell + in the group contributes its known cells and sets `partial`; +- a line under the list chooses how the ticked values must be found: "in any column" (the default), "in every + column", "in at least N columns", "in exactly N columns", or "all of them, each in a column". The first four + are one `oneOf` entry with a `match`; the last is one `eq` entry per ticked value in `together` mode, and is + offered while at least 2 values are ticked and no more than the group has columns. + +**On a server.** `apply` evaluates every form above. + +### The status line + +A table has one line under its rows where it says what the rows alone cannot. It is part of the table, drawn +by each backend from `Table::status`, and it is where every refusal this document mentions is shown. + +| Part | Shows | Examples | +|---|---|---| +| Counts, at the leading edge | The view's size and what is still coming, from `TableRows::counts` | "9,093 rows"; "100,000 or more"; "12 so far, 40 loading"; "3 of 9,093 selected" | +| State | A level that failed, with "Retry"; a fetch that failed, with its error and "Retry" | "Recipe data could not be loaded. Retry" | +| Message, at the trailing edge | The latest refusal or notice, until the user's next gesture on the table or for six seconds | "A table sorts by at most 8 columns" (the table's bound); "Copied 200 rows, 12 cells were not loaded" | + +- "Retry" sends the table's query again with `TableQuery::retry` set, which makes the level cache load the + failed keys the reply needs at once ([The server level cache](#the-server-level-cache), rule 11). +- A fetch that failed offers "Retry" too: the refetch carries the same flag, so a level that failed with it is + tried again in the same request. +- The line is a polite live region for assistive technology: a message is read out once, a count when it + settles. +- **When it shows.** A model-backed table has it always: its counts are not visible any other way. A table + over `rows` shows it while it has a state or a message, and otherwise takes no space. A document sets + `status: true` to show it always or `status: false` to never show it; with `false` a message goes to the + session's notifications instead, so a refusal is never silent. +- The counts are also element values (`viewCount`, `viewCountKind`, `undecided`, `selectedCount`, `awaiting`, + `failed`), so a document that hides the line can say the same things in its own words. + +### Copy + +`Ctrl+C`, and "Copy" in the table's menu, put the selection on the clipboard as text. + +- **What.** The selected rows, in view order, by the visible columns, in layout order: one line a row, cells + separated by tabs, each cell its display text as the column formats it, in the display unit the user chose. + A tab or a line break inside a cell's text is written as a space. A column's own `cell` template is not + copied; its value's text is. With no row selected, the focused cell's text is copied. "Copy with headers" + puts the columns' labels on a first line. +- **Rows and columns the client does not hold.** A server-mode table fetches them: keyed queries naming the + visible columns, `maxKeys` rows a request, for at most `SessionOptions::maxCopyRows` (10,000) rows. Over + that the copy is refused with a message in the status line. +- **Unloaded cells** are copied as empty, and the message says how many there were. Copying does not wait for + a level. +- **What the status line says.** "Copied {n} rows" ("Copied 1 row"), with ", {m} cells were not loaded" ("1 cell + was not loaded") when there were any. A fetch that failed says "The rows could not be copied: {reason}", and a + backend with no clipboard "The rows could not be copied: there is no clipboard"; neither changes the clipboard. + A copy whose rows have all left the view changes nothing and says nothing, and a copy started before another + whose rows arrive later writes nothing. +- The text reaches the clipboard through `IViewBackend::copyText`. + +Writing a view to a file (CSV, a spreadsheet) is not part of the table: it is an action of the application +over the same query, which runs on the server and is not bound by what a client holds. + +### Persisted state + +A table's arrangement outlives the screen: its column order, hidden and pinned columns, widths and display +units, its sort chain, its filters, the groups a user formed, and its saved views. Every table stores and loads +it through one interface the application injects. Selection and scroll position are not arrangement and are +not stored. + +```cpp +/// Which table's state. No member names a person: a store keeps one person's state apart from another's itself. +struct TableStateKey { + std::string application; + std::string model; // the model's type; empty for a table over a document's rows + std::string table; // the table's id; for a `rows` table, the node's id + std::string qualifier; // the screen's id, or what the table's `persist` names + std::string part; // "state", "views" or "shared" +}; + +struct StoredTableState { + std::string json; + std::string revision; // names this stored document; opaque +}; + +enum class SaveOutcome : std::uint8_t { Saved, Conflict, Refused }; +struct SaveResult { + SaveOutcome outcome = SaveOutcome::Saved; + std::string revision; // of what is stored now + std::string reason; // for Refused +}; + +/// An `expected` revision that stores only when nothing is stored under the key, and answers `Conflict` +/// otherwise. +inline constexpr std::string_view kNoDocument = "-"; + +class ITableStateStore { +public: + virtual ~ITableStateStore() = default; + /// The stored document, or nothing when none is stored. + virtual async::Completion> load(TableStateKey const& key) = 0; + /// Stores `json`. With `expected` empty it replaces whatever is stored; with `kNoDocument` it stores only when + /// nothing is stored; otherwise it stores only when the stored document has that revision. It answers + /// `Conflict` with the current revision when the condition does not hold. + virtual async::Completion save(TableStateKey const& key, std::string json, + std::string expected = {}) = 0; + virtual async::Completion remove(TableStateKey const& key) = 0; + /// Whether the store keeps the `shared` part for everyone rather than for one person. + [[nodiscard]] virtual bool shares() const { return false; } + /// Applies one operation (add, replace, rename or remove one view; see "Saved views") to the `shared` part, + /// under the `expected` rule of `save`. A store that does not share answers `Refused`, "this store does not + /// share views", which `refusePublish` gives it on the store's own executor. Pure: the interface owns no + /// executor to deliver a default answer on. + virtual async::Completion publish(TableStateKey const& key, ViewOperation const& operation, + std::string expected) = 0; +protected: + static async::Completion refusePublish(exec::IExecutor& executor); +}; +``` + +`kNoDocument` lets a save say "I loaded nothing": a table whose `views` part was empty when it loaded saves its +first view with it, so two windows that both start from no views cannot overwrite each other's first view. An +empty `expected` cannot say that, because it means "replace whatever is stored". + +- **One place.** The store is `SessionOptions::tableState`, a `std::shared_ptr`. The session is + what every table surface reaches: a document table over rows, a model-backed table, a collection, in client + and in server mode. A table mounted from C++ with no session is given the store through its `TableRows`. With + no store, a table keeps its state for as long as it is mounted. +- **Asynchronous.** Every call returns a completion; nothing waits on the thread that paints. A store delivers + its completions on an executor it owns, as a preferences store does. +- **The person is the store's.** A key names no person, because a client must not be able to name someone + else's. The framework's default store derives the person on the server from the verified session; an + application's own store scopes by whoever it knows is signed in. +- **What a key distinguishes.** Tables of two instances of one model type share a key and so an arrangement: + the state belongs to the kind of table on a screen, not to the data it shows. A table over `rows` needs an + `id` on its node to have a key; without one it persists nothing, and a `persist` that says otherwise is + refused when the document loads. +- **No size limit.** A state is as large as the arrangement it holds: a filter that ticks 20,000 values is + stored whole, and a table keeps as many views as the user saves. Neither the interface nor the framework + bounds a document, and a store may not truncate one. An operator who wants a ceiling sets a quota on the + server ([The framework's stores](#the-frameworks-stores)); a save over a quota is `Refused`, and the table + says so in its status line and keeps its arrangement. + +**What is stored.** JSON documents per table, each with a version: the arrangement and the saved views below, and the shared views, of the views' shape ([Saved views](#saved-views)): + +```json +{ "version": 1, + "layout": { "order": ["id", "name"], "hidden": ["notes"], "pinned": 1, "widths": {"name": 24}, + "groups": [{"id": "g1", "label": "Company", "columns": ["companyA", "companyB"]}], + "units": {"weight": {"mass": "g"}} }, + "sort": [{"column": "name", "direction": "asc"}], + "filters": { "columns": {}, "groups": [] }, + "view": "Open orders" } +``` + +```json +{ "version": 1, "default": "Open orders", "defaultOnMount": false, + "views": [{ "name": "Open orders", "layout": {}, "sort": [], "filters": {} }] } +``` + +- `part: "state"` is the arrangement in use; `part: "views"` is the saved views; `part: "shared"` is the views + published for everyone ([Saved views](#saved-views)). +- `view` names the saved view the arrangement was taken from, or is absent. The menu shows the name, and shows + it as modified when the arrangement differs from that view; nothing more is stored for it. +- **Versions.** A document of an older version is brought forward by the framework, one version at a time, when + it is read. One of a version the framework does not know is not used and is reported; the table starts from + its defaults, and writes its own version when the user next changes something. + +**Fitting stored state to the table.** State is fitted to the description the caller receives, never the other +way round, and a table is never refused over its state: + +- columns are fitted as a layout is ([Columns](#columns-order-visibility-pinning-width)); +- a sort key on a column the table lacks, or that is not sortable, is dropped; +- a filter on a column or group the table lacks, one that does not compile for the column's kind, and a unit + the description does not list are dropped, each reported once at the table's path; +- a user-formed group that is left with fewer than two columns is dropped with its filter; +- what was dropped because the caller's description lacks the column or group is **carried**: it is kept + beside the fitted state and written back as it was, a carried column keeping its place after the column it + followed. A table whose columns depend on the session therefore keeps a user's place for a column that is + absent now and returns later. What was dropped for any other reason is gone at the next save. + +**When it is loaded.** A table loads its state before it shows rows. Its `TableRows` starts in a restoring +state: a server-mode table sends no query, and a client-mode table draws placeholder rows. When the load +completes it applies the fitted state and then makes its first query, so the first rows are in the stored order +and under the stored filters, with no rows of the default order shown first and no second fetch. + +- The session keeps every state it has loaded or saved, by key, for its lifetime. A table mounted a second + time is restored from it at once, with no request; the first mount of a screen is the only one that waits. +- A load that has not completed after `SessionOptions::tableStateTimeout` (300 ms) is given up on for the first + query: the table starts from its defaults. If the state arrives later it is applied, at the cost of one more + query, unless the user has touched the table meanwhile (scrolled it, selected in it or changed its + arrangement), in which case it is kept for the next mount and not applied under the user's hands. +- A load that fails is reported once through the session and the table starts from its defaults. Its changes are + still saved. + +**When it is saved.** A change marks the state unsaved; a save goes out when the arrangement has not changed for +`SessionOptions::tableStateDebounce` (500 ms), and at once when the table unmounts. One save per key is in +flight; a change made during it is one more save after it. A failed or refused save is reported in the status +line and the table keeps the arrangement. A client that is closed loses at most the changes of the last +debounce. + +**Two windows, two devices.** The two parts differ. + +- `state` is saved with no expected revision: the last save wins, whole document. Nothing is merged: an + arrangement is a choice, and half of one window's filter joined to half of another's is neither's. Every + window and device reaching one server has this guarantee in full. Two servers over one preferences store share + no lock: two saves of one key reaching two servers in the same moment can interleave, and the worst outcome is + a head naming a removed segment, which is a failed load until the next save, and segments no intent names, + which stay in the store. A deployment of several servers that needs the guarantee across them keeps state in a + store with a conditional write. +- `views` is a list, and losing a view another window saved is losing work. A change to it is one operation + (add, replace, rename or remove one view, or set the default). The table saves with the revision it loaded, + or with `kNoDocument` when it loaded nothing; on `Conflict` it loads again, applies its one operation to what + is stored now, and saves once more, with the revision it read. When that reload finds nothing stored, the one + retry saves with an empty `expected`: a store that does not honour `kNoDocument` answers `Conflict` over + nothing, and one that does cannot, unless the document was removed in between. +- A mounted table does not follow saves made elsewhere; it reads its state when it mounts. + +#### The framework's stores + +| Store | Keeps state in | Use | +|---|---|---| +| `PreferencesTableStateStore` | The application's `IPreferencesStore`, through the server's `morph.tableState` model, the person derived on the server | The default. A host that has a preferences store gives every table persistence with no further wiring. | +| `MemoryTableStateStore` | A map | Tests, and a host that wants state for a session only. Built with `Sharing::Private` by default, it does not share and offers no publishing; built with `Sharing::Shared`, it keeps the `shared` part for everyone | +| A host's own | Anything: a settings file, a browser's local storage for a build with no server | The interface is all a host implements | + +**`PreferencesTableStateStore` has its own path to the preferences store.** It does not go through the +preferences model, whose `maxValueBytes` (16 KiB) bounds a preference and would bound a table's state. The +client half calls a model of its own, `morph.tableState`, through the interpreter's `Dispatcher`, so it travels +the same bridge and session as the screen's models; the server half, `TableStateModel`, reads the person from +the verified session exactly as the preferences model does, refuses a caller with no verified person, and +writes to the same `IPreferencesStore` the application already has. Table state therefore has one home, the +application's preferences storage, and no second database. + +How it keeps a document of any size in a store built for small values: + +- **Where.** Entries of the caller's person and the key's `application`, under the scope + `morph.table.`, the digest being of the key's `model`, `table` and `qualifier`. A digest keeps the + scope inside a preference name's length whatever the ids are; the head entry repeats the key in clear for + whoever reads the store. +- **Small documents.** A document of at most `TableStateOptions::segmentBytes` (12 KiB) is one entry at the + point ``: `{"revision": …, "document": …}`. Nearly every state is this. +- **Large documents** are written as segments. Each segment is an entry at the point + `..` whose value is a JSON string holding a slice of the document's text, so every + entry is valid JSON, as a preferences store expects, and no longer than `segmentBytes`, which is inside the + size such stores are built for. The head entry at `` is `{"revision": …, "segments": n, "bytes": b}`. +- **Order of writes.** The segments of a new revision first, then the head, then the removal of the previous + revision's segments. A reader takes the head and then the segments it names, so it reads either the old + document or the new one and never a mixture. Reads take no lock: a segment missing because a save replaced the + head meanwhile sends the reader back to the head stored now, so a load answers the new document and a `read` + answers the new revision, which the client starts again from. A save that stops halfway leaves segments no head + names; the next save of that key removes them. A segment missing under an unchanged head is a failed load. Every write of one key + (a save, a removal, a publish) holds that key's lock on the server, shared by all its model instances, so two + writes of one key run one after the other: the last wins whole, and no save removes segments another is still + writing. +- **`expected`.** The model compares it with the head's revision before it writes, under the key's lock. Two + servers over one preferences store share no lock, and the store has no conditional write, so two saves that + reach two servers within the same moment can both pass the comparison and interleave their writes, with the + outcome "Two windows, two devices" states. That window is the store's call time, not a user's think time; a + host store with a conditional write closes it. +- **Transport.** A call is bounded by an envelope (8 MiB). `save` carries a document of up to 1 MiB; a larger + one is sent as parts of 1 MiB under one upload id and committed when the last arrives. `load` returns the + first 1 MiB and the document's revision and size, and the client asks for the rest by offset, starting again + if the revision changes meanwhile. Loads made in one turn of the owner go out as one call naming all their + keys (at most 256 a call), so a screen of five tables waits for one round trip. Each key is answered alone: a + key out of bounds, or one whose segment is missing, fails its own load and no other. A reply stops adding heads + once their text, as it travels escaped in the reply and again in the envelope, would pass 6 MiB, and answers + the remaining keys as deferred; the client asks for those in its next call, so a screen of large states takes + a few round trips and no reply outgrows its envelope. A server keeps at most four uploads in parts open per + person: a save that would start a fifth is `Refused`, "too many table-state uploads in progress", and the + client sends it again after a session's `tableStateTimeout`, until one of the four ends. It drops an upload + whose next part has not come within + `TableStateOptions::uploadExpiry` (30 s), and, with a quota set, refuses a part that takes its upload past it. +- **Bounds.** `application`, `table`, `qualifier` and `part` are 1 to 256 bytes each, and `part` holds no `.`, + which would name another part's points; `model` is 0 to 256 bytes, empty for a table over a document's rows. + `TableStateOptions::maxBytesPerPerson` is the operator's quota across one person's stored state, in every application, and across the shared views, which count as + one more account; it is unset by default, and then nothing limits + a state. The model checks it before it writes, against a usage total it keeps for the person. A preferences + store has no conditional write, so two saves of one person's different keys in the same moment can both pass + the check: each such race of two different keys can leave one document uncounted, so the quota is overshot by + one document per race, and races add up; a ceiling tolerates that. A usage that has fallen + below what a replace removes (a quota set over states stored before it, that race, a usage write the store + refused) counts as nothing rather than going negative, so it never locks a person out. +- **Reserved names.** The preferences model writes wherever its caller names, so it refuses an application + `morph.tableState` and a scope that starts with `morph.table`, on every call: without that rule a person could + overwrite a state's head or the quota's usage entry through the preferences model. The same rule means a + person cannot reset their own quota. + +A document's `columns` and `saved` preference points that name a table hold no value of their own: their +editors read and write the table's state, a `saved` point its `view`, on a model-backed table and on a table over +`rows` alike. A point naming a table over `rows` that keeps no state (no store, `persist: false`) holds its choice as +a plain preference. A `saved` point without `of` names no table. + +**Document vocabulary.** `persist` is a literal on a table: `true` (the default), `false` (nothing is loaded or +saved), or a string, which becomes the key's qualifier in place of the screen's id, so the same table on two +screens shares one arrangement, or two tables of one screen keep theirs apart. + +**Bound values.** A `layout`, `sort` or `filters` the document binds is the document's: the stored value of that +part is neither applied nor saved, and the rest of the state persists as usual. A literal `sort` is the table's +default, and a stored one replaces it. + +### Saved views + +A saved view is a name with a `layout`, a `sort` and `filters`. A table's views are the `views` part of its +persisted state; the table's menu lists them, applies one, saves the current arrangement under a name, renames +and removes one, and marks one as the default. Applying one sets the three values, through their handlers where +they are bound, and records its name in the state's `view`. The view the `default` member names is applied +when the table mounts and no `state` is stored for it. A stored view is fitted to the table as its state is. + +- **The default first.** With `"defaultOnMount": true` in the views document, the default view's sort and + filters are applied at every mount, over those of the stored `state`; the stored layout still applies. It is + for a user who wants each session to start from the same order, and the menu sets it as "Start from the + default view". +- **Shared views.** A user may publish a view, under a name, for everyone who uses the table. Published views + are a third part, `part: "shared"`, of the same shape as `views`, which the store keeps for the application + and not for one person: a `TableStateKey` still names no person, and the store decides what the part means. + The table's menu lists them under the user's own, applies one as it applies one of the user's, and copies one + into the user's views with "Save as my view". + - **Who may publish.** Reading the part is the `morph.tableState` model's `load`, open to everyone who may use + the table. Writing it is a separate action of the model, `morph.tableState.publish`, carrying one operation + (add, replace, rename or remove one shared view), so the application's authoriser admits or refuses + publishing by action id, without reading a body. A user's own `save` or `remove` of the `shared` part is + refused. The part is no one's, so it is an account of its own under the operator's quota: with + `maxBytesPerPerson` set it is bounded as each person's state is, and a `publish` that would pass it is + `Refused`, "over the table-state quota", as a save is; without a quota nothing limits it, as for everyone. + - A shared view is changed under the `Conflict` rule, as a user's views are. The shared document has no + `default` and no `defaultOnMount`; they are the user's choice, kept in the user's own views document. + - **Which stores share.** `ITableStateStore::shares()` (default `false`) says whether a store keeps the + `shared` part for everyone. A table offers publishing only over a store that shares, so a host's own store + that does not never keeps a "shared" view for one person. `PreferencesTableStateStore` shares: it keeps the + part under the application's own scope in the preferences store, with no person. + +## Acting on rows + +A table is where a user picks the rows an application's action works on, and where they see what it did: a +selection that is the whole view, the application's own entries in the table's menus, rows an action changed +that stay in view, a row whose key an action changed, and rows an action is working on or failed on. + +### A selection of the view + +On a model-backed table the client holds a window, not the view, so "every row I see" cannot be a list of keys. +It is a description of the view, which the server turns into keys when an action runs. + +```cpp +/// What a user selected in one table. Its JSON is {"keys": […]}, or {"view": {…}, "except": […]}. +template +struct RowSelection { + struct View { + FilterSpec filters; // the view's filter, as the table queried it + std::vector retained; // the rows the view kept although they no longer match + std::string revision; // the view's `viewRevision` when the user selected it + }; + std::vector keys; // without `view`: exactly these rows + std::optional view; // with it: every row of that view, less `except` + std::vector except; +}; + +enum class SelectionPolicy : std::uint8_t { + Exact, // refuse when the view's rows may have changed since the user selected it + Current, // act on the view as it is when the action runs +}; + +struct SelectedRows { + std::vector keys; // in the table's source order + std::int64_t dropped = 0; // keys the caller may no longer see, left out +}; + +/// Calls the table's function on the caller's thread, the model's strand, and resolves on the table executor; +/// a Task handler awaits it. The model is not const because a table function is not. +template +[[nodiscard]] async::Completion> +resolve(Model& model, RowSelection const& selection, TableContext const& context, + SelectionPolicy policy); + +/// The body of `Table..resolve`, for an action of another model or a task off the model's strand. +template +struct ResolveRequest { + RowSelection selection; + SelectionPolicy policy = SelectionPolicy::Exact; +}; +``` + +`RowSelection` is the value an action receives; `table::Selection`, the set of selected keys +([`engine.md`](engine.md)), is what a client-mode table holds while the user selects. + +- **Making one.** On a model-backed table `Ctrl+A`, the + select-all box and "Select all" in the table's menu select the view: no row is fetched. `Ctrl`+click then + toggles a row in `except`, and a `Shift` range adds or removes a range of `except` through `keysOf`. A plain + click replaces the selection with that one key. A table held whole on the client selects all by keys, since it + holds them. +- **Its count.** `selectedCount` is the view's total less the keys of `except` the window still sees in the + view; a key of `except` that has left the view is dropped from it when the window learns so. The count is + exact when the total is and no key of `except` is unaccounted for; the element value `selectedCountKind` + (`exact` or `approximate`) says which, and the status line shows an approximate count with "about". +- **Its life.** A view selection is of one filter. A change of the filter, or of the retained rows by "Show only + matching rows", ends it: the selection becomes empty. A change of the sort keeps it, since the rows are the + same. +- **Not while membership is open.** A view whose filter waits for a level does not yet know which rows are in + it, and "the rows I saw" says nothing about them. While `undecided` is above zero, or `awaiting` names a + level a filtered column needs, select-all is disabled and the status line says why: "Select all is available + once 40 rows are decided", or "… once recipe data has loaded" when no row is undecided yet. A level only the + sort needs does not disable it, since order is not membership. +- **The view's revision.** Every page reply carries `viewRevision`, which names the view's membership: two + replies with the same revision describe the same rows, and the sort is not part of it. It is a digest of the + keys of the view's rows, taken in source order when the view is computed, a pass the computation makes + anyway; the view cache keeps it with the entry, and the retained rows merged into a reply are added to it. An + edit that leaves every row in or out of the view as it was, the session's own previous action included, + leaves the revision as it was; an edit that brings a row in or takes one out changes it. +- **Resolving.** An action of the table's model takes a `table::RowSelection<&Model::designs>` member, and its + Task handler ([`../core/coroutines.md`](../core/coroutines.md#task-handlers)) awaits + `resolve(*this, selection, context, policy)`. `resolve` calls the table's function on that model for the + caller, on the model's strand, so the caller's row scope and `mayRead` apply; then, on the table executor, it + computes the view's membership: the filter's rows with an empty sort, which the view cache holds under that + key when another request computed it, and the retained rows merged in. An action of another model, or a + server task, sends `Table..resolve` with the selection and the policy instead, under its own principal. A + key selection resolves to the keys the caller can still see, counting the others in `dropped`. A view of more than + `QueryLimits::maxSelectedRows` (1,000,000) rows is `LimitExceeded`. +- **When the rows changed.** Under `Exact`, `resolve` refuses with `TableErrorCode::ViewChanged` when the + revision differs. The client then takes the selection again from the view as it is now (its filter, its + current revision and retained rows, the same `except`), says "The rows changed since you selected them: 9,120 + rows now. Run on these?", and sends the action again with the new selection when the user confirms. +- **The action's input says which table.** `RowSelection`'s schema carries `x-selectionOf` with the + table's record, so the client knows which table an action works on + ([Rows at work](#rows-at-work-rows-that-failed)). +- **One filter language.** A server task that works on "the rows matching a filter" builds a view selection and + resolves it under `Current`, so the rows a user filters to in a header and the rows a task selects on the + server are chosen by the same code. +- **Copying a selection of the view** fetches the view's rows as pages naming the visible columns, in view + order, less `except`, for at most `maxCopyRows` rows; over that the copy is refused, as any copy is + ([Copy](#copy)). + +In a document a table's element value `selectionSet` is the selection's JSON on every table, for an action's +body. `selection` is the list of keys, and is empty while the selection is a view. + +### The application's menu entries + +A table's built-in menus ([Configuring a table](#configuring-a-table)) take the application's entries after +their own: + +- `cellMenu` and `headerMenu` are parts of the `menu` node's entry shape: `{label, icon, keys, checked, enabled, + onClick, items, description, visible}` or `{separator: true}`. +- **A cell's menu** opens on a right-click, the menu key or a long press on a cell. It focuses the cell, and + selects its row alone when the row is not already selected. It shows the table's entries ("Copy", "Copy with + headers", "Filter by this value", "Exclude this value"), a separator, then `cellMenu`, read in the row's scope + with `column` (the column's id) and `value` (the cell) beside `row`. +- **A header's menu** shows its built-in entries, a separator, then `headerMenu`, read in a scope with `column`. + An entry's `visible` decides which columns it appears on: `{"fn": "eq", "args": [{"ref": "column"}, "kind"]}` + shows it on one. +- **"Filter by this value"** sets the column's filter to a `oneOf` of the cell's operand in `include`, replacing + that column's entries; "Exclude this value" adds the operand to the column's `exclude`. On an empty cell they + use `isEmpty`; on an unloaded or invalid cell they are disabled. On a column of a declared group the entry + "Filter by this value in any " sets the group's filter instead. +- An entry's `keys` work while the table has focus. The columns its expressions read are fetched for every row, + as `rowTone`'s are. + +### Rows an action changed + +**Kept in view.** A user who changes the rows they filtered to (replaces a component in the designs that hold +it) expects to see the result, not to watch the rows vanish because they no longer match. With `retainChanged` +(a literal flag, default `false`) a row an action of this session changed stays in the view while it no longer +passes the filter. + +- The retained rows are the keys of the `ChangedRows` the session's own actions returned for this table, since + the filter last changed. A change of the filter, or "Show only matching rows" in the status line, clears them. +- `TableQuery::retain` carries them, at most `QueryLimits::maxRetained` (10,000) in all. An action whose rows + would take the set past the bound adds none of them, and the status line says so; the rows retained before + stay. +- **The view.** The rows that pass the filter, and the retained rows the caller may see, in the sort's order. A + retained row whose filter is `Unknown` is in the view, not undecided. `Page::unmatched` holds the indices, + into the reply's `rows`, of its retained rows that the filter rejects. +- **On the server** the base view of the sort and filter is the view cache's shared entry; the retained rows not + in it are ordered by the sort's keys and merged into it per request, a cost of the retained rows and not of + the table. A keyed query sees the merged view; distinct values ignore `retain`, being the filter's. +- **In client mode** `Engine::retain(keys)` does the same; its filter run admits those keys. +- **Ordering with the event.** The action's change event can reach the client before the action's reply, whose + `ChangedRows` adds the keys. On a table with `retainChanged`, while an action of this session that declares an + effect on the table is in flight, the window holds back the refetches the table's change events cause, for at + most `SessionOptions::retainHold` (2 s), and sends one when the action settles or the hold runs out, with the + retained rows added. Within the hold a row never leaves the view and comes back; past it, other users' + changes are not held up by a long action. +- A retained row that does not match draws muted, with a tooltip saying it no longer matches the filter, and + the status line counts them: "3 rows shown that no longer match. Show only matching rows". +- Retained rows are not stored with the table's state. A view selection names them, so it resolves to the rows + the user saw. + +**A key that changes.** An action may give a row a new key: saving a modified design as a new one. The action +returns the row in its `ChangedRows` with `from`, the key the row had ([A model's tables](#a-models-tables)). + +- The result walk collects both keys, so the change event names both. +- The session that ran the action moves what it holds by key from `from` to `key`: the row's membership of the + selection, the focus, its place among the retained rows, its busy or failed state and its cell drafts + ([`editing.md`](editing.md)). Both keys are then fetched, since the old one may still be a row (the original + design, unchanged). +- Another session's change event names both keys without saying which became which, so there a selected or + focused old key behaves as any row that left the view: it is dropped from the selection, and focus moves as + [Keyboard, focus and assistive technology](#keyboard-focus-and-assistive-technology) says. + +### Rows at work, rows that failed + +While the session runs an action whose input names rows of a table on screen, the rows it names are **busy**: +for a `RowSelection` member, the keys of a key selection or the held rows of a view selection that `except` does +not name; the row of a `CellEdit` or a `RowEdit` that a document runs as a mutation ([`editing.md`](editing.md)); +and the row of a `table::RowRef<&Model::designs>` member, a row key whose schema carries `x-rowOf` with the +table's record, for an action that works on one row. A table's own cell and row edits are not runs of the +session: they make no row busy, and a cell being saved shows as stale instead +([`editing.md`](editing.md#cells-of-a-models-table)). + +- A busy row draws the theme's busy mark and takes no cell edit ([`editing.md`](editing.md)). It can still be + selected, copied and scrolled past. +- The element value `busyCount` counts them, and the status line says "Saving 40 rows". +- When the action settles, its rows stop being busy, whatever its outcome. + +An action that changes some rows and not others names the others in `ChangedRows::failed`, each with its +reason ([A model's tables](#a-models-tables)). + +- A failed row draws with the `err` tone and its message as the row's tooltip, until the next action of this + session on it, until a change event that names it arrives after the action settled (a failed row's key is not + among the keys the action's own event names), or until the user chooses "Clear marks" in the status line. A + row-scoped table's events name no keys, so there the mark lasts until the next action on the row or "Clear + marks". +- The status line says "12 rows could not be saved", with "Select them", which makes them the selection. + +### The header while the application is busy + +`headerEnabled` (a condition, default `true`): while it is false, the header's sort, filter and arrangement +gestures, and the menu entries that change them, are disabled. A gesture made anyway is refused with a message +in the status line. Selecting, scrolling, copying and the application's own entries stay available. A screen +that runs a long operation over a table's rows sets it, so the rows do not reorder or leave the view under the +operation. + +## Values with units + +A column can hold amounts in different units, and of different kinds of unit: 0.3 kg in one row, 200 g in the +next, 0.3 % in a third. Such a column sorts and filters by what the values mean: 200 g is less than 0.3 kg, and +neither is comparable with 0.3 %. + +A `Quantity` column stays what it is: one dimension, every cell converted to the column's canonical unit by the +factor the cell carries. `Measure` is the kind for a column whose cells name their unit. + +### Measures and the unit registry + +```cpp +/// A unit known to a table: which dimension it measures and how it converts to that dimension's base unit. +struct UnitInfo { + std::string id; // "kg", "g", "percent"; what a cell and an operand name + std::string symbol; // "kg", "g", "%"; what is shown + std::string dimension; // "mass", "ratio" + math::Rational toBase; // exact: 1 for kg, 1/1000 for g, 1/100 for percent + std::uint32_t decimals; // places shown in this unit +}; + +using UnitId = std::uint32_t; + +/// The units of a process, immutable once built and safe to read from any thread. +class UnitRegistry { +public: + [[nodiscard]] std::optional find(std::string_view id) const; + [[nodiscard]] UnitInfo const& info(UnitId unit) const; + /// Dimensions in the order they were first registered. + [[nodiscard]] std::span dimensions() const; + /// The units of one dimension, largest base factor first. + [[nodiscard]] std::span unitsOf(std::string_view dimension) const; +}; + +/// An exact amount in a named unit. +struct Measure { + math::Rational amount; + UnitId unit = 0; +}; +``` + +- `Cell` has `Measure`, its last alternative, after `Unloaded`. It is smaller than `QuantityCell`, so a `Cell` + does not grow. +- `ColumnKind` has `Measure` (`"measure"`). `ColumnInfo::dimensions` is the dimensions the column allows, + in the order their groups sort; empty allows every dimension, in the registry's order. +- `Services::units` is a `std::shared_ptr`. A `Measure` column with no registry is a + `SourceContract` error. +- **The application fills the registry at run time**, on the server, from its own configuration or data: which + units exist is the application's knowledge, and may be a table in its database. `UnitRegistryBuilder` takes + `UnitInfo`s and builds an immutable registry; `addUnitsOf()` adds the units of one of morph's compile-time + unit enums, as a convenience for an application that has them. +- **A client learns units from the table's description** (`TableDescription::units`, the units of the + dimensions the table's columns allow), and from nowhere else: it has no registry of its own. A typed row's + schema carries none either; it marks a measure's property `x-measure` only. +- **A unit's id** is 1 to 32 bytes, holds no white space, and does not begin with a digit, a sign, a point or + a comma; the builder refuses any other, and a second unit of the same id. An operand is a number, a space and + an id ([Filters on values with units](#filters-on-values-with-units)), so an id with a space in it, or one + that begins like a number, could not be told from the amount. The ratio's unit is the one empty id. +- **A `UnitId` is stable within a lineage.** The number is a place in one registry, and cells that hold it + outlive that registry in a level cache. So a registry is changed by building its successor from it: + `UnitRegistryBuilder{previous}` keeps every unit's number, gives a new unit the next one, and leaves a + removed unit's number as a tombstone that `find` does not return and that is never given out again. A + registry and its successors share a `lineage()`. A cell holding a removed unit's number is an invalid cell. +- **Changing the units.** The application builds the successor and swaps it in; requests in flight finish on + the one they started with. Every description that lists units takes a new `revision`, so each client fetches + the description again and resets its window, which re-reads its rows and redraws them. Key columns built + with the previous registry are dropped with the snapshot they belong to, and the view cache's entries with + them. A level cache holds amounts and unit numbers, not base amounts, and remembers the lineage they are + of: under a successor its values stay, and under a registry of another lineage, built from nothing, the + cache invalidates the level when it is next read, because its numbers mean nothing there. A stored display + unit or filter operand names a unit by its string id, and one naming a removed unit is dropped when it is + applied. +- Amounts and factors are `Rational`s. A value's key is its amount times its unit's factor, with checked + arithmetic: a product that does not fit is an invalid cell, as for a quantity. No value passes through a + double. +- **A plain number is a ratio.** The registry always holds the unit `""` of the dimension `ratio` with factor 1, + and `percent` is a ratio with factor 1/100. So 0.3 % is 0.003, equals a plain 0.003, and sorts among plain + numbers. Percent means a hundredth, and treating it as a dimension of its own would make 50 % and 0.5 two + values. A count of things is not a ratio: it is given a unit of its own (`pcs`). +- On the wire a unit is always its string id, never its number. A generic page writes a measure as + `[numerator, denominator, unit id]` ([Rows on the wire](#rows-on-the-wire)). A typed row's member is a + `table::MeasureValue`, written `{"num", "den", "unit"}` as a `Rational` is with the unit's id beside it. + `RowsSource` resolves the id through the registry it is given, which for a typed table is the model's + `tableUnits` ([Typed rows are a convenience](#typed-rows-are-a-convenience)); a document's row value of that + shape is read the same way by `ValueRowsSource`. The row's schema marks the property `x-measure` and lists no + units: it is built from the row type alone, and the units are the application's run-time registry. A client + parses, converts and shows a measure with the units of the table's description, without asking. + +### Order of values with units + +A value's key is a pair: its dimension's place among the column's dimensions, and its amount in the dimension's +base unit. + +- Values of one dimension are ordered by base amount, whatever their units: 0.2 kg, 300 g, 0.5 kg. +- Dimensions form groups, in the column's declared order or the registry's. The sort direction reverses the + amounts inside each group and leaves the groups where they are: a descending sort shows 0.5 kg, 300 g, 0.2 kg, + then 0.3 %, 0.2 %. Comparing kilograms with percent means nothing, so the direction has nothing to reverse + between them, and a group that stays put is easier to find; empty cells keep their place for the same reason. +- A cell whose unit the registry does not hold, or whose dimension the column does not allow, is invalid. Valid + cells come first, then empty and invalid, then unloaded, in either direction, as in every column. An unloaded cell + has no dimension. +- Ties break by source row. Equal amounts in different units (0.3 kg and 300 g) tie. + +### Filters on values with units + +An operand names its unit: `"250 g"`, `"0.3 kg"`, `"0.5 percent"`. On the wire it is a decimal with a point, a +space and a unit id, whatever the user's locale; the client turns what was typed into that form. + +- **Comparisons** (`lt`, `le`, `gt`, `ge`, `between`) and `eq` match a cell of the operand's dimension by base + amount, and are `No` on a cell of another dimension: "more than 250 g" keeps 0.3 kg and drops 200 g and 0.3 %. + They are never `Unknown` for a loaded cell. +- **`ne`** matches every valid cell that is not equal to the operand, a cell of another dimension included: + 0.3 % is not 250 g. +- **Equality is by amount.** `eq "300 g"` matches 0.3 kg. `oneOf` is a set of such keys. +- **`between`** takes two operands of one dimension, in any of its units; of two dimensions it is `InvalidValue`. +- **An operand with no unit is a ratio.** `"0.003"` is the plain number, which equals 0.3 %. On a column that + does not allow ratios it is `InvalidValue`: the engine does not guess a unit. A menu always sends a unit, + because it makes the user choose one. +- An operand whose unit the registry lacks, or whose dimension the column does not allow, is `InvalidValue` + naming the column. +- A group of `Measure` columns filters as any group does; every form of [Column groups](#column-groups) applies. +- An unloaded cell is `Unknown`, as everywhere. + +**What a user types.** `ui::parseMeasure(text, units, locale)` reads "0.3kg", "0.3 kg", "300 g" and, in a locale +whose decimal separator is a comma, "0,3 kg": the locale's number, optional space, then a unit's symbol or id, +matched exactly and then without regard to case. Text with no unit takes the unit the menu shows as chosen. + +### The values list and the menu + +`distinctValues` on a `Measure` column groups by key, so 0.3 kg and 300 g are one value with one count, in key +order: the list comes out grouped by dimension, each group in order of amount. `DistinctValue` has `dimension` +and `unit`: the dimension's name, and the unit of the first row that had the value. The menu draws a heading per +dimension, and its conditions take a number and a unit picker offering the units of the dimensions the column +holds. + +### Display + +A cell is shown in its own unit, to that unit's decimals. A user may choose a display unit per dimension for a +column, from the header menu; the layout's stored shape holds it as `"units": {column: {dimension: unit}}`. The +shown amount is then the exact conversion, rounded half to even to the display unit's decimals for showing only; +order and filters always use the exact amount. A `Measure` column aligns to the end with digits of one width, as +an `end` column does, with the symbol after the number, so amounts in one unit line up. Changing the display +unit changes the cells' text and may widen the column once. + +## Performance + +The target is a table of 100,000 rows and 300 columns that stays fluent on the screen. Every layer has a named +benchmark, a budget, and the regression it exists to catch. Budgets marked **M** come from figures measured on +this code ([`engine.md`, "Measurements"](engine.md#measurements)); those marked **P** are provisional and are +replaced by the first recorded baseline plus its spread. + +**The fixture.** Every measurement here, at every size, runs against one pure C++ model: no database, no SQL +and no store translator is in any benchmark's path. + +- `bench::WideTableModel`, in `tests/table/wide_table_model.hpp` and `.cpp`, built as the static library + `morph_wide_table_model` and linked by the table, UI, net and Qt Quick test executables, so the server, wire, + cache, end-to-end and frontend cases all drive the same model. +- It is a registered model type that serves three tables through `BRIDGE_REGISTER_TABLE`: `wide`, the + 100,000 × 300 table; `small`, 1,000 × 30 over the same generator; and `scoped`, whose description adds and + removes columns by the caller's principal. `wide` and `small` share the rows they have in common and one level + cache. `EditWideRow` changes one cell, declares `updatesTable` on `wide` and on `small`, and returns a + `ChangedRows` for each; `ReplaceWideRows` regenerates the rows and declares `changesTable`; `EditWideRecipe` + changes a record the slow level depends on. + Together they exercise descriptions, pages, keyed replies, distinct values, effects, invalidation and + arrivals, and a model with more than one table. +- Its rows are a column store: one typed array per column, generated from `WideTableOptions{rows, columns, + seed}`, read by a `DataSource` whose snapshot hands the arrays out in runs. The same seed gives the same table + on every machine. There is no row type anywhere in it: the description is built from the options, and a reply + is the generic page written from the arrays. +- It is built in the order the design lands ([Delivery order](#delivery-order)): its rows and generator + first, as `bench::WideTableSource`, which needs nothing but a `DataSource`; registered as a model with its + three tables when the generic contract lands; its slow level with the level cache. A benchmark is recorded + from the step that lands what it measures. No baseline is taken of a thing that does not exist. +- Its slow level is a `LevelCache` whose loader waits a configured time per key (`WideTableOptions::loadDelay`) + or on a gate a test holds, so a load's duration is known and can be subtracted, held or released. + +**The data.** Rows × columns of 1,000, 10,000 and 100,000 by 30 and 300. Per 300 columns: 100 integers, 60 +decimals, 30 quantities in two units, 10 values with units over three dimensions and ten units, 70 texts with +accents and mixed case, 69 of 4 +to 60 characters and one of 200 to 2,000, 20 dates and date-times, 10 booleans; one column in twelve has 10% +empty cells. Three of the text columns form one column group and sixteen another. Twenty columns (ten decimals, +ten texts) are at the level `recipe`, loaded for 70% of the rows unless a benchmark says otherwise. + +**How figures are taken.** Release (`-O3`), the same compiler for a comparison, median and 10th to 90th +percentile over at least seven runs at 100,000 rows, the machine's load average recorded beside each table as +`engine.md` records it. The benchmark machine also hosts CI runners, so a timing is never a CI gate: the gates +are the counts (cells read, loader calls, requests sent, widgets realized, bytes), which are exact and run as +ordinary tests. Timings are run by tag, `"[.benchmark]"`, and written into this section. Each benchmark first +asserts that its feature was active (unloaded cells present, the cache hit, the page at 300 columns), so a figure +is never taken over a path the feature did not reach. + +### Benchmarks: server + +`morph_table_tests "[.benchmark]"`, beside the existing cases. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| S1 | `apply`, sort one numeric key at the `recipe` level, page of 200, 100,000 × 300, the level read through its snapshot | ≤ 48 ms (M: 33.0 ms with all cells loaded, and L1's 8 ms for the level's 100,000 reads); ≤ 1.10 × the same query with no unloaded cell | The unloaded rank slowing every comparison | +| S2 | `apply`, text `contains` on a `recipe` column | ≤ 12 ms (M: 9.25 ms); ≤ 1.15 × the two-valued filter | Three-valued evaluation costing more than a state test | +| S3 | Cells read by `apply`, per column, through a recording source | Exactly the sorted and filtered columns; zero for the other 298 (gate) | `apply` building keys, or reading unloaded state, for every column | +| S4 | `levelsNeeded`, 300 columns, 8 sort keys, 32 filtered columns | ≤ 50 µs (P) | A lookup that scans the columns per key | +| S5 | Engine repair when a level arrives for 200 and for 1,000 rows of a sorted 100,000-row view | ≤ 15 ms (P) and ≤ 35 ms (M: 27.4 ms for 1,000 updates); one repair and no full sort on `EngineStats`, and the arrived rows at the view rows the oracle gives them (gates) | An arrival recomputing the view; an arrival that changes nothing | +| S6 | Repair with 50,000 undecided rows when 1,000 are decided | ≤ 40 ms (P); one repair, no filter run over all rows, and each decided row in the view or rejected as the oracle has it (gates) | The undecided set rebuilt per arrival; a decided row left undecided | +| S7 | Ten consecutive page requests of one sorted view | One view computed, by `ViewCacheStats` (gate); requests two to ten ≤ 2 ms each (P) | A request that sorts again | +| S8 | Resident memory of the source at 100,000 × 300 | Recorded; the fixture's column store, against a `VectorSource` of the same rows, expected near 1.7 GB | A server holding a wide table as cells | +| S9 | A keyed query of 20 keys against that view: the first, which builds the view rows by source row, and the next | ≤ 3 ms and ≤ 0.5 ms (P); no view computed (gate) | A keyed fetch that sorts | + +### Benchmarks: server level cache + +`morph_table_tests "[.benchmark]"`, with a loader that sleeps a fixed time per key so that load time is known and +subtracted. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| L1 | The hit path of one request: a snapshot and 200 reads (a page), and 100,000 reads (an `order` level) | ≤ 20 µs and ≤ 8 ms (P) | A copy of the cache per request; a lock per read | +| L2 | Bytes per cached row at twenty columns, and for 100,000 rows | ≤ 1.5 kB a row, ≤ 150 MB (P; twenty cells are about 1.1 kB) | Per-value allocation overhead | +| L3 | `invalidate` of 1,000 keys, and the observer call for a 4,096-key change, which runs on the server strand; the same while a reader holds a snapshot for 40 ms | ≤ 0.5 ms and ≤ 1 ms (P), with or without the reader (gate: the call does not wait for it) | Invalidation that scans the cache, or waits for a reply being built | +| L4 | Loader calls when 8 threads want the same 200 keys | 200 keys loaded, once (gate) | No in-flight set | +| L5 | Loader calls for a second query and a second client | Zero (gate) | A miss on a held key | +| L6 | The cache's own time from loader return to announce, per batch of 64, at 100,000 held rows | ≤ 1 ms (P); shards copied ≤ keys stored (gate) | Storing under a lock held across the announce; copying the cache per batch | +| L7 | Two order uses of one level whose candidates do not fit `maxBytes` together | The first loads its candidates once; the second is refused with `Unavailable`; loader calls equal the first's candidates (gates) | Two sorts evicting each other's rows in turn | +| L8 | Ten page requests over rows whose loads failed, inside `retryAfter`; then one with `retry` | Zero loader calls, `awaiting` empty and `failed` set; then one load of the page's keys (gates) | A failed level wanted again by every request | +| L9 | Bytes counted for 1,000 values of twenty cells with texts, against the allocator's figure | Within 10% (gate) | A bound that counts `sizeof` and never evicts | + +### Benchmarks: many clients + +`tests/net`, one server and fifty clients in one process, each with a window on the fixture's `wide`. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| C1 | Fifty watchers of one sorted view while its order level loads for 100,000 rows in batches | Views computed ≤ level generations read, never one per watcher (gate); refetches per watcher ≤ 4 a second (gate); the server strand's longest task ≤ 2 ms (P) | A sort per watcher per arrival; a strand that sorts | +| C2 | The thread each request's sort runs on, and the model strand's time per request | A `tableWork` thread (gate); ≤ 50 µs on the model's strand (P) | A model that answers nothing else while its table sorts | +| C3 | Fifty watchers with fifty different sorts | Bytes held ≤ `ViewCacheOptions::maxBytes` (gate); views computed per second recorded | A cache without a bound | + +### Benchmarks: wire + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| W1 | Bytes of a generic page of 200 rows and 40 named columns in an `ok` envelope | ≤ 200 kB (P; 21 bytes a cell in a typed page gives 168 kB); no cell of a column the query did not name (gate) | A reply that carries the table's width | +| W2 | Encode of that page from the column store, and decode on the client | ≤ 2 ms and ≤ 3 ms (P) | A writer or reader whose cost grows faster than the cells | +| W3 | Bytes added by `unloadedRows` when all 200 rows have one unloaded level | ≤ 1% of W1 (P) | The sidecar repeating per cell what is true per level | +| W4 | A keyed reply of 20 rows and 40 columns: bytes, encode and decode | ≤ 20 kB, ≤ 0.5 ms (P) | A keyed reply carrying the page | +| W5 | The same 200 × 30 page as generic rows and as a typed `Page` | Generic ≤ 0.7 × typed in bytes (P) | An encoding that repeats what the header says | +| W6 | A 300-column `TableDescription`: bytes, encode, decode, and requests for it per mounted table | ≤ 60 kB, ≤ 2 ms (P); one request (gate) | A description fetched per page | +| W7 | The page of W1 with `columns` absent, all 300: bytes, encode, decode | ≤ 1.5 MB (P; 1.27 MB as a typed page) and under `kMaxEnvelopeBytes` (gate); ≤ 10 ms and ≤ 15 ms (P) | A whole page that does not fit an envelope | + +### Benchmarks: client cache and window + +`morph_table_tests` and `morph_ui_tests`, `"[.benchmark]"`, beside `bench_interpreter.cpp` and `bench_mount.cpp`. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| K1 | `PageWindow::accept` of a 200 × 300 page | ≤ 0.1 ms (P) | Rows copied instead of moved | +| K2 | `refresh` with 900 event keys against 1,600 held rows in eight runs | ≤ 0.5 ms (P); the fetch holds the 900 keys and eight probes (gate) | Matching keys by scanning the held rows per key | +| K3 | `patch` of 200 rows | ≤ 0.3 ms (P) | The same scan | +| K4 | Query cache: a 4,096-key event against an entry of 200 rows; storing a decoded 200 × 300 page | ≤ 2 ms and ≤ 30 ms (P) | A walk of the whole value per key | +| K5 | Rows whose cells are evaluated again after a page refetch that changed 20 of 200 rows | 20 (gate) | A refetch repainting the page | +| K6 | Page fetches sent, and cancelled, while the scroll thumb is dragged across 100,000 rows in two seconds and released | At most three sent, and every one not at the resting place cancelled (gate) | A fetch per page passed | +| K7 | Fetches sent by scrolling sideways by one viewport over held pages | One column fetch per page around the visible rows, naming only the columns not held (gate); bytes ≤ W1 | A sideways scroll that fetches rows it holds | +| K8 | Cells converted to document values for a realized row of 300 columns, twenty drawn | Twenty (gate) | A row record built whole | + +### The frontend at 300 columns + +Windowing rows alone is not enough at 300 columns. A table that realizes, for each realized row, a widget for +every column, in one horizontal scroll area as wide as all the columns together, holds 50 rows × 300 columns at +thirty visible rows and a margin of ten each side: 15,000 cell widgets, 300 created for each row that scrolls +in. For scale, mounting 14,001 nodes takes 19 ms on the recording backend, which creates no Qt items. With the +columns windowed too ([The renderer](#the-renderer)) the same view is about 50 × 20: 1,000 widgets. + +`morph_qt_quick_tests "[.benchmark]"`, a 1,280 × 800 window, a model-backed table of the fixture's `wide`, +100,000 × 300, at a fixed height. The step 0 baseline is a `rows` table of 2,000 × 300, which is the size a mount +with no column window holds. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| F1 | From a page reply to the first frame showing its rows | ≤ 250 ms (P) | Cell creation that scales with all columns | +| F2 | Cell and header widgets alive | ≤ realized rows × (pinned columns + columns in view + 2 × `columnOverscan`), and one header cell for each of those columns (gate) | A change that realizes more than the windows | +| F3 | Frame time scrolling vertically: at 20 rows a second, in a fling at 2,000 rows a second, and under a drag of the thumb across the table | p50 ≤ 8 ms, p99 ≤ 16.6 ms, in each | 300 widgets created per row scrolled in; realization that keeps up by missing frames | +| F4 | Frame time scrolling horizontally across all columns: at 10 columns a second, and in a fling at 100 columns a second | p50 ≤ 8 ms, p99 ≤ 16.6 ms, in each | Layout or rendering cost that follows the full width | +| F5 | Memory per realized row | ≤ 64 kB a row (P) | Widget growth | +| F6 | An arrival for the 50 realized rows, twenty cells each: frames it takes and bindings evaluated | One frame ≤ 16.6 ms (P); 1,000 cells evaluated and no other (gate) | An arrival rebuilding rows | +| F7 | Column-width work on that arrival | Each of the twenty columns grows at most once; ≤ 2 ms (P) | A rescan of every realized row per cell | +| F8 | Cells created, and cells rebound, per frame in F3's and F4's flings | Created: zero once the pools are warm; rebound: ≤ `realizePerFrame` (gates) | A scroll that allocates; a frame that realizes without bound | +| F9 | Work per frame that reads every column: extents, widths, header | Zero reads outside the column window, counted by `ColumnExtents` (gate) | Widths computed over 300 columns per frame | +| F10 | The focused cell after scrolling 10,000 rows and 200 columns away, and the row and column counts the table reports | The cell is realized and holds focus; counts are the view's total and the visible columns (gates) | Focus lost to recycling; counts of the realized rows | + +How a frame is timed: + +- **In CI**, under `QT_QPA_PLATFORM=offscreen` with the software scene graph, the test drives the scroll position + in fixed steps through `QQuickRenderControl` and times `polishItems`, `sync` and `render` for each step. The + figure is CPU time for one frame's work. It is comparable between commits on one machine and says nothing about + a GPU. The counts in F2, F6 and F7 are exact there and are the gates. +- **Locally, on a display**, with the threaded render loop and vsync, the same test records the intervals between + `QQuickWindow::frameSwapped` and reports p50 and p99 and the frames over 16.6 ms. This is the figure the 60 + frames a second target is held to, and it is recorded here with the machine and its load. + +F2 to F4 are the budgets the column window exists to meet: a table that realizes every column of its realized +rows is recorded against them first, and that record is the measure of what the window buys. + +### Benchmarks: end to end + +`tests/net`, a socket server and one client in one process, the loader held or timed. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| E1 | First page of a sorted 100,000 × 300 table whose `recipe` level is not loaded: request to accepted page | ≤ 1.10 × the same table with no level; ≤ 120 ms (P) | A reply that waits for a load | +| E2 | From the loader's return to the patched rows, for 20 rows | p50 ≤ 80 ms, p99 ≤ 150 ms (P; 50 ms of it is the coalescing window) | A second round trip, or a page where rows would do | +| E3 | Requests the client sends from first page to patched rows | One page request, then one keyed request (gate) | Polling | +| E4 | The same arrival through the query cache | One page request per marked entry (gate); time recorded against E2 | The cost of a screen that is not on a window | + +### Benchmarks: browser + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| B1 | Client-mode engine with no worker, native: a three-key sort then a text filter, request to result and worst owner step, at 10,000, 20,000 and 100,000 rows | ≤ 5 ms, ≤ 12 ms (P) and ≤ 70 ms; worst step ≤ 5 ms at 20,000 (P) and ≤ 12 ms at 100,000 (M: 3.27 ms, 57.3 ms, 9.6 to 11.6 ms) | A step that runs past the frame at the size client mode is allowed in a browser | +| B2 | The same, and S1, S2 and W2's decode, compiled to WebAssembly and run under Node | Recorded as a factor over native; expected 1.5 to 3 (estimate) | Nothing: it replaces the estimate this design's browser figures use | +| B3 | Server mode: from a sort change, and from the last key of a text filter, to the accepted page, over a socket with 50 ms added each way | ≤ 150 ms; ≤ 250 ms debounce + 150 ms (P) | A sort or filter change that costs more than one round trip | +| B4 | Requests sent while typing a ten-letter word in 1.5 s | One (gate) | A filter that is not debounced | +| B5 | The WebAssembly build in a headless browser: mount of a `rows` table of 2,000 × 300, then one screen of vertical scroll | Recorded in step 0, against F1 and F3 natively | Nothing: it is the browser's baseline, taken before anything is built for it | + +The table module builds for WebAssembly without Qt. Step 0 builds the table tests for that +target and runs them under Node, so the count gates of the single-threaded path run there as they do natively; +B2's factor is a timing and is recorded here with its date, as every timing is, and the engine's +single-threaded step size is set from it. B5 and U8 need a browser and the Qt WebAssembly build and are run +locally, under a headless browser. U8 is the exit criterion of the step that lands the column window, so the +browser is measured when the frontend's cost is decided and not after everything else is built. + +### Benchmarks: configuring + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| D1 | `distinctValues` on a text column with 50,000 distinct values in 100,000 rows, first 200, keys built | ≤ 30 ms (P; a sort of one text key with its keys is 46.3 ms; recorded runs 15.9 to 35.4 ms on a busy host) | Grouping by comparing texts instead of keys | +| D2 | The same with a three-letter search | ≤ D1 (P; not met in the recorded runs) | A search that folds every value again | +| D3 | The same with a filter on two other columns, one at an unloaded level | ≤ 1.5 × D1 (P); `partial` set (gate) | The cascade running the full filter per value | +| D4 | Compile a `oneOf` of 10,000 values; filter 100,000 rows with it | ≤ 2.2 ms; ≤ 9.1 ms (recorded 2.07 ms and 6.51 ms, spreads to 2.21 and 9.13 ms) | A membership test that scans the set per row | +| D5 | Lookups per row by that filter | One (gate, counted by the set) | The same | +| D6 | Wire bytes of a query with a 10,000-value `oneOf` of the fixture's texts, 16 bytes a value on average; of unticking one value of 50,000 | ≤ 250 kB (P) and under `maxQuerySetBytes` (gate); one value (gate) | A menu that sends the larger side | +| D7 | Adding a third key to a two-key sort of 100,000 rows | ≤ 50 ms (M: a three-key sort is 40.4 ms) | Nothing new in the engine; it bounds the gesture | +| D8 | Cell widgets created and released by hiding a column, and by moving one within the window | None created; the hidden column's cells, one per realized row, returned to their pool; every other cell still bound to its row and column (gates) | A layout change that rebuilds rows; a hide that does nothing | +| D9 | A server-mode distinct request: menu opened to list shown, over a socket | ≤ 150 ms (P) | A request per keystroke of the search (it is debounced, gate: one request per pause) | +| T1 | Parse, fit and apply a stored state for 300 columns with 8 sort keys and 32 filters, the store's own time excluded | ≤ 2 ms (P) | Fitting that scans the columns per stored id | +| T2 | Bytes of that state, and store entries and calls for it; the same for a state whose filter ticks 20,000 values | Recorded; one entry and one call for the first; the second reads back equal, through segments of at most `segmentBytes` (gates) | A store that shortens a state; one that writes every state as segments | +| T3 | Queries sent by a table mounting with a stored sort and filter | One (gate) | A first page fetched before the state is applied | +| T4 | Saves sent for 50 changes within a second | One (gate) | A save per change | +| T5 | Calls to load state when a screen of five tables mounts, and when it mounts a second time | One, then none (gates) | A round trip per table; a state fetched again by the session that holds it | + +### Benchmarks: column groups + +100,000 rows; a group of 3 and a group of 16 text columns; the group's keys built. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| G1 | `any`, a `oneOf` of 2 values: 3 columns, 16 columns | ≤ 10 ms; ≤ 45 ms (P; about one set lookup a cell) | Compiling the set once per column | +| G2 | `any`, a `oneOf` of 1,000 values: 3 columns, 16 columns | ≤ 1.2 × G1 (P) | Cost that follows the set's size | +| G3 | `atLeast 2` and `exactly 1`, the same sets | ≤ 1.2 × G1 (P) | Counting that does not stop when decided | +| G4 | `together`, 2 entries over 3 columns; 16 entries over 16 columns | ≤ 12 ms; ≤ 120 ms (P) | A search over assignments instead of a matching | +| G5 | Per row: cell lookups, and augmentations in `together` | k lookups in either mode for value entries; at most one augmentation per entry, none for a row with an unmatched entry (gate) | A lookup per entry and cell; a matching attempted on rows that cannot match | +| G6 | Pooled distinct values over 3 and 16 columns, first 200 | ≤ 3 × D1; ≤ 16 × D1 (P) | Pooling by merging per-column lists per request | +| G7 | G1 and G4 with a third of the group's cells unloaded | ≤ 1.2 × the loaded figure (P); undecided rows equal the oracle's (gate) | Three-valued counting done by a second pass | + +### Benchmarks: values with units + +100,000 rows; one column of three dimensions and ten units, against a `Quantity` column of the same amounts. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| M1 | Build keys and sort the `Measure` column | ≤ 1.2 × the `Quantity` column (P) | A registry lookup by name per cell; a dimension compared as text | +| M2 | Filter `gt "250 g"` | ≤ 1.2 × the `Quantity` column's `gt` (P) | Converting the operand per row | +| M3 | Compile 1,000 operands with units; `ui::parseMeasure` of 1,000 typed texts | ≤ 1 ms each (P) | A scan of the registry per operand | +| M4 | `distinctValues` on the column | ≤ 1.2 × D1 on a decimal column (P) | Grouping by shown text instead of key | +| M5 | Registry lookups per cell while building keys | One, by id (gate) | The same as M1 | + +### Benchmarks: every surface + +The budgets above are for the pipeline, and every surface is on it, natively and in the browser. These cases hold +each surface to them and record what each costs before it moves. + +| Id | Measures | Budget | Catches | +|---|---|---|---| +| U1 | A document `rows` table of 100,000 rows: a header click on a text column, to the sorted view | ≤ 60 ms (M: the engine sorts one text key in 46.3 ms) | A surface sorting outside the engine. The interpreter's pipeline is recorded first as the figure this replaces. | +| U2 | The same table sorted, one row's value changed | ≤ 10 ms when the list shares its unchanged rows, ≤ 40 ms when it is a fresh decode of 100,000 rows (P); one repair, no full sort, cells derived for the column in use only (gates) | A changed row sorting the list; a diff that reads every field | +| U3 | Text folds performed by a sort of 100,000 rows on one text key | 100,000: one per row (gate) | Folding inside the comparison | +| U4 | Memory of a 10,000 × 300 `rows` table as document values and as the source's cells, with one column sorted | Recorded; the source holds one column's cells (gate) | A second copy of the rows | +| U5 | A collection of 20,000 rows: mount, sort, one row edited | As U1 and U2 scaled; recorded | The collection leaving the shared path | +| U6 | A model-backed table of 100,000 × 300: F1 to F7, E1 to E3 on a real screen | Those budgets | A lowering that fetches pages where rows would do | +| U7 | Cell widgets alive in the terminal backend at 100,000 × 300 | Rows in view × columns in view (gate) | A backend that ignores the column range | +| U8 | U1 and U2 at 20,000 rows, and U6's scrolls, in the WebAssembly build in a browser | Recorded against the native figures; the frame budgets of F3 and F4 hold. The exit criterion of the column window's step | A path that works natively and not on one thread | + +**What a baseline is for.** A baseline is the figure of a path before the step that moves it onto the +pipeline, recorded once in step 0 and kept beside the budget it is held to afterwards: + +- *A `rows` table ordered outside the engine* (U1 to U4): a comparison that folds both texts each time it is + called folds about 3.4 million strings to sort 100,000 rows, where the engine folds 100,000 once. +- *A reply of every column* (W7 against W1 and W4): a page of 200 × 300 for an arrival of twenty rows. +- *A sort per request* (S7): ten page requests of one view as ten sorts, against one. +- *Every column realized* (F2): 15,000 cell widgets for 50 realized rows. +- *A table held as cells* (U5, S8): about 56 bytes each. + +### Recorded baselines + +Step 0's figures, taken before anything they measure moves onto the pipeline. Timings are the median and the 10th +to 90th percentile; a count or a size is exact. *Machine A* is a Windows Server 2025 host, AMD EPYC 7763 (128 +logical processors), 256 GB, MSVC 19.51.36257 Release (`cl-release`, `cl-qt-release`); it is shared with CI builds, and +its processor time was 82 to 91% busy while these ran (five one-second samples before the run), which is what the +spread reflects. A row marked *not yet measured* says why; its figure is taken where the environment exists. + +| Id | Step | Figure | Machine, load | Date | +|---|---|---|---|---| +| S1 | 0 | `apply`, sort `d000` asc, page of 200, 100,000 × 300: 91.9 ms (84.9–109.5) | A, 82–91% busy | 2026-11-17 | +| S2 | 0 | `apply`, filter `t001` contains `"ka"`, 100,000 × 300: 175.3 ms (158.3–182.7) | A, 82–91% busy | 2026-11-17 | +| S7 | 0 | Ten consecutive `apply` calls of S1, offsets 0 to 1,800: 937.7 ms (894.3–946.6) in all, 94.6 ms (80.0–107.5) a call — ten sorts | A, 82–91% busy | 2026-11-17 | +| S8 | 0 | The column store at 100,000 × 300: 757,023,934 bytes (722.0 MiB); the same rows as a `VectorSource`'s cells, by `approximateCellBytes`: 2,143,111,296 bytes (2,043.8 MiB) | A | 2026-11-17 | +| B1 | 0 | Client mode, an owner and no worker, 30 columns, three-key sort then a text filter, request to result: 21.0 ms (19.8–24.0) at 10,000 rows, 42.7 ms (37.0–44.8) at 20,000, 242.5 ms (215.3–245.0) at 100,000 | A, 82–91% busy | 2026-11-17 | +| B1 | 0 | The same, the longest owner step: 10.0 ms (8.1–10.5) at 10,000, 10.2 ms (8.9–10.5) at 20,000, 11.6 ms (10.6–14.2) at 100,000 | A, 82–91% busy | 2026-11-17 | +| B2 | 0 | S1, S2 and B1 under Node from the `table-wasm` build, as a factor over native: *not yet measured* — no Emscripten or Node on machine A; the CI job builds and runs the table tests there, and the factor is taken by running `node build-wasm/tests/morph_table_tests.js "[.benchmark][baseline]"` beside a native run on one machine | — | — | +| B2 | 1 | W2's decode under Node: *not yet measured* — no Emscripten or Node on machine A; the figure is taken by running `node build-wasm/tests/morph_table_tests.js "[.benchmark][wire]"` beside a native run on one machine | — | — | +| B5 | 0 | Qt for WebAssembly in a headless browser, mount of the 2,000 × 300 `rows` table and one screen of scroll: *not yet measured* — no Qt for WebAssembly kit, Emscripten or browser runner on machine A; the harness is `tests/qt_quick/wasm/wide_rows_baseline.cpp`, built and run as its header says | — | — | +| W7 | 0 | A page of 200 × 300 as typed row objects (a decimal as its `{"num","den","dp"}` object, a quantity as its amount): 2,162,606 bytes; encode 14.7 ms (14.4–15.7) | A, 82–91% busy | 2026-11-17 | +| W1 | 1 | A generic page of 200 rows and the 40 columns at positions 100 to 139, in an `ok` envelope: 116,207 bytes, of which 52 are the empty partial-page members (`unloadedRows`, `undecided`, `awaiting`); no other column's cell | A, 43–71% busy | 2026-11-18 | +| W2 | 1 | That page: `writeGenericPage` and its JSON from the column store 1.48 ms (1.45–1.62); `readGenericPage` 2.33 ms (2.21–3.01) | A, 12–23% busy | 2026-11-18 | +| W1 | 1 | The same page as the `Table.wide` reply through `LocalBackend` (a `TableQuery` naming those 40 columns, page of 200), in an `ok` envelope: 116,223 bytes, 16 more than W1's for the description's revision; the round trip 1.79 ms (1.41–2.15) | A, 80–88% busy | 2026-11-18 | +| W2 | 1 | That reply's server side: the table function, the pinned snapshot, `answerQuery` and the page's JSON, 2.25 ms (1.65–2.44) | A, 80–88% busy | 2026-11-18 | +| S1 | 2a | `apply`, sort `d000` asc, page of 200, 100,000 × 300 through `bench::withUnloaded` with the `recipe` level loaded for 70% of the rows: 104.6 ms (90.8–111.4); the same source with every row loaded: 111.7 ms (103.7–117.4). Above the 48 ms budget, as step 0's S1 already was on this host (91.9 ms); within the 1.10 factor, at 0.94, a factor inside the overlapping spreads, so noise and not a speed-up | A, 34–76% busy | 2026-11-18 | +| S2 | 2a | `apply`, filter `t001` contains `"ka"`, the same sources: 147.3 ms (120.5–167.5) at 70% loaded, 219.9 ms (194.8–226.1) with every row loaded. Above the 12 ms budget, as step 0's S2 already was on this host (175.3 ms); within the 1.15 factor, at 0.67. Inferred, not measured: the unloaded rows are faster because an unloaded cell is decided by its state and its text is not searched | A, 34–76% busy | 2026-11-18 | +| S4 | 2a | `levelsNeeded`, 300 columns, 8 sort keys, 32 filtered columns, the filter compiled to find the columns `apply` reads: 35.8 µs (33.8–45.0) a call, within the 50 µs budget | A, 57–76% busy | 2026-11-18 | +| S5 | 2a | An `Engine` sorted on `d000` over the 100,000 × 300 table at 70% loaded: 200 rows arrive by one `load`, 18.3 ms (16.6–22.9); the next 1,000, 21.5 ms (17.9–23.9); one repair and no full sort each. The 200-row arrival is above its 15 ms budget (P); the 1,000-row one is within 35 ms. Inferred, not measured: the cost is mostly the merge into the sorted 100,000-row view, since five times the rows cost 3 ms more | A, 34–76% busy | 2026-11-18 | +| S6 | 2a | An `Engine` filtered `d000 gt 0` at 50% loaded (about 50,000 undecided rows), 1,000 of them decided by one `load`: 4.18 ms (3.91–4.28); one repair, no filter run | A, 34–76% busy | 2026-11-18 | +| W5 | 1 | 200 × 30: generic page 405,396 bytes, encode 3.00 ms (2.91–4.00); typed `Page` with an absent member for an empty cell 479,205 bytes, encode 1.87 ms (1.80–1.91); generic / typed 0.85, above the 0.7 budget | A, 12–23% busy | 2026-11-18 | +| W6 | 1 | The 300-column description: 42,494 bytes; encode with `describe` 0.23 ms (0.23–0.24); decode 0.14 ms (0.14–0.15) | A, 12–23% busy | 2026-11-18 | +| W6 | 9a | The 300-column description with every column's default `display`, `tone` and `tooltip` left out: 51,727 bytes (91,927 while every column wrote them), under the 60 kB budget. Above step 1's 42,494 by the members added since (each column's `comparator`, `format` and `level`, about 30 bytes a column; inferred, not measured member by member). Measured on a `cl-debug` build, so its timings are not comparable with the Release rows: encode 5.58 ms (5.46–6.47), decode 7.21 ms (7.00–10.32); the byte count does not depend on the build | A, load not sampled, `cl-debug` | 2026-11-20 | +| W7 | 1 | A generic page of 200 × 300 in an `ok` envelope: 1,443,726 bytes, under `kMaxEnvelopeBytes`; encode 17.0 ms (16.5–19.0) and decode 18.7 ms (17.8–21.6), above the 10 ms and 15 ms budgets | A, 12–23% busy | 2026-11-18 | +| W3 | 2b | W1's page (200 rows, the 40 columns at positions 100 to 139, which hold the recipe decimals) with no row's recipe level loaded, in an `ok` envelope: 105,592 bytes; the same page with `unloadedRows` cleared 97,703 bytes; the 200 entries 7,889 bytes, 39 a row, 6.8% of W1 (116,207 bytes), above the 1% budget. One entry a row is the spec's shape, and 1% of W1 is 5.8 bytes a row | A, 43–71% busy | 2026-11-18 | +| W4 | 2b | A keyed reply of 20 keys spread over the view and W1's 40 columns: 12,265 bytes in an `ok` envelope; encode from the column store 0.132 ms (0.127–0.152); `readGenericPage` 0.273 ms (0.258–0.399) | A, 37–64% busy | 2026-11-18 | +| L1 | 2c | A level snapshot and 200 reads of twenty-cell values at 100,000 held rows: 0.066 ms (0.066–0.067), above the 20 µs budget; 100,000 reads 59.8 ms (57.1–77.6), above the 8 ms budget. Inferred from the code, not measured apart: each read copies the value's twenty cells, ten of them strings, into the caller's buffer, which `LevelSnapshot::read(key, span)` requires | A, Release | 2026-11-19 | +| L2 | 2c | Bytes the cache counts for 100,000 values of ten decimals and ten texts of 4 to 60 characters: 151,449,600, 1,514 a row, 0.9% over the 1.5 kB budget (the cells by `cellBytes` and the vector; the shard entries are not counted); the process's private bytes grew 196,718,592 over the store, which includes the 100,000 values built to be stored | A, Release | 2026-11-19 | +| L3 | 2c | Shards of about 64 rows (2,048 at 100,000 rows); every change prepared with no lock held and published under the writer mutex, and a `want` holding that mutex for 1,024 keys at a time: `invalidate` of 1,000 keys 4.11 ms (3.39–6.98), the observer call for a 4,096-key change 15.0 ms (11.7–19.8); with a reader holding a snapshot for 40 ms, 2.55 ms (1.90–3.72) and 13.1 ms (12.1–19.8) (gate `"level cache: invalidation does not wait for a reader"`; gate `"level cache: an invalidation waits for one chunk of a large want at most"`). Measured with the host nearly idle (one compiler process running): L1, whose code this measurement did not change, read 0.064 ms (0.064–0.082) against its recorded 0.066 ms. **Both miss the 0.5 ms and 1 ms budgets**; the budget is an owner's question. Cause, inferred from the code and not measured apart: random keys spread over the shards, so 1,000 keys touch about 800 of the 2,048 shards and the call copies about 40% of the entries and frees the shards they replace; the 4,096-key call touches nearly every shard | A, Release | 2026-11-19 | +| L6 | 2c | Loader return to announce for a batch of 64 at 100,000 held rows: 0.385 ms (0.374–0.480), within the 1 ms budget; 960 shards copied for 960 keys stored over fifteen batches (gate: at most one shard a key, `"level cache: a batch copies only the shards it touches"`). Measured with the host nearly idle (one compiler process running): L1, whose code this measurement did not change, read 0.064 ms (0.064–0.082) against its recorded 0.066 ms | A, Release | 2026-11-19 | +| S7 | 2c | Ten `answerQuery` calls through one `ViewCache` over the 100,000 × 300 column store, sorted on `i001`, pages 0 to 9 of 200: the first 75.1 ms (it sorts), requests two to ten 1.48 ms (1.43–1.49) each, within the 2 ms budget; one view computed for the ten (gate) | A, Release | 2026-11-19 | +| S9 | 2c | A keyed query of 20 keys against that view: the first 22.0 ms (it builds the view rows by source row and the key index, 100,000 rows each), above the 3 ms budget; the next 1.22 ms, above the 0.5 ms budget; no view computed (gate) | A, Release | 2026-11-19 | +| C1 | 2c | In process, not over a socket (`"table benchmark: C1 C2 C3 many requests through an in-process server"`): fifty `Table.wide` requests on fifty instances, sorted on the `recipe` column `d000` at 100,000 rows, sent together after an arrival on the level: **399–583 ms** over six runs (558.9, 432.1, 399.1, 461.1, 582.8, 512.2) from the first send to the last reply, on a loaded host (3 to 63 compiler processes during the runs; L1, whose code did not change, read 0.101 and 0.106 ms against its recorded 0.066 ms); one view computed, 7 requests waited for it, the other 42 found it computed; the new view's order set was fitted once and protected its 100,000 keys in one pass, releasing the superseded set of the view before the arrival after the repeats waiting for the new set were woken, and the other 49 requests were repeats of the set, each one more holder and a longer lease under the lock. Without that release, and without counting the sets' keys in the bound, the same benchmark measured 339–401 ms on a nearly idle host; how much of the difference is the host is not measured apart. Measured apart (`"table benchmark: C1 where a request's time goes"`): the table function, its description and the pinned snapshot 0.184 ms; a whole `answerQuery` from the cached view 0.934 ms (0.897–0.974) sorted on the `recipe` column and 0.853 ms on a base column; an order `want` of 100,000 held keys as a plain list, which leases each key, 23.9 ms (22.8–29.0); the one sort after the arrival is S7's first request, 75 ms. The bound holds ten base-column views and one view sorted by a level with its 100,000 order keys (8,000,024 bytes); at a bound of ten 400 kB views the level-sorted view, about 4.4 MB with its keys, does not fit and is computed again by later requests (3,338.7 ms, 7 views computed). The server strand's longest task is not measured: it needs the socket benchmark (`[.benchmark][net]`, POSIX only, not run) | A, Release | 2026-11-19 | +| C2 | 2c | In process: twenty distinct sorts of `wide` one after another, 21.2 views computed a second | A, Release | 2026-11-19 | +| C3 | 2c | In process: fifty sorts against the C1 bound, ten 100,000-row base-column views and one level-sorted view's 100,000 order keys (8,000,024 bytes), which holds about twenty base-column views once the level-sorted one is evicted: 8,000,000 bytes held, 31 evictions (gate: held within the bound). The evictions are fewer than at a bound of ten views because the bound is wider, not because a view holds less | A, Release | 2026-11-19 | +| K1 | 2d | `PageWindow::accept` of a whole 200 × 300 page of integer cells, into a fresh window built with `maxColumns` 300 (at the default of 96 a page holds no 300 columns): 3.05 ms (2.81–3.69), **above the 0.1 ms budget (P)**. Inferred from the code, not measured apart: the page is stored by column, so each of the 60,000 cells is moved into its column's vector, and the reply's 200 row vectors are freed; the cells are moved, never copied | A, Release | 2026-11-19 | +| K2 | 2d | `refresh` of 900 event keys against 1,600 held rows in eight runs (pages 0, 2, …, 14 of 200): 0.102 ms (0.090–0.194), within the 0.5 ms budget; the fetch holds the 900 keys and eight probes (gate `"window: a refresh of 900 keys over eight runs asks 908"`) | A, Release | 2026-11-19 | +| T2 | 9 | Through the `morph.tableState` model over an in-process server, as the `state` part and alike as the `views` part: a state of 300 columns, 8 sort keys and 32 filters is 7,700 bytes, one store `set` and one entry (gate); a state whose filter ticks 20,000 values is 1,380,070 bytes, 123 segments of at most 12 KiB with a quote and a two-byte character in every value, 125 `set` calls (the intent, the segments, the head) and 124 entries after the save, and reads back byte-equal (gate `"table state: a full state is one entry and one call; …"`) | A, Debug | 2026-11-19 | +| K3 | 2d | `patch` of 200 rows and the seven other runs' probes, one column: 0.325 ms (0.306–0.374), just above the 0.3 ms budget (P). It builds an index of the 1,600 held keys for each patch | A, Release | 2026-11-19 | +| K4 | 2d | Debug build only (`cl-debug`), so not comparable with the budgets: a 4,096-key event against an entry of 200 rows, 86.4 ms (74.6–101.4); storing a decoded 200 × 300 page of fractional numbers in an opaque entry, 708.1 ms (623.3–759.6). The Release figure is *not yet measured*: a Release build of `morph_tests` did not fit the session; the case is `"interpreter bench: K4 the query cache under an event and a wide page"` | A, Debug | 2026-11-19 | +| E1, E2 | 2d | *Not yet measured* — the case `"table benchmark: E1 E2 a window over the bridge"` is a socket benchmark (`[.benchmark][net]`, POSIX only); machine A builds no `morph_net_tests` | — | — | +| D1 | 3 | `distinctValues` through an `Engine` holding the column's keys, a text column of 50,000 distinct values in 100,000 rows, first 200: 35.4 ms (26.8–43.9); an earlier run of the code before its unused reserve was removed, at 40–54% busy, 15.9 ms (15.5–22.1) | A, 51–77% busy | 2026-11-18 | +| D2 | 3 | The same with the search `"abc"`: 41.4 ms (27.5–42.5), above D1 as in the earlier run (30.9 ms against 15.9) | A, 51–77% busy | 2026-11-18 | +| D3 | 3 | The same with `o1 ge 20` and `o2 lt 80`, `o2` unloaded in 30% of the rows, `partial` set: 25.3 ms (24.4–26.6) | A, 51–77% busy | 2026-11-18 | +| D4 | 3 | A `oneOf` of 10,000 texts: compiled in 2.07 ms (2.01–2.21); 100,000 rows filtered with it, keys built, in 6.51 ms (6.22–9.13) | A, 40–54% busy | 2026-11-18 | +| G1 | 3 | An `any` group with a `oneOf` of 2 values, 100,000 rows: 3 columns 12.2 ms (11.5–13.8), **over** the 10 ms budget (earlier runs 18.3 and 23.3 ms); 16 columns 53.3 ms (49.1–68.1), **over** the 45 ms budget. Each figure is an `Engine::setFilter` with the group's keys held, so it includes the view's rebuild and change, not the group filter alone | A, 20–46% busy | 2026-11-19 | +| G2 | 3 | The same with a `oneOf` of 1,000 values: 19.8 ms (16.5–21.3), **over** 1.2 × G1 (14.7 ms) in this run; 66.5 ms (54.5–82.4), **over** 1.2 × G1 (64.0 ms) in this run. The previous run had 15.3 ms against G1's 18.3, and 82.0 ms against 70.6, both within; the run before that, 113.2 ms at 16 columns, over | A, 20–46% busy | 2026-11-19 | +| G3 | 3 | `atLeast 2`: 11.9 ms (9.8–15.1); 68.7 ms (63.8–74.7), **over** 1.2 × G1. `exactly 1`: 12.8 ms (12.0–15.8); 70.1 ms (68.8–81.6), **over** 1.2 × G1 | A, 20–46% busy | 2026-11-19 | +| G4 | 3 | `together`, 2 entries over 3 columns: 11.9 ms (10.6–13.9), within the 12 ms budget in this run (17.4 ms, over, in the previous one); 16 entries over 16 columns: 74.5 ms (67.0–95.3) | A, 20–46% busy | 2026-11-19 | +| G6 | 3 | Pooled distinct values through the engine, first 200 of 32: 3 columns 7.8 ms (7.7–8.0); 16 columns 51.7 ms (46.9–64.3) | A, 20–46% busy | 2026-11-19 | +| G7 | 3 | G1 and G4 with a third of the cells unloaded: G1 15.9 ms (15.6–17.1), **over** 1.2 × the loaded 12.2 ms, and 58.3 ms (45.5–61.4), within; G4 14.5 ms (13.3–14.8), **over** 1.2 × the loaded 11.9 ms by a hair, and 76.2 ms (72.5–97.7), within 1.2 × 74.5 ms. The 16-column `together` figure rests on a count of the columns that can match any entry, taken before the wildcard matching: with the unknown columns' masks full, the covered test passes on nearly every row, and a row with fewer such columns than entries is refused without running a failing augmenting-path search for each entry | A, 20–46% busy | 2026-11-19 | +| M1 | 3 | `apply` sorting 100,000 rows, keys built in the call: the `Measure` column over the fixture's registry (three dimensions, ten units) 80.5 ms (75.5–114.4) and 78.2 ms (73.0–83.2) in two runs, against the `Quantity` column of the same amounts with their units' factors 90.9 ms (86.2–102.3) and 72.6 ms (71.8–83.4): 0.89 and 1.08 times, within the 1.2 budget | A, 5–55% busy | 2026-11-19 | +| M2 | 3 | `apply` filtering `gt "250 g"`: 30.9 ms (19.3–31.6) and 23.6 ms (19.3–24.1), against the quantity's `gt "0.25"` 22.4 ms (19.3–24.7) and 23.8 ms (23.7–23.9): 1.38 times, **over** the 1.2 budget, in the first run, and 0.99 in the second; the 10th percentiles of the first run are equal, so its median is inferred to be the host's noise, not measured apart | A, 5–55% busy | 2026-11-19 | +| M3 | 3 | Compiling a `oneOf` of 1,000 operands with units in nine units: 0.57 ms (0.56–0.59) and 0.50 ms (0.49–0.52); `ui::parseMeasure` of 1,000 texts typed in German: 0.29 ms (0.22–0.31) and 0.29 ms (0.27–0.39); both within 1 ms | A, 5–55% busy | 2026-11-19 | +| M4 | 3 | `distinctValues` of the `Measure` column, first 200, keys built in the call: 49.4 ms (46.4–51.9) and 46.5 ms (45.9–57.0), against a `Decimal` column of the same amounts 30.3 ms (28.8–33.8) and 37.6 ms (34.6–45.6): 1.63 and 1.24 times, **over** the 1.2 budget in both runs. Inferred from the code, not measured apart: a measure's key is read with a checked product by its unit's factor and grouped by a place and an amount, where a decimal's is copied and grouped by the amount alone, and the units make more distinct values of the same amounts. Measured as D1 is, through an `Engine` holding the column's keys, in a third run on a busier host (M1's two columns at 109.0 and 121.7 ms): 67.7 ms (64.4–73.9) against the `Decimal` column's 56.1 ms (54.0–66.3), 1.21 times, at the budget; the same run's in-call figures were 97.9 against 68.5 ms | A, 5–55% busy; third run busier, not sampled | 2026-11-19 | +| U1 | 0 | A document `rows` table of 100,000 rows on the recording backend, a bound sort set on a text column, click to settled: 2,921.5 ms (2,860.0–3,017.6). The rows realized after the sort are the ones realized before it, reordered, not the view's first rows: the figure is the interpreter's sort and reconcile, not a correct window | A, 82–91% busy | 2026-11-17 | +| U2 | 0 | The same table sorted, one row's name replaced in `items`, click to settled: 2,941.3 ms (2,881.4–2,992.2) | A, 82–91% busy | 2026-11-17 | +| U3 | 0 | Text folds of the interpreter's sort of 100,000 rows: *not yet measured* — the interpreter folds with a `CodePointCollator` it constructs inside the comparison and takes none from outside, so no counting collator can be installed; the count needs that seam | — | — | +| U4 | 0 | A `rows` table of 10,000 × 300 sorted on one column: the rows as cells, by `approximateCellBytes`, 214,423,008 bytes (204.5 MiB, 71.5 bytes a cell); the state's `items` as document values, counted the same way (each value, a string's heap, a list's or a record's container, a map node's links; shared lists and records once), 432,663,112 bytes (412.6 MiB, 144.2 bytes a cell) | A | 2026-11-18 | +| U5 | 0 | A collection of 20,000 rows over a `ListRows` reply: mount 117.0 ms (102.8–143.5); sort on a text column through the engine 46.9 ms (37.6–62.1); one row edited, the list reloaded and the sorted view repaired, 206.4 ms (171.9–226.2) | A, 82–91% busy | 2026-11-17 | +| U8 | 5 | U1 and U2 at 20,000 rows, and U6's scrolls (F3 and F4), in the WebAssembly build in a browser: *not yet measured* — the harness, `tests/qt_quick/wasm/u8_scrolls.cpp`, is written and unbuilt: no Emscripten, Qt for WebAssembly kit or Chrome on machine A, and Qt Quick cannot be configured there. The window-shaped part of the exit criterion (every scroll's p50 ≤ 8 ms and p99 ≤ 16.6 ms) is open until it is built and run as its header says | — | — | +| U1 | 6 | A document `rows` table of 100,000 rows on the recording backend, a bound sort set on a text column, click to settled, through `ValueRowsSource` and the engine (owner, no worker, 4 ms steps): 494.5 ms (472.2–528.7), **over** the 60 ms budget. Measured apart on an engine of its own (8 ms steps, the default collator): the source deriving the column's 100,000 cells 91.4 ms (88.1–100.7), the engine absorbing them 40.1 ms (36.9–51.8), the sort to settled 257.0 ms (247.6–284.7). The rest of the screen figure, about 100 ms, is the lowering's, inferred by subtraction and not measured apart | A, 35% busy (128 logical processors) | 2026-11-19 | +| U2 | 6 | The same table sorted, one row's name replaced in `items` (its other rows shared), click to settled: 356.5 ms (341.9–378.5), **over** the 10 ms budget. Measured apart on an engine of its own: the source matching the new list 101.1 ms (99.0–127.5), the engine absorbing and repairing it 116.0 ms (115.5–130.6); counts hold (one repair, no full sort, one column's cells derived: the gate cases). The rest, about 140 ms, is inferred by subtraction to be the lowering's per-change passes over every row: the view's records read again for `TableView`, the page's entries rebuilt, every field of every row read for a unit the screen does not list, and above the virtualization threshold every key given to the backend; the mount itself receives the engine's own operations for the one row | A, 35% busy (128 logical processors) | 2026-11-19 | +| U3 | 6 | Text folds of a sort of 100,000 rows on one text key: 100,000, one per row (the gate case "a sort of 100,000 rows folds each text once") | — | 2026-11-19 | +| U4 | 6 | A `rows` table of 10,000 × 300 through `ValueRowsSource`, sorted on one column: the source holds 10,000 cells, 1,033,840 bytes (0.99 MiB), against 214,423,008 bytes (204.5 MiB) for every column as cells | A | 2026-11-19 | +| B1 | 6 | A `rows` table's engine (owner, no worker, 4 ms steps, `ValueRowsCollator`), three-key sort then a text filter, request to result: 19.6 ms (17.1–21.3) at 10,000 rows, 39.3 ms (34.9–44.8) at 20,000, 216.4 ms (202.9–251.0) at 100,000. The longest owner step: 6.1 ms (5.3–6.6) at 10,000, 6.3 ms (6.1–6.8) at 20,000, **over** the 5 ms bound, and 23.4 ms (21.0–26.1) at 100,000, **over** 12 ms | A, 35% busy (128 logical processors) | 2026-11-19 | +| F2–F5 | 0 | A `rows` table of 2,000 × 300 in a 1,280 × 800 offscreen window: widgets alive, frame times of the vertical and horizontal scrolls, memory per realized row: *not yet measured* — on machine A the interpreter's mount of that table on the Qt Quick backend did not finish within its 300 s budget (the document's text 0.4 s, its parse 0.8 s); the case, `"qt quick baseline: F2 to F5 on a rows table of 2,000 x 300"`, bounds every step and names the one that overruns | A, 80–90% busy | 2026-11-18 | +| W6 | 9a | The 300-column description of the W6 case, Release (`cl-release`): 51,727 bytes, as the `cl-debug` row has it, under the 60 kB budget; encode with `describe` 0.385 ms (0.371–0.406), decode 0.280 ms (0.275–0.292), both within the 2 ms budget | A, 30–60% busy, `cl-release` | 2026-11-21 | +| T1 | 4 | Parse, fit and apply a stored state of 300 columns with 8 sort keys and 32 filters, no store (`"table state benchmark: parse, fit and apply 300 columns, 8 keys, 32 filters"`): 0.47 ms (0.45–0.67), within the 2 ms budget | A, 30–60% busy, `cl-release` | 2026-11-21 | +| D6 | 3 | A query with a 10,000-value `oneOf` of 16-byte texts: at most 250,000 bytes and under `maxQuerySetBytes`, and valid (the gate case `"table query: a 10,000-value set fits the wire bound"`, passing on `cl-release`). The case asserts the bound and does not print the byte count, so the exact figure is not recorded | A, `cl-release` | 2026-11-21 | +| K4 | 2d | Release (`cl-release`), the case `"interpreter bench: K4 the query cache under an event and a wide page"`; the median and the lowest to highest of the runs, which is what the case prints: a 4,096-key event against an entry of 200 rows, 3.50 ms (2.47–5.43) over fifteen runs, **above the 2 ms budget (P)**; storing a decoded 200 × 300 page of fractional numbers in an opaque entry, 23.3 ms (22.0–31.2) over seven runs, within the 30 ms budget | A, 27–55% busy, `cl-release` | 2026-11-21 | +| D7 | 7 | A document `table` of 100,000 rows on the recording backend, sorted on two keys from the header; a Shift-click adding the third key, click to settled (`"interpreter bench: a third sort key on 100,000 rows"`): 233.4 ms (222.5–262.3), **above the 50 ms budget (M)** by 4.7 times | A, 20–59% busy, `cl-release` | 2026-11-21 | +| U5 | 8 | A `collection` node of 20,000 rows on the table engine, on the recording backend (`"interpreter bench: a collection of 20,000 rows: mount, sort, one row edited"`): mount, the list's reply to settled, 190.0 ms (179.0–216.9); a header sort on Name, click to settled, 40.6 ms (36.2–53.4); one row edited, the reloaded list's reply to settled, 284.8 ms (240.3–305.6). Against U1 and U2 scaled by rows to 20,000 (U1's 60 ms to 12 ms; U2's 40 ms for a fresh decode, which a reloaded list is, to 8 ms): **the sort is above its scaled budget by 3.4 times and the edit by 36 times**; the mount has no budget of its own. Step 0's figures for the same three, through the engine and not on a screen, were 117.0, 46.9 and 206.4 ms | A, 15–44% busy, `cl-release` | 2026-11-21 | + +## Invariants + +1. **Soundness of the filter.** For every way of replacing the unloaded cells of a table with loaded cells, a + row `apply` puts in the view is in the view of the completed table, and a row it rejects is rejected there. +2. **Soundness of the order.** Two rows with no unloaded cell in any sort column have the same relative order + before and after any completion. +3. **Counts.** view rows + undecided rows + rejected rows = source rows, a retained row counting in the view and + not as rejected. `totalKind` is `AtLeast` whenever `undecided > 0`. +4. **Unloaded is not empty.** `isEmpty` and `notEmpty` are `Unknown` on an unloaded cell; `displayText(Unloaded{})` + is the empty string and is never used as a key. A cell whose load failed is unloaded. +5. **No unloaded cell at the base level.** One is refused as `SourceContract`. +6. **Nothing unneeded is read or sent.** `apply` reads cells only of sorted and filtered columns; a reply holds + cells only of the columns its query names; `levelsNeeded` names no level outside the query's sorted, filtered + and named columns. +7. **Absent means loaded and whole.** A source that never produces `Unloaded`, columns with no `level`, a query + without `columns`, `keys` and `retain`, and a `Page` without `unloadedRows`, `undecided`, `awaiting`, `failed` + and `unmatched` are a + fully loaded table of every column: no cell is unloaded, no row is undecided, and every result is the one + [`engine.md`](engine.md) specifies. +8. **A window's totals come from page replies only**, and a window never shows a row at a view row the server did + not report for it in the reply that supplied it. +9. **No event is lost to ordering.** For any interleaving of a page reply and an event for one of its rows, the + window ends holding the row as the server had it after the change. +10. **No polling.** Nothing is requested because time passed. Time only delays or merges a request that an + event or a gesture caused: the server's coalescing window, the window's settle and awaited-refetch delays, + a filter's debounce, a state save's debounce. Leases and retry delays are read from a clock when a request + arrives and schedule nothing. +11. **Loaded once.** Between two invalidations of a row's level, the loader is called for that row and level at + most once, however many queries, pages, sessions and clients need it, unless the value was evicted or its + load failed. +12. **Nothing stale lands.** A value whose load began before an invalidation of its row is never stored. +13. **Visible before told.** A change event for a row is sent only after a read of the cache would return the + row's new state, whether that state is a value, a failure or its absence. +14. **No value crosses a scope.** A reply holds a row only from the source the model returned for that caller, + and a cell only in a column `mayRead` allows. A cached value is laid out against the cache's own column list, + never a caller's description, and a cached view is shared only between callers of one `scope`. +15. **A table is its description.** Nothing a client or the framework needs to show, sort, filter or page a + table comes from a C++ type: a model that can build a `TableDescription` and a `DataSource` has a table. +16. **One order.** Every table on a screen orders and filters through `morph::table`: the same keys, the same + collation rules, the same place for empty, invalid and unloaded cells. +17. **A document keeps its rows.** A document that names none of this design's vocabulary shows the same rows in + the same order on the pipeline, except where [The document `table` node](#the-document-table-node-on-the-engine) + says otherwise. +18. **One mode per table**, decided by its declaration, for its lifetime. +19. **Nothing realized out of view.** The cells and header cells alive are bounded by the rows and columns in or + near view, the pinned columns and the focused cell's row and column, whatever the table's size. +20. **A changed row is a repair** on every surface that holds its rows. +21. **Arranging is not ordering.** A change of layout never changes the view's rows or their order, never runs a + sort or a filter on the server, and fetches only the cells of columns the window does not hold for the + rows around the view. +22. **A value list is what the other filters leave.** A column's distinct values and counts are those of the rows + passing every other column's filter, and the sum of the counts, `blanks` and `invalid` is that row count + when `partial` is false. +23. **A set filter is its conditions.** `oneOf` with values v1…vn matches exactly the rows `eq v1` or … or `eq vn` + match. +24. **A group filter is its definition.** For every row with no unloaded cell, a `Columns` filter passes exactly + when the count of satisfying columns meets `match`, and a `Together` filter exactly when an assignment of + entries to distinct columns exists; `{columns, combine, include}` alone is the `any` case. +25. **Units do not change an amount.** Two `Measure` cells of one dimension order and compare as their amounts in + the base unit do, exactly; two of different dimensions are never equal and never ordered by amount. A unit's + numeric id means the same unit in every registry of one lineage. +26. **A stored arrangement never breaks a table.** Whatever a store holds, the table shows at least one + column and applies only keys and filters on columns it has. +27. **State before rows.** A table with a store shows its first rows only after its stored state is applied or + its load has timed out or failed; a table whose load completes in time sends exactly one first query. +28. **One store.** Every table's arrangement is read and written through the injected `ITableStateStore` and + nowhere else, no key it is given names a person, and no layer shortens what it is given. +29. **A cached view is the view.** A reply built from a view cache entry equals the reply `apply` would build + from the same source snapshot and level snapshots. +30. **A shift is seen.** After a keyed reply is patched, either every held row is at the view row the server + has it at and the window's totals are the server's, or the window is invalidated. +31. **A refusal is shown.** Every refusal of a user's gesture (a sort key past the bound, a set too large, a + range or a copy too long, a save refused, a select-all while rows are undecided, a gesture on a disabled + header) appears in the status line or, where a document hides it, in the session's notifications. +32. **Text never orders.** A column's display (places, rounding, labels, empty text) changes what a cell shows + and nothing a sort, a filter, a distinct value or a selection uses. +33. **A selection of the view is the view.** Under `Exact`, `resolve` returns exactly the rows of the view the + user selected, less `except`, or refuses; under either policy it returns no row outside the caller's scope. +34. **A revision that holds means rows that held.** Two page replies with the same `viewRevision` describe views + of the same rows. +35. **Retaining adds, never removes.** A view with `retain` holds every row it holds without it, and the retained + rows the caller may see; `unmatched` names exactly the retained rows the filter rejects. + +## API surface + +Headers marked (new) do not exist before the step that lands them ([Delivery order](#delivery-order)). + +| Header | Holds | +|---|---| +| `table/data_source.hpp` | `struct Unloaded`; `Cell`'s alternatives `Unloaded` and then `Measure`, last; `ColumnInfo::level`, `dimensions`; `ColumnKind::Measure`; `TableErrorCode::SourceContract` (`"sourceContract"`); `displayText` returns empty text for `Unloaded`; `UnitInfo`, `UnitId`, `UnitRegistry` with `lineage()`, `UnitRegistryBuilder` (from a previous registry), `addUnitsOf`, `Measure`; `Services::units`; `DataSource::groups()`; `cellBytes`. | +| `table/sort.hpp` | `CellState::Unloaded`; `KeyColumn::read` maps `Unloaded`; `compareKeys` ranks valid, then empty and invalid, then unloaded. | +| `table/filter.hpp` | `enum class Match { No, Yes, Unknown }`; `CompiledFilter::evaluate(Column const&, KeyColumn const&, std::uint32_t) -> Match`; `passes` is `evaluate == Yes`; `FilterRun::takeUndecided() &&`; `FilterEntry::oneOf`; `GroupMode`, `ColumnCount`; `GroupFilter::group`, `mode`, `match`, `exclude`; matching for `Together`. | +| `table/engine.hpp` | `detail::JobInput::previousUndecided`, `detail::JobResult::undecided`; `Engine::undecidedRowCount()`, `undecidedRows()` (source rows), `onUndecidedChange(std::function)`; `Engine::distinctValues`; `ColumnLayout::setWidth`, `widths`, `setPinned`, `pinned`, `value`, `apply`, and `rebuild` placing a column by the fitting rule. | +| `table/query.hpp` | `TableQuery::columns`, `keys`, `distinct`, `retry`; `QueryLimits::maxColumns`, `maxKeys`, `maxSetValues`, `maxQuerySetValues`, `maxQuerySetBytes`; `ColumnLevel` and the row type's `columnLevels()`; `LevelLoaded` as a trailing parameter of `RowsSource` and the typed `apply`; `LevelsNeeded`, `levelsNeeded`; `PageRows::totalKind`, `undecided`, `awaiting`, `failed`, `indices`; `UnloadedRow`, `UnloadedLevels`; `Page::unloadedRows`, `undecided`, `awaiting`, `failed`, `indices`, `distinct`; `DistinctRequest`, `DistinctValue`, `DistinctValues`, `DateBucket`, `distinctValues`; `changeKeys`, `rowIdOf`; `PageFetch::columns`, `revision`; `RowsFetch`, `Refresh`, `RefreshPlan`; `PageWindow`'s key function, `maxKeys` and `maxColumns`; `PageWindow::visible` with columns, `superseded`, `cancelled`, `refresh`, `owed`, `invalidate`, `patch`, `unloadedLevels`, `undecided`, `awaiting`, `failed`; the specialisation `PageWindow`. | +| `table/edits.hpp` | `CellEdits::commit` refuses an unloaded cell. | +| `table/description.hpp` (new) | `TableColumn`, `ColumnGroupInfo`, `TableCapabilities`, `TableDescription`, `TableContext`, `ServedTable`, `GenericRow`, `GenericPage`, `ChangedRow`, `ChangedRows`, `TableOf`, `table::typed` and the model's `tableUnits` hook it calls, `table::scoped`, `table::rowScoped`, `table::derivedFrom`; the generic page's writer and reader. `ColumnDisplay`, `Rounding`, `ValueLabel`; `TableColumn::display`, `tone`, `tooltip`, `edit` and `EditInfo` ([`editing.md`](editing.md)); `TableDescription::rowTone`, `rowLock`, `bands` and `BandInfo`; `TableCapabilities::maxSortKeys`; `ResolveRequest` and the `Table..resolve` action; `ChangedRow::from`, `FailedRow`, `ChangedRows::failed`. | +| `table/row_selection.hpp` (new) | `RowSelection` and its schema's `x-selectionOf`, `SelectionPolicy`, `SelectedRows`, `resolve`, `ResolveRequest`; `RowRef` and its schema's `x-rowOf`. | +| `table/data_source.hpp`, `table/query.hpp`, `table/engine.hpp` (additions) | `TableErrorCode::ViewChanged`; the view cache entry's membership digest; `QueryLimits::maxSelectedRows`, `maxRetained`; `TableQuery::retain`, `Page::unmatched`, `Page::viewRevision` and their generic-page members; `Engine::retain`. | +| `table/query.hpp`, `table/filter.hpp` (removals) | `QueryPlan` and the planned types, `PlanUse`, `planQuery`, and `plan_conformance.hpp` whole: no table is paged in a database. | +| `ui/cell_format.hpp` (new) | `ui::formatCell`, the one formatter of a cell's text from its column's display and the session's `ui::FormatContext`. | +| `table/level_cache.hpp` (new) | `LevelRead`, `LevelUse`, `LevelSnapshot`, `LevelSource`, `LevelCacheOptions`, `LevelCacheStats`, `LevelCache`, `CellLevelCache`. | +| `table/view_cache.hpp` (new) | `ViewCacheOptions`, `ViewCacheStats`, `ViewCache`. | +| `table/state_store.hpp` (new) | `TableStateKey`, `StoredTableState`, `SaveOutcome`, `SaveResult`, `kNoDocument`, `ITableStateStore` with `shares()` and `publish`, `Sharing`, `MemoryTableStateStore`; the views operations; the state's and the views' readers, writers, version migration and fitting. | +| `forms/views.hpp`, `forms/engine/collection.hpp` | The schema carries `x-level` from `columnLevels()` and `x-column-group` from `columnGroups()`; `deriveColumns` copies them; `CollectionColumn::level`. | +| `core/change_types.hpp` | `effects::IChangeObserver` (`changed(Changes const&)`, `bind(AnnounceSink)`); `effects::AnnounceSink`. | +| `core/remote.hpp` | `RemoteServer::announce`, `RemoteServer::attach(std::shared_ptr)`; `ServerConfig::tableWork`, `views`. | +| `core/registry.hpp`, `core/effects.hpp` | `BRIDGE_REGISTER_TABLE` and its options; the actions `Table.` and `Table..describe`; the table's record; `effects::updatesTable`, `effects::changesTable`; the result walk's slot for `ChangedRows`, collecting each row's `key` and `from` and no `failed` key, and its record of a holder's `openMembers()` and `partialMember()`; `ActionRecordInfo::open`, `partial`, `opaque`. `Page` declares both members. | +| `ui/table_rows.hpp` (new) | `SortChain`, `TableTotal`, `TableRowRef`, `TableCountsView`, `TableRows`, `EngineRows`, `WindowRows`, `ValueRowsSource`; `ui::parseMeasure`; a selection of the view, retained, busy, failed and locked rows, and key moves by `from`, in both `TableRows`; `TableCountsView::retained`, `busy`; `SessionOptions::retainHold`; the element value `selectedCountKind`. | +| `ui/interpreter.hpp` | `Session::read`, `Session::watchRecord`, `WatchHolder`; the query cache's rules for open, partial and opaque entries; `SessionOptions::tableState`, `tableStateTimeout`, `tableStateDebounce`, `tableSettle`, `tableAwaitedRefetch`, `maxRangeRows`, `maxCopyRows`; the lowering of every table node onto `TableRows`; a table node's `cellMenu`, `headerMenu`, `retainChanged`, `headerEnabled` and element values `selectionSet`, `busyCount`; a column's display parts, `tone` and `tooltip`; a table node's `status`, `persist`, a column's `kind` and `locked`. | +| `ui/view.hpp`, `ui/mount.hpp`, `ui/backend.hpp` | `Virtualization::columnThreshold`, `cellThreshold`, `columnOverscan`, `realizePerFrame`; `ColumnExtents`; the column window, cell pools and the frame budget; `Table::status`; `IViewBackend::copyText`; the range-selection report by view rows. | +| `ui/table_state.hpp` (new), `ui/table_state_model.hpp` (new) | `PreferencesTableStateStore`; `TableStateModel` (`morph.tableState`) with its `publish` action for shared views, `TableStateOptions`. | +| `qt_quick` and the terminal backend | Cells and header cells for columns in the window only; pinned columns; header menus, drag, resize, the sort dialog, the column chooser, the filter menu, the status line. | + +A caller that passes nothing new gets what it gets without this design, with one exception, stated where it +applies: `ColumnLayout::rebuild` places a new column after its declared predecessor instead of last. + +## Tests + +Each case names the mutation it was seen to fail on, as the module's other tests do. + +| Condition | Test | Layer | +|---|---|---| +| (a) the first page arrives before a slow level is loaded | A recording `DataSource` logs the column of every `cell` and `readColumn` call and returns `Unloaded` for the slow level. `apply` returns the page, and the log holds only the sorted and filtered columns. Mutation: `apply` building keys for every column. Over the bridge: the list action answers while the loader is held on a latch the test never releases, and the reply's `unloadedRows` names exactly the unloaded rows and the level. Mutation: the model waiting for its loader. | `tests/table/test_table_unloaded_cells.cpp`; `tests/net/test_push_unloaded_rows.cpp` | +| (b) cells show as unloaded | `Page::unloadedRows` names exactly the unloaded rows and levels; `Engine::cellAt` returns `Unloaded`; `PageWindow::unloadedLevels` agrees after `accept`. Mutation: the typed `apply` dropping `unloadedRows`. | `test_table_unloaded_cells.cpp`, `test_table_server.cpp` | +| (b) unloaded cells do not match a filter | Per operator of every kind, `isEmpty` and `notEmpty` included, include and exclude, `any` and `all`, and a group: the row is undecided, the view lacks it, `totalKind` is `AtLeast`. A row `Unknown` at one stage and `No` at a later one is rejected. Mutation: `evaluate` returning `passes`. Property: invariant 1 over random tables, unloaded cells and completions. | `test_table_filter.cpp`, `test_table_unloaded_cells.cpp` | +| (b) unloaded cells do not sort as empty | A column with values, empties and unloaded cells, both directions: unloaded rows are the tail, after the empties. Mutation: `compareKeys` tying unloaded with empty. Property: invariant 2. | `test_table_sort.cpp` | +| (c) a level loads only when a shown, sorted or filtered column needs it | A table of `levelsNeeded` cases: a column of the level named, sorted, filtered, in a group, not named, `columns` absent, `columns` empty. A model with a recording loader: a query using no column of the level records nothing; one that names a column of it records the page's rows only; one that sorts on it records every candidate row. Mutation: `levelsNeeded` returning every level, which makes the first case record a load. | `test_table_query.cpp`; `test_push_unloaded_rows.cpp` | +| (d) exactly the arrived rows update, without polling | Engine: an undecided row arriving is one `Inserted` and one `onUndecidedChange`; an undecided row rejected is no view operation and one `onUndecidedChange`; a displayed row arriving is `Changed` for that row only, under `Immediate` and `Deferred`. Mutation: a repair that ignores `previousUndecided`. Window: `refresh` asks for the event's keys and one probe per held run; `patch` returns the replaced view rows only; a missing key, a moved row, an unheld key inside a held page and a changed total each invalidate; a keyed reply older than a later fetch for the same key is ignored. Bridge: over a real socket the server's action counter shows one page request, then none until `announce`, then one keyed request holding the announced keys and the window's probes; the test has no `refreshEvery` and advances no clock. Mutations: `refresh` asking for every held key; `refresh` dropping the keys the window does not hold, which leaves a row an edit moved into the window unseen. | `test_table_changes.cpp`, `test_table_server.cpp`, `test_push_unloaded_rows.cpp` | +| An event that precedes its page reply | The window is given `refresh(keys)` while the page fetch is in flight, then the reply with those rows unloaded: `owed` returns those keys. Mutation: `refresh` not recording keys in flight. | `test_table_server.cpp` | +| An ordinary edit on the same record | A held, fully loaded row's event yields a keyed fetch; a reply at another view row invalidates. Mutation: `refresh` skipping rows with no unloaded level. | `test_table_server.cpp` | +| Invalidation faster than a round trip | Invalidate, fetch, invalidate again, then accept the first reply: the page shows the reply's rows and is still stale; `visible` returns one fetch, not two. Mutation: `accept` ignoring every older revision. | `test_table_server.cpp` | +| `announce` | A derived record is included; more than `kMaxChangeKeys` keys become whole-type; an unregistered record is refused. `changeKeys` and `rowIdOf` round-trip both key kinds and agree with the record's key member. | `tests/net/test_push_unloaded_rows.cpp`, `test_table_query.cpp` | +| `TableQuery` on the wire | `columns` and `keys`, integer and text, round-trip through glaze; a query without them reads with both absent. An unknown column in `columns` is `UnknownColumn` and an unreadable one `ColumnNotReadable`; an empty `columns` gives a page of keys. | `test_table_query.cpp` | +| A value is loaded once | Two queries, then two clients over a socket, need the same 200 rows' level: `LevelCacheStats::loadedKeys` is 200 and the loader's own call log lists each key once. Mutation: `want` not checking the cache, which makes it 400 and 800. | `tests/table/test_table_level_cache.cpp`; `test_push_unloaded_rows.cpp` | +| Concurrent queries share a load | Eight threads call `want` for the same keys while the loader is held on a latch: one loader call. Mutation: no in-flight set. | `test_table_level_cache.cpp` | +| Reloaded once after invalidation | After `invalidate` of 10 keys the view lacks them; the next two queries load exactly those 10, once. An action declaring `updates` on the record does the same through the server with no call to `invalidate`. Mutation: `changed` ignoring the record, which leaves the old values served and the loader uncalled. | `test_table_level_cache.cpp`; `test_push_unloaded_rows.cpp` | +| A load in flight at invalidation | The loader is held; the row is invalidated; the loader returns the old value: the view does not hold it, `droppedLoads` is 1, and the next `want` loads again. Mutation: storing without the generation check, which serves the old value. | `test_table_level_cache.cpp` | +| Visible before told | The announce sink reads the cache when called and finds the value for every key it is given; on invalidation it finds none. Mutation: announcing before storing. | `test_table_level_cache.cpp` | +| Eviction | Over `maxBytes` the least recently used rows that no order lease holds go, the view shows them absent, and a query needing them loads them again; no event is sent for an eviction. | `test_table_level_cache.cpp` | +| No value crosses a scope | Two principals with different row scopes query one cached table: each reply holds only its rows, and the loader ran once for the shared rows. | `test_push_unloaded_rows.cpp` | +| An open entry hears every change | A cached page whose `awaiting` is not empty is marked by an event for a key it does not hold; one whose `awaiting` is empty is not. Mutation: the cache ignoring `open`. | `tests/test_ui_interpreter_cache.cpp` | +| A partial entry is not merged into | An `updates` reply for a row of a cached page with `unloadedRows` marks the entry and leaves its value; without `unloadedRows` it merges. Mutation: the cache ignoring `partial`, which shows an unloaded member's default as a value. | `tests/test_ui_interpreter_cache.cpp` | +| A table from a description | A model with no row type serves a table; a client given only the catalog draws its columns, sorts, filters and pages it. Mutation: a lowering that needs the node's `columns`. | `tests/table/test_table_description.cpp`; `tests/test_ui_table_model_*.cpp` | +| A model with several tables | Two tables of one model are authorised, cached and changed apart: a principal allowed one action is refused the other; an action declaring `updatesTable` on one marks only its watchers; an action that changes two tables returns two `ChangedRows`, and each table's watchers get that table's keys; `updatesTable` without its `ChangedRows` in the result is refused when the registries resolve; one table id in two models is refused when the registries resolve. Mutation: one record for the model. | `tests/net/test_push_tables.cpp`; `tests/table/test_table_description.cpp` | +| Columns by session | Two principals get different descriptions of one table; a page's `columns` are the caller's; a changed `revision` makes the client fetch the description again. | `tests/net/test_push_tables.cpp` | +| The generic page | Every kind of cell round-trips: empty, unloaded, a quantity with a factor and with none, a measure; a typed table served through `table::typed` writes the same page as the generic source of the same rows. | `test_table_description.cpp` | +| Column layout | A stored layout with unknown ids, a new column and every column hidden yields the fitted layout; hiding and moving create no cell widgets (gate D8). Mutation: `apply` ignoring `hidden`. | `tests/table/test_table_columns.cpp`; `tests/qt_quick` | +| Sort chains | `Shift`+click adds a key and flips one in the chain; a plain click replaces; a key past the table's `maxSortKeys` is refused. Mutation: `Shift` ignored. | `tests/test_ui_table_model_*.cpp`; `tests/qt_quick` | +| `oneOf` | It matches exactly the rows the OR of its `eq` entries matches, in include and exclude, with blanks beside it; an unloaded cell is undecided. Mutation: a `oneOf` that matches nothing. | `test_table_filter.cpp` | +| Distinct values | Counts are those of the rows the other filters leave; the column's own filter is ignored; counts, `blanks` and `invalid` sum to those rows when `partial` is false; a group's "(Blanks)" count is the rows its `isEmpty` entry admits; unloaded rows set `partial`. Mutation: counting over the view. | `tests/table/test_table_distinct.cpp` | +| Column groups | The truth table of [Column groups](#column-groups) row by row, including the row that tells `together` from `atLeast 2`; each quantifier with unloaded cells against its three-valued rule; an exclude; a group with exclude entries and no include entry, in either mode. Mutation: `together` evaluated as `atLeast`. | `test_table_filter.cpp` | +| Values with units | 300 g sorts between 0.2 kg and 0.5 kg in both directions; `gt "250 g"` drops 0.3 % rows; 0.3 % and 0.3 kg are not equal; 0.3 kg and 300 g are one distinct value; an operand with no unit is a ratio. Mutation: a key that ignores the unit's factor. | `tests/table/test_table_measure.cpp` | +| Persisted state before the first query | A table mounts with a stored sort and filter in a `MemoryTableStateStore` whose load is held: no query is sent; released, one query goes out carrying the stored sort and filter. Mutation: a table that ignores its store sends the default query. | `tests/test_ui_table_model_*.cpp` | +| Stale state is fitted | A stored state naming a removed column, a removed group, an unknown unit, a filter that no longer compiles and every column hidden: the table shows, with one column at least, the rest applied, each drop reported once; what a session's description lacks is written back unchanged. Mutation: applying the state unfitted. | `tests/table/test_table_state.cpp` | +| Saves are coalesced | Fifty changes inside the debounce are one save holding the last arrangement; a change during a save in flight is one more; unmounting saves at once. Mutation: no debounce. | `tests/test_ui_table_model_*.cpp` | +| A slow or failed load | A load past the timeout starts the table from defaults and is applied when it arrives, unless the user changed something; a failed load is reported once and later changes still save. | `tests/test_ui_table_model_*.cpp` | +| The person is the store's | Two principals mounting one table through the preferences-backed store read and write separate state; a key naming a person does not exist to forge. | `tests/net/test_push_tables.cpp` | +| Bound values win | With `sort` bound, a stored sort is neither applied nor saved, and the stored layout still is; `persist: false` loads and saves nothing. | `tests/test_ui_table_model_*.cpp` | +| One order on every surface | A `rows` table, a collection and a model-backed table over the same rows show the same order for the same sort, text and measures included. Mutation: the interpreter's pipeline left in place for one surface. | `tests/test_ui_table_model_*.cpp` | + +| A cached view is the view | Property: for random sorts, filters and unloaded cells, a page, a keyed reply and a second page built from one cache entry equal `apply`'s over the same snapshots. An arrival on an order level makes the next request compute again; one on a display level does not. Mutation: an entry that ignores a level's generation, which serves the old order. | `tests/table/test_table_view_cache.cpp` | +| One sort for many watchers | Fifty requests for one view while it is computed: one computation, on a `tableWork` thread. Mutation: no single flight. | `test_table_view_cache.cpp`; `tests/net/test_push_tables.cpp` | +| A reply holds the named columns only | A page of forty named columns holds no other cell, and loads only the levels those columns have; a column that scrolls in is fetched for the held pages and merged by key; a column fetch whose keys differ invalidates. Mutation: a writer that ignores `columns`. | `test_table_description.cpp`, `test_table_server.cpp` | +| A row the window never held | An edit moves an unheld row into a held page, above it, and across it: the keyed reply's view row, a probe and the total each invalidate; an edit far below the pages with the total unchanged does not. Mutation: no probes, which leaves the held rows one view row off. | `test_table_server.cpp` | +| A scroll that passes | A drag across the table sends no fetch until the visible rows rest for `tableSettle`, and cancels what it left behind; a scroll into the next page fetches at once. Mutation: a fetch per `visible` call. | `tests/test_ui_table_model_*.cpp` | +| An awaited order is throttled | With `awaiting` set, ten events in 100 ms are one refetch at once and one after `tableAwaitedRefetch`. Mutation: a refetch per event. | `tests/test_ui_table_model_*.cpp` | +| A level's layout is the cache's | Two principals whose descriptions hold different columns of one level, in different orders, read one cached value: each reply has each cell under its own column, and a column `mayRead` refuses is absent. Mutation: reading the value by the caller's column order. | `test_table_level_cache.cpp`; `test_push_tables.cpp` | +| A cache's size is deep | Values of twenty text cells evict at `maxBytes` of their real size. Mutation: `sizeof(Value)`, under which nothing is ever evicted. | `test_table_level_cache.cpp` | +| A reader blocks no one | With a snapshot held, a store, an invalidation and the observer call complete, and the snapshot still reads its old values. Mutation: a shared lock held by the snapshot. | `test_table_level_cache.cpp` | +| Order uses are leased | Two order uses that do not fit together: the first loads once and keeps every row, the second is `Unavailable`; after `orderLease` on an injected clock the first's rows are evictable. A level whose values outgrow the estimate stops loading and announces without keys. Mutation: no lease, under which the loader's call count grows without end. | `test_table_level_cache.cpp` | +| A failed load | The loader returns no value for ten keys: their cells are unloaded, the reply names the level in `failed` and not in `awaiting`, the keys are announced once, and no request loads them until `retryAfter` on an injected clock, a `retry` query or an invalidation. A row with nothing at the level comes back empty and loaded. Mutation: a failed key wanted again by every request. | `test_table_level_cache.cpp`; `test_push_unloaded_rows.cpp` | +| A row-scoped table | A principal's watch receives an arrival without keys and refetches its pages; no event it receives names a key outside its scope. `rowScoped` with an empty `scope` is `SourceContract`. Mutation: the record registered without `privateKeys`. | `test_push_tables.cpp` | +| An opaque entry | A document query on `Table.` and a distinct-values entry are marked by a keyed change of the table's record that names none of their rows, and are not merged into; a page's fractional `Number` cell is held as a decimal, while an ordinary action's reply with a fraction is still refused. Mutation: the cache looking for a key member. | `tests/test_ui_interpreter_cache.cpp` | +| A read with no entry | `Session::read` makes no cache entry and resolves with the reply's text, a fractional number intact; `watchRecord` puts the record in the watch set while its holder lives and is told a whole-type change on resync; the first page fetch follows the watch. | `tests/test_ui_interpreter_cache.cpp` | +| A document's rows as a source | A fresh decode of the same rows notifies nothing; one changed row is one `Updated`; a change to what a `sortBy` reads updates that row; an unused column holds no cells; integers with decimals are one `Decimal` column and a text among them is one invalid cell; a timestamp is a `DateTime` cell of whole seconds, rounded down; only a literal `kind` makes a `Number` column. Mutation: a diff by row value. | `tests/test_ui_table_model_*.cpp` | +| Windows of the renderer | 1,999 × 300 is windowed both ways, and 1,000 × 30 by its cells alone; cells and header cells alive match F2, pooled ones counted; a fling creates no cell once the pools are warm; a column growing left of the view keeps the columns in view where they are; pinned columns stay realized, narrow tables unpin for display only and pin again when the viewport widens. Mutation: a column window that ignores `cellThreshold`. | `tests/test_ui_mount.cpp`; `tests/qt_quick` | +| Keyboard and focus under windowing | The focused cell survives a scroll of 10,000 rows; `Ctrl+End` over rows not fetched lands on the last row when it arrives; the reported row count is the total, or unknown for a lower bound. | `tests/test_ui_mount.cpp`; `tests/qt_quick` | +| Range selection in server mode | A range over rows not held resolves to the view's keys through pages that name no columns; over `maxRangeRows` it is refused with a status message and selects nothing. | `tests/test_ui_table_model_*.cpp` | +| Copy | Selected rows copy as tab-separated display text in layout order, in the chosen display units; rows not held are fetched; unloaded cells are empty and counted in the message; over `maxCopyRows` is refused. | `tests/test_ui_table_model_*.cpp` | +| The status line | Counts for exact, lower-bound and undecided totals; a failed level with "Retry", which sends `retry`; a refusal shown once; `status: false` sends the message to the session's notifications. Mutation: a refusal with no message. | `tests/test_ui_table_model_*.cpp` | +| State of any size | A state with a 20,000-value filter saves through `PreferencesTableStateStore` and reads back equal, as segments each within `segmentBytes`; a save stopped after its segments leaves the previous state readable; a missing segment is a failed load. Mutation: no segments, the whole document in its head. | `tests/test_ui_table_state.cpp` | +| Views are not lost between windows | Two windows each add a view from the same loaded revision: the second save answers `Conflict`, reloads, and both views are stored. A table that loaded no views saves with `kNoDocument`; over a store that does not honour it, the retry after a `Conflict` whose reload finds nothing saves with an empty `expected`. A `state` save overwrites. | `tests/test_ui_table_state.cpp` | +| Unit numbers across registries | A successor registry keeps every number and tombstones a removed unit; a level cache keeps its values under a successor and invalidates under another lineage; a unit id with a space is refused. | `tests/table/test_table_measure.cpp` | +| A column's display | 0.125 at two places shows "0.12" under `HalfEven` and "0.13" under `HalfUp`; `eq 0.13` matches neither; an empty cell shows `empty`, an unloaded one its placeholder; a `Bool` with labels orders false first; `decimals` on a `Measure` column is `SourceContract`; copy writes the formatted text. Mutation: a sort over the formatted text, which orders "10.00" before "9.00". | `tests/test_ui_cell_format.cpp`; `test_table_description.cpp` | +| Companion columns travel with their column | A page naming a column names its `tone` and `tooltip` companions and the `rowTone` one; a column out of the window fetches neither; a document `tone` expression stops the companion being fetched. Mutation: companions fetched for every column. | `test_table_description.cpp`; `tests/test_ui_table_model_*.cpp` | +| A selection of the view | `Ctrl+A` on a model-backed table fetches no row; `resolve` under `Exact` returns the view's keys less `except` and refuses `ViewChanged` after an edit that moves a row into the view; under `Current` it returns the new view; a principal's resolution holds no row outside its scope; select-all is refused while rows are undecided. Mutation: `viewRevision` that ignores the source snapshot, which resolves the edited view under `Exact`. | `tests/table/test_table_selection.cpp`; `tests/net/test_push_tables.cpp` | +| Retained rows | After an action changes three rows so that the filter rejects them, they stay in the view, listed in `unmatched` and counted; a change of the filter clears them; an action over `maxRetained` retains none and says so; a client-mode engine does the same. Mutation: the merged view written into the shared view cache entry, which serves one session's retained rows to another. | `test_table_selection.cpp`; `tests/test_ui_table_model_*.cpp` | +| A key that changes | A `ChangedRow` with `from` moves the selection, the focus and a failed mark to the new key and fetches both. Mutation: the walk ignoring `from`, which leaves the old row's watchers untold. | `tests/test_ui_table_model_*.cpp`; `test_push_tables.cpp` | +| Busy and failed rows | While an action over a selection runs, its rows draw busy and refuse an edit; a `failed` entry draws `err` with its message until the row's next change; "Select them" selects exactly the failed keys. Mutation: busy state cleared only on success. | `tests/test_ui_table_model_*.cpp` | +| The application's menu entries | `cellMenu` entries read `row`, `column` and `value`; a right-click on an unselected row selects it alone; "Filter by this value" sets a one-member `oneOf` and on an empty cell `isEmpty`; a `visible` on `column` shows an entry on one header only. Mutation: the cell menu read in the table's scope. | `tests/test_ui_table_model_*.cpp`; `tests/qt_quick` | +| Resolving from elsewhere | `Table..resolve` from another model's action returns the caller's keys and counts unseen keys in `dropped`; a view over `maxSelectedRows` is `LimitExceeded`; after `ViewChanged` the client offers the view as it is and resends on confirmation; a change of the filter ends a view selection. Mutation: `resolve` run under the server's principal, which returns rows outside the caller's scope. | `tests/net/test_push_tables.cpp`; `tests/test_ui_table_model_*.cpp` | +| The view revision is membership | An edit that changes a cell of a row in the view without moving it in or out leaves `viewRevision` as it was; one that brings a row in changes it. Mutation: the revision taken from the snapshot's version, which refuses the first case. | `test_table_selection.cpp` | +| Retained rows and the event | With `retainChanged`, an event that precedes its action's reply causes no refetch until the reply or `retainHold`. Mutation: no hold, under which a retained row leaves the view and comes back. | `tests/test_ui_table_model_*.cpp` | +| Locked rows and companions | A row whose `rowLock` companion holds text draws locked with that tooltip and refuses a cell edit; companion columns are absent from the column chooser and the header menus; an unknown tone is reported once. Mutation: the chooser listing every column of the description. | `tests/test_ui_table_model_*.cpp` | +| A raised sort bound | A table whose `limits` set 32 accepts a 32-key chain from the header and refuses the 33rd; the description carries the bound; `limits` above 32 is `SourceContract`. Mutation: the client holding 8 whatever the description says. | `tests/test_ui_table_model_*.cpp`; `test_table_description.cpp` | +| Shared views | A view published through `morph.tableState.publish` is read by a second principal and copied by "Save as my view"; a principal the authoriser refuses `publish` is refused; a store whose `shares()` is false, a `MemoryTableStateStore` built with the default `Sharing::Private` among them, offers no publishing; `defaultOnMount` applies the default view's sort and filters over the stored state at mount. Mutation: the shared part saved through `save`, which an authoriser cannot tell from a user's own state. | `tests/test_ui_table_state.cpp`; `tests/net/test_push_tables.cpp` | +| Copy of a selection of the view | A copy of a view selection less two keys writes the view's rows in order without them, fetched as pages; over `maxCopyRows` it is refused. | `tests/test_ui_table_model_*.cpp` | +| A disabled header | With `headerEnabled` false a header click, a filter menu and a column drag change nothing and each is refused in the status line; selection and copy still work. Mutation: `headerEnabled` read once at mount, which leaves the header enabled after the condition turns false. | `tests/test_ui_table_model_*.cpp` | + +The arrival path on a screen (a model-backed `table`, its repaint and its frame cost) is tested and measured +with the lowering, as cases U6, F6 and F7 of [Performance](#performance). + +## What this does not do + +- It does not know how a level is read. The loader is the model's function; the level cache decides when it runs. +- It does not fetch one cell's detail on demand. A level that is never loaded in bulk and is fetched for one row + by a keyed query naming its column is expressible, and nothing here assumes a level is loaded for all rows. +- It does not add row attributes. `UnloadedRow` is a sidecar keyed by row index; another per-row sidecar on `Page` + does not conflict with it. +- It does not give `RowsSource` a row-level update: `setRows` notifies `Reset`. A client-mode table that + wants exact row updates on arrival uses a `VectorSource`. +- It does not page a forms collection or make its rows unloaded: a collection's rows arrive whole, and a + collection whose `v-query` takes a query is a design for the forms specs. +- **It does not edit cells.** Editing a cell in place, the grid that lays out a fixed form as rows and columns, + spans, header bands and summary rows are [`editing.md`](editing.md)'s, which builds on this pipeline. A row + of a model's table is changed by an action of the application that declares `updatesTable`. +- It does not format a value on the server for a client: the client formats from the exact value + ([How a column shows its cells](#how-a-column-shows-its-cells)). +- **It does not export.** Copy puts selected rows on the clipboard ([Copy](#copy)); writing a view to a file is + an application action over the query. +- It does not group rows, aggregate, or total a model-backed table: `group` and `rowSpans` are a `rows` table's. +- It does not page, sort or filter a table in a database. A model with rows in a database reads them into a + `DataSource`; a report that aggregates over a database is the application's. +- It does not offer top-N or ranking filters, or colour and icon filters. A tone is shown, never filtered on; + a filter on what decides it is a filter on that column. +- It does not keep loaded values across a server restart ([Caching layers](#a-persistent-tier)). +- It does not repair a cached view when a level's generation changes: the view is computed again, once for all + its watchers ([The view cache](#the-view-cache)). +- It does not cache distinct values on the server. +- It does not invalidate a level cache in local mode, where no server derives changes: the application calls + `invalidate` itself. +- It does not lower a collection's or a wizard's chrome. +- It does not turn a `rows` table bound to a page into a model-backed one. +- It does not give a model-backed table grouping or row spans; the node refuses them. Its select-all is not + a client-side one: it is a selection of the view, resolved on the server. +- It does not sort or filter held rows on the client in server mode + ([Where sort and filter run](#where-sort-and-filter-run)). +- It does not change `forEach` or `grid`. +- It does not define the `layout` preference point. A table's arrangement is its persisted state, and the + `columns` and `saved` points that name a table edit that state. +- It does not merge two windows' arrangements or push a saved arrangement to a table that is already mounted. +- It does not limit the size of a table's stored state. + +## Alternatives considered + +- **A readiness mask per row and level instead of a `Cell` alternative.** It states the loader's unit directly and + costs one bit per row and level. But inside the engine the mask is a second call beside every cell: + `RowSnapshot` needs a new virtual, key building needs the mask beside each cell it is handed through + `ColumnSink`, `TableSnapshot`'s chunks and `withRow`, `VectorSource::updateRow` and `RowPatcher::patchRow` need + a mask argument, and every reader of `Engine::cellAt` must ask a second question or show an unloaded cell as + empty. The mask is used where a `Cell` cannot go, on the wire beside typed rows. +- **A `Loadable` member type in the row.** It would make the wire state impossible to ignore, but changes every + row type, its schema and every reader of its JSON, and says per member what is true per level. +- **Showing undecided rows in the view.** See [Unloaded cells in filters](#unloaded-cells-in-filters): it shows rows + the filter may reject and needs a + total that is an upper bound. +- **Two-valued filters, with an unloaded cell matching nothing.** An include then hides the row and an exclude shows + it, so the same unknown is answered both ways, and invariant 1 fails for excludes. +- **Unloaded tying with empty in the order.** Rows whose place is unknown would be scattered among the empties by + source row. +- **A separate "rows by key" action.** A second action per table repeats the table action's scope and + authorisation and can drift from it; `keys` on the query reuses both. +- **A keyed reply without view rows, patched in place.** It cannot tell an arrival from an edit that moves the + row, so a row edited in a sorted column would stay where it was. +- **Refreshing only rows with an unloaded level.** The record's events also carry edits; a loaded row would then + never refresh. +- **Dropping every reply older than the current revision, or cancelling fetches on `invalidate`.** With events + closer together than a round trip no reply is ever current, and the window never updates. +- **`announce` taking a ready-made `effects::Changes`.** It skips derived records and the key bound unless every + caller rebuilds them. +- **A level name in the event.** The server would decide per connection what a client needs; the client knows + what it shows and holds. +- **`ChangeKind::Loaded`.** An engine does the same work for it as for `Updated`. +- **Shown levels in the query instead of columns.** It keeps a query equal while columns of one level come and + go, which matters only where the query's body is a cache key. A window's fetches make no cache entry, and a + reply of every column is 1.27 MB at 300 columns, decoded on the painting thread in a browser, for the twenty + a user sees. +- **Asking only for the keys a window holds.** An edit that moves a row the window has never held into its + pages is then never seen, unless every action that might do so declares a whole-table change; and an action's + author cannot know how each client has sorted. +- **Sorting for every request.** Every page of a scroll, every keyed fetch and every watcher of an arrival pays + 33 to 46 ms at 100,000 rows, on a strand that answers nothing else meanwhile. +- **A view of the level cache that holds a shared lock.** A reply holds it for as long as its sort takes, and + the observer call that removes entries runs on the server strand and would wait for it. +- **Eviction by recency alone.** A row a view orders by is evicted by another query's loads, leaves the view + with no event, and is loaded again; two sorts on one level can then evict each other without end. +- **One untyped list of changed keys.** An action's keys are matched to a record by the type of the result's + slot, so one list cannot belong to two tables. +- **An edit action in the table's contract.** It needs client vocabulary, validation and effects of its own; + half of it in the contract is a capability no client can use. +- **`Pending` for the cell's state, renaming the table's other uses of the word.** A `table` element's `pending` + is read by documents, and the two facts differ. +- **Table state through the preferences model.** Its value bound is right for a preference and wrong for a + filter of 20,000 values; an exemption per caller would make the bound mean nothing. +- **A size limit on table state, dropping what does not fit.** A filter the user set would be forgotten + silently at the next mount. +- **Each model keeping its own store of loaded values.** Every model would re-derive deduplication, the bound, + the generation check and the order of storing and announcing, and a table would be as correct as its model's + copy of them. +- **Expiring cached values by age.** A slow value would be reloaded although nothing changed it, and a changed + one would be served until its age ran out. Invalidation says exactly when a value is wrong. +- **One cache per principal.** It multiplies the slowest work by the number of users. Scope is applied to rows + before the cache is read, so raw values can be shared. +- **An effect naming the levels it invalidates.** Effects name records; a second vocabulary beside them would + drift from the first. The cache's own `invalidatedBy` narrows instead. +- **Announcing an `order` level's arrival without keys for cache-driven screens.** It makes the loader know what + kind of client is listening. The cache's rule for open entries needs nothing from the server. +- **Sorting and filtering the held window on the client while the server's reply is in flight.** The held rows + are a slice of the old order, so their local order is not a slice of the new one: rows would move twice. +- **A row type as the contract.** The columns would be fixed when the server is compiled, so a table whose + columns depend on the session, or on data, could not be said, and every table would need a struct. +- **One generic table action addressed by a table id in its body.** See + [A model's tables](#a-models-tables): authorisation, the catalog, the cache key and effects are all per + action. +- **Column arrays on the wire.** The same bytes as row arrays, and every client structure is by row. +- **An unloaded marker in each cell.** Twenty markers a row for what one level name says. +- **A second, simpler pipeline for small tables.** Two orders on one screen, and the small table is the + one that grows. +- **A second engine for document values.** The engine's keys are typed arrays built once; ordering document + values directly is the per-comparison cost this replaces. +- **Detecting a paged `rows` expression and windowing it.** See + [Screens over a server's pages](#screens-over-a-servers-pages). +- **Virtualizing columns in the Qt Quick backend alone.** The mount would still build every cell's node; the + window has to be the mount's, as the row window is. +- **A list of `eq` entries for a value filter.** `QueryLimits::maxEntries` is 32, and 10,000 entries are 10,000 + comparisons a row. +- **One "all values" mode that lets two values share a column's match.** For values it is the same as + `together`, since a cell has one value; for conditions it is two `any` groups, which AND already. +- **Trying every assignment for `together`.** Sixteen entries over sixteen columns are 16! assignments; a matching + is found in a few hundred steps. +- **Paging in the database**, the model translating each query into the database's own query and the server + answering only what the database cannot say. The table's order would then be the database's collation + wherever the query was pushed down and the engine's where it was not, so two tables, or one table before and + after a filter, would order the same text differently. Every feature (column groups, `together`, values with + units, unloaded cells and undecided rows, distinct values by fold) would depend on what each store can + translate, and every model would need a translator and a conformance run to show it agrees with `apply`. + A `DataSource` read from the database and `apply` over it give one order and every feature, at the cost of + holding a column's keys on the server while it is sorted or filtered, which the 100,000-row budget allows. +- **A quantifier on the existing `combine`.** `combine` says how entries meet in one cell; the quantifier counts + columns. One name for both leaves the fourth example unsayable. +- **Groups as a merged virtual column.** Sorting and showing the columns one by one would be lost, and "exactly + one" cannot be asked of a merged value. +- **One canonical unit for a mixed column.** There is no factor from kilograms to percent. +- **A per-cell dimension inside `QuantityCell`.** It grows every cell of every table by eight bytes; `Measure` is + smaller than the largest alternative. +- **Reversing the dimension groups with the direction.** The groups' order is a convention, not a magnitude. +- **Percent as its own dimension.** 50 % and 0.5 would be different values that mean the same. +- **A column default unit for an operand with none.** The same text would mean different amounts on different + columns; the menu supplies the unit instead. +- **Comparisons `Unknown` across dimensions.** `Unknown` means "not loaded yet"; a row would wait for a value + that will never come. +- **A separate `notIn` operator.** `exclude` already negates an entry, with the engine's rule for empty cells. +- **Distinct values over the view, the column's own filter included.** A value the user unticked would vanish + from the list and could not be ticked again. +- **A sibling action for distinct values.** It repeats the table action's scope and can drift from it. +- **A third click on a header clearing the sort.** It changes what a click does in documents that exist; the + header menu removes a key. +- **Persisting the layout through a bound `layout` and a handler in every document.** Every document would repeat + it, and the first page would be fetched before the handler ran. The binding stays for a document that wants + the value. +- **Table state as preference points.** A point's value is loaded after the screen mounts, which is after the + first query; and each application would need the points declared per table. One interface the table itself + calls loads before the query and needs no declaration. +- **Two stores, preferences and table state.** One arrangement could be written to both and read from either. + The default table store writes into the preferences store, so there is one. +- **The person in the key.** A client could ask for another person's state. +- **Merging concurrent saves.** See [Persisted state](#persisted-state). +- **Waiting for the state however long it takes.** A slow store would hold every table blank. +- **Text formatted on the server.** It cannot follow the user's locale or display unit without a request per + change, and a column sorted by its text orders "10.00" before "9.00". The exact value crosses; the client + formats it. +- **A rule language for tones in the description** (ranges, thresholds, colours). It would be a second expression + language beside the document's, evaluated on a client that may lack the values a rule needs. A companion + column computed by the model, or a document expression, says the same with what exists. +- **Select-all as a list of keys in server mode.** It fetches every key of up to 100,000 rows before the user + has done anything with them, and is stale by the time the action runs. The view's filter and revision are + what the user selected. +- **Retained rows frozen at their place.** A retained row that the sort would move is a row whose edit the + user cannot see take effect; retaining exempts it from the filter and leaves the order truthful. Holding a row + still is `ReorderPolicy::Deferred`'s, for the time an edit is in flight. +- **A rename as a removal and an insertion.** The selection, the focus and a failed mark would be lost on the + row the user is looking at. +- **One `TableRows` implementation that holds either an engine or a window.** The two differ in whether a row can + be absent, which every reader would then test; two implementations of one interface keep that in one place. + +## Failure modes + +| Situation | Behaviour | +|---|---| +| A level never arrives | Its cells stay unloaded and its rows stay undecided; nothing times out in the engine. A load that failed is named in the reply's `failed`, and the status line offers "Retry". | +| A `Unloaded` cell in a base-level column | `SourceContract`, naming the column. | +| A `columnLevels()` entry naming no column | Refused where the row's columns are reflected. | +| An event without keys, a `resync`, or a key that is neither integer nor text | `PageWindow::invalidate`: the shown pages are fetched again. | +| An event that precedes the page reply holding its rows | The keys are recorded and `owed` asks for them after the reply. | +| A keyed reply misses a requested key, or returns it at another view row | The window invalidates. | +| A keyed reply after a later fetch for the same key | That row is ignored. | +| A page reply older than the current revision | Accepted when newer than what is held; the page stays stale. | +| More event keys and probes than `maxKeys` | The window invalidates instead of asking for rows. | +| A keyed query to a model that does not translate keys | `Unavailable`; the window invalidates. | +| `announce` for an unregistered record | Refused; nothing is sent. | +| `announce` after the server is gone | The cache's sink finds no server and does nothing. | +| The loader throws, or returns no value for a key it was given | The keys are `Failed`: their cells stay unloaded, replies name the level in `failed` and not in `awaiting`, `LevelCacheStats::failedLoads` counts them, `onLoadFailed` is told and the keys are announced once. They are loaded again after `retryAfter`, by a `retry` query, or after an invalidation. | +| A row is invalidated while its load is in flight | The load's result is dropped for that row. | +| The cache is over `maxBytes` | The least recently used values no order lease holds are evicted; their cells are unloaded again and reload on demand. | +| A sort or filter on a level whose candidate rows cannot fit in `maxBytes` | `want` finds the keys times the mean value size over the room left, and the framework refuses the query with `Unavailable` naming the column; nothing is loaded. | +| A change of a record in `invalidatedBy` other than the row's own | The whole level is invalidated and the table's record is announced without keys. | +| The server restarts | The cache is empty; every level is unloaded until it is asked for. | +| An edit of an unloaded cell | Refused on the cell with a `FieldError`; nothing is sent. | +| A filter on a level no cache serves | Every row is undecided and `awaiting` names the level. | +| A reader of `Page::rows` that ignores `unloadedRows` | It shows unloaded members as the server left them. | +| A `rows` table whose sort column holds values of different kinds | Those cells are invalid and sort last; reported once at the `sort` path. | +| A `rows` table over more rows or cells than the client-mode bound | A warning naming the table; it still shows. | +| A model-backed table whose action does not take a `TableQuery` | Refused when the document loads. | +| `pageSize`, `page`, `group` or `rowSpans` on a model-backed table | Refused when the document loads. | +| A row not fetched yet in a server-mode table | The row draws as a placeholder row of the estimated height. | +| A column scrolled into range | Its cells are realized for the realized rows; its width may grow once. | +| A fetch fails | `PageWindow::fail`: the table shows the error until the next reply. | +| A document names a table the model does not have | Refused when the document loads, against the catalog. | +| A reply's `revision` differs from the description held | The client fetches the description again and resets its window. | +| A description with two columns of one id, a key that is no column, a level or group naming no column | The table's action answers `SourceContract`; nothing is shown. | +| A principal may run a table's action but read none of its columns | A page with no columns; the table shows its empty state. | +| A stored layout names a column the table lacks, or hides every column | The id is dropped; the first declared column is shown. | +| A sort key past the table's `maxSortKeys` | Refused, with a message in the table's status line. | +| A table whose `limits` set `maxSortKeys` above 32 | `SourceContract` when the table is first served. | +| A `oneOf` over `maxSetValues` | `LimitExceeded`; the menu sends the smaller side, and disables the list when both exceed it. | +| A distinct request to a model that does not translate it | `Unavailable`; the menu offers conditions only. | +| A values list while the column's level loads | The loaded values with `partial`; the list refreshes on each arrival. | +| A saved view with a filter on a removed column | That filter is dropped when the view is applied. | +| No table state store is injected | Tables keep their state while mounted and persist nothing. | +| The state's load is slower than the timeout | The table starts from defaults; the state is applied when it arrives unless the user changed the arrangement. | +| The state's load or save fails | Reported once through the session; the table keeps working, from defaults or with the arrangement it has. | +| Stored state of a version the framework does not know, or that is not JSON | Not used; reported; overwritten at the next change. | +| A save over the operator's quota, or refused by the store | `Refused`: the status line says so, and the table keeps its arrangement, unsaved. | +| A stored state whose segment is missing | A failed load: reported, and the table starts from its defaults. | +| A `views` save over a revision another window replaced | `Conflict`: the table loads the views again, applies its one change and saves once more. | +| Stored state names what the caller's description lacks | Not applied; carried and written back unchanged. | +| A `Measure` cell whose unit the registry lacks, or whose dimension the column does not allow | An invalid cell: it sorts with the empty cells and matches nothing but `notEmpty`. | +| A `Measure` cell whose base amount does not fit | An invalid cell. | +| An operand with an unknown unit, a dimension the column does not allow, or two dimensions in a `between` | `InvalidValue`, naming the column. | +| An operand with no unit on a column that allows no ratio | `InvalidValue`. | +| A `Measure` column and no unit registry in the services | `SourceContract`. | +| A stored display unit the registry no longer has | Dropped; the cells show in their own units. | +| A group of columns of different kinds, of fewer than 2 or more than 16 columns, or sharing a column with another declared group | Refused where the columns are read. | +| A group filter naming a group the table lacks | `UnknownColumn`, naming the group. | +| `together` with exactly 1 include entry, or more include entries than the group has columns | `InvalidSpec`. | +| `atLeast` or `exactly` with n below 0 or above the group's column count | `InvalidSpec`. | +| A user-formed group loses a column | The column leaves the group; under two columns the group and its filter are dropped. | +| A query's `columns` names a column the table lacks, or one the caller may not read | `UnknownColumn` or `ColumnNotReadable`; the client fetches the description again and asks once more. | +| A column fetch whose keys are not the held page's | The rows moved between the two fetches; the window invalidates. | +| A page reply whose total differs from the window's | The window adopts it and marks its other pages stale. | +| A keyed reply that shows a probe, or any held key, at another view row; an unheld key inside a held page; another total | The window invalidates. A check that fires because two replies crossed costs one page fetch. | +| A cell expression reads a column the window does not hold | The field reads as absent, the column is fetched, and the cell is evaluated again when it arrives. | +| An expression reads the row in a way the loader cannot follow | The table fetches every column; a warning names the node. | +| A fetch for a page the user scrolled away from | Cancelled; its reply, if it comes, is ignored. | +| `table::rowScoped` with an empty `scope` | `SourceContract` when the table is first served. | +| `updatesTable` on an action whose result holds no `ChangedRows` | A registration error when the registries resolve. | +| A second order use of a level that does not fit beside the first | `Unavailable` while the first's lease lives. | +| Leased values outgrow `maxBytes` while they load | The cache stops loading for order, drops the lease and announces the record without keys; the next query is refused. | +| A range selection over more than `maxRangeRows` rows, or a copy of more than `maxCopyRows` | Refused, with a message in the status line; nothing is selected or copied. | +| A unit id with white space, or one that begins like a number | Refused by `UnitRegistryBuilder`. | +| A level cache read under a registry of another lineage | The level is invalidated: its unit numbers mean nothing there. | +| A `rows` table that sets `persist` and has no `id` | Refused when the document loads. Without `persist` it shows, and persists nothing. | +| A refusal on a table whose document sets `status: false` | Shown through the session's notifications. | +| A companion column that names no column, or is not `Text`; `decimals` or `unit` on a `Measure` column | `SourceContract` when the description is built. | +| A companion's tone that is not a tone name | No tone; reported once for the column. | +| `resolve` under `Exact` after the view's membership changed | `ViewChanged`; the client keeps the selection and asks the user to confirm on the view as it is. | +| A selection of the view larger than `maxSelectedRows` | `LimitExceeded`. | +| Select-all while rows are undecided or a level is awaited | Refused, with a message in the status line. | +| An action that retains more rows than `maxRetained` | None of its rows are retained; the status line says so. | +| A `ChangedRow::from` the client does not hold | The new key is fetched as any changed key; nothing moves. | +| A gesture on a header while `headerEnabled` is false | Refused, with a message in the status line. | +| A `publish` the authoriser refuses, or a store whose `shares()` is false | Refused with a message; over a store that does not share, publishing is not offered. | +| A user's own `save` of the `shared` part | Refused. | +| A `rowLock` companion that names no column, or is not `Text` | `SourceContract` when the description is built. | + +## Open questions + +- **Retaining the rows of an action over a whole view.** `retain` carries keys, so an action that changes more + than `maxRetained` rows (a replacement over every visible design) retains none of them. Carrying a set the + server holds for the session, named in the query, would lift the bound; whether that is needed is settled by + the first application that meets it. +- **A level cache in local mode.** With no server deriving changes, the application invalidates a cache itself. + A hook for it belongs with local mode's effects. +- **Frame timing in CI.** Whether `QQuickRenderControl` with the software backend gives stable step times on the + CI image is settled by the first baseline. +- **The shard count of a level cache.** 256 shards make a batch of 64 keys copy about a quarter of the cache's + key entries at 100,000 rows; L6 measures it, and the count is a constant to tune from that figure. + +## Neighbouring specs + +This document is the design. The specs below describe the code, so each takes its part when the step that +builds it lands, and until then says nothing of it; a link from here to one of them is to the file, not to a +section that does not exist yet. + +| Spec | Takes | With step | +|---|---|---| +| [`../core/registry.md`](../core/registry.md) | `BRIDGE_REGISTER_TABLE` and its options, the table's record and `TableOf`, the result walk's slot for `ChangedRows`, `openMembers`, `partialMember`, an opaque holder | 1, 2d | +| [`../core/backend.md`](../core/backend.md), "Fan-out" | `ServerConfig::tableWork`; `RemoteServer::announce`, `attach`, `IChangeObserver`; the view cache | 1, 2c | +| [`../ui/interpreter.md`](../ui/interpreter.md), "Queries and the cache" | The rules for open, partial and opaque entries; `Session::read` and `watchRecord` | 2d | +| [`../ui/interpreter.md`](../ui/interpreter.md), "Not yet lowered" and the rows' pipeline | The entry for a model-backed `table` goes; the lowering onto `TableRows` is described; the "Rows' pipeline" and "Groups" rules keep what the lowering does around the engine's order | 4, 6 | +| [`../ui/document.md`](../ui/document.md), the `table` kind | `table`, `status`, `persist`, `layout`, `configurable`, a column's `kind` and `locked`; `filters` on every table; `cellMenu`, `headerMenu`, `retainChanged`, `headerEnabled`; a column's display parts, `tone` and `tooltip`; the element values this design names | 4, 6, 7, 9a, 9b | +| [`../ui/preferences.md`](../ui/preferences.md) | That table state has its own model and is not bounded by `maxValueBytes`; the `columns` and `saved` points | 4 | +| [`../qt_quick/backend.md`](../qt_quick/backend.md) | The column window, cell pools, pinned columns, the status line; the menus and dialogs | 5, 7 | +| [`../forms/views.md`](../forms/views.md) | `x-level`, `x-column-group` and `x-measure` on a schema property, and the `measure` kind | 2a, 3 | +| [`engine.md`](engine.md) | Its "Not here yet" entries for the model-backed table and the single-threaded steps; `ColumnLayout`'s fitting rule | 4, 6, 7 | +| [`engine.md`](engine.md), `database_pages.md` | `planQuery`, `QueryPlan` and the conformance helper leave `engine.md`; `database_pages.md` is removed | 0a | +| [`editing.md`](editing.md) | Editing cells in place, grids, spans, header bands and summary rows, on this pipeline | its own order | + +## Delivery order + +The design lands in this order. Each step is shippable and green alone, and carries the gates named. A count +gate runs as an ordinary test; a timing is recorded in [Performance](#performance) when the step lands. + +| Step | Lands | Gates and records | +|---|---|---| +| 0 | The fixture's rows, with nothing that does not exist yet: the column-store `DataSource` and its generator (`bench::WideTableSource`), and a baseline of what the code does today. The table tests are built for WebAssembly and run under Node. | Gate: S3. Recorded: S1 and S2 with every cell loaded; S7 as ten `apply` calls; S8; B1 at 10,000, 20,000 and 100,000 rows; B2; B5; U1 to U5; W7 as a typed page; F2 to F5 on a `rows` table of 2,000 × 300, the size a mount without a column window holds | +| 0a | Store paging goes: `QueryPlan`, `planQuery`, `PlanUse` and `plan_conformance.hpp`, their tests, and the example models that page in SQLite, which serve their rows as a `DataSource` instead. | The table, net and example suites green without them | +| 1 | The generic table contract: `TableDescription`, `ServedTable` over a `source`, `BRIDGE_REGISTER_TABLE`, its options and its two actions, the table's record with `updatesTable`, `changesTable` and `ChangedRows`, the generic page with every cell encoding, `TableQuery::columns`, `table::typed`, requests answered on `tableWork`. The fixture becomes the registered model `bench::WideTableModel` with its three tables and no slow level. | W1, W2, W5, W7; W6's bytes and codec | +| 2a | The engine's part of slow columns: the `Unloaded` cell and its rank, the three-valued filter and the undecided set, `ColumnInfo::level`, `levelsNeeded`, `LevelLoaded`, `unloadedRows` on `PageRows` and the typed `Page`. | S1 to S6 | +| 2b | The wire's part: `unloadedRows`, `undecided`, `awaiting`, `failed` and `indices` on the generic page; `TableQuery::keys` and the keyed reply with its totals. `TableQuery::columns` is step 1's. | W3, W4 | +| 2c | The server's caches and the push: `LevelSource`, `LevelCache` with leases, failures and immutable snapshots; `RemoteServer::announce` and `attach`; the view cache. The fixture gains its slow level. | L1 to L8, S7, S9, C1 to C3 | +| 2d | The client's part: `PageWindow` under changes, with columns, probes and `superseded`; `Session::read` and `watchRecord`; the query cache's rules for open, partial and opaque entries. A table served over `apply` and read through a `PageWindow` then shows a first page before a slow level loads, shows its cells as unloaded, loads a level only when a named column needs it, and updates exactly the rows that arrived. | K1 to K4, K6, K7, E1 to E4 | +| 3 | The engine's configuring additions: `oneOf`, `distinctValues`, column groups with quantifiers and `together`, `Measure` and the unit registry, `ColumnLayout`'s widths, pinning, fitting rule and stored shape. | D1 to D6, G1 to G7, M1 to M5 | +| 4 | `TableRows` and the lowering of a model-backed `table` onto `PageWindow`, from the description, with the status line's counts. The four behaviours of 2d then hold on a screen. `ITableStateStore`, the framework's stores and the load before the first rows land here, for sort and filters, so the rule is built into the first lowering. | U6 (E1 to E3 on a screen), K5, K8, F6, F7, T1, T3 to T5; W6's one request; F1 recorded | +| 5 | The column window in the mount and in both backends: extents, pinned columns, cell pools, the frame budget, focus, keys and counts under windowing; range selection in server mode. **Exit criterion:** U8, the same scrolls in the WebAssembly build in a browser, within F3's and F4's frame budgets. | F1 to F5, F8 to F10, U7, U8, D8 | +| 6 | `rows` tables on the engine through `ValueRowsSource`; the interpreter's own sort and page go. | U1 to U4; B1's 20,000-row step bound | +| 7 | The configuration interface: header and table menus, column order, visibility, pinning and width, persisted with the rest of the table's state; sort chains; the filter menu with values, conditions, groups and units; copy. Screenshots of existing screens change here, as intended. | D7, D9, B3, B4 | +| 8 | Collections through the same lowering. | U5 | +| 9 | Saved views, as the `views` part of the persisted state, with the conflict rule; shared views and the default first. | T2 | +| 9a | A column's display and `ui::formatCell`; companion columns for tone and tooltip; header units. It may land before step 4; if it lands after, step 4's lowering formats through a stand-in that 9a replaces. | The display and companion tests of [Tests](#tests) | +| 9b | Acting on rows: `RowSelection`, `resolve` and `Table..resolve`, `viewRevision`, retained rows, `ChangedRow::from`, busy, failed and locked rows, the application's menu entries, `headerEnabled`. Needs step 4. | The selection, store selection, retained, key-change, busy, locked, menu and disabled-header tests of [Tests](#tests) | +| 9c | `maxSortKeys` configurable up to 32, carried in the description. | "A raised sort bound" | +| 10 | As measured: repairing a cached view in place of computing it again, local work when a window holds the whole view, a persistent tier under the level cache. | The figures that justify each | diff --git a/docs/spec/tui/frontend.md b/docs/spec/tui/frontend.md index e8b76758f..8c6b6b32b 100644 --- a/docs/spec/tui/frontend.md +++ b/docs/spec/tui/frontend.md @@ -94,7 +94,7 @@ width: the terminal does not wrap it, so it has no unbreakable segment to keep w | Dialog | a centred box over everything; a description given as runs draws them on the description's row, as a text draws runs; its footer is the box's bottom row, its children against the right edge, one cell apart, and stays last when the content mounts again. As a sheet the box fills the viewport, its top row draws `[dismissLabel]` before the title, and its footer takes the box's last rows under content that fills the rest | Esc dismisses; a press on a sheet's `[dismissLabel]` dismisses as Esc does. A head note is drawn muted on the title's row against its right end, followed by `[dismissLabel]` while the close control is on and the box is not a sheet; a press on it dismisses as Esc does. A footer note takes a row of its own at the bottom of the box, muted | | Drawer | a box against its side, the screen's height; its footer as a dialog's | Esc dismisses | | Busy | a spinner and its label while active | — | -| Table | a header (set apart by its role: the terminal reads no table colour, so `color.table.header` and `color.table.headerRule` are not read and no rule is drawn under it) and keyed rows, `*` on selected rows, `>` on the cursor; with a select column a five-cell gutter, `[x]` or `[ ]` per row in place of the `*`, under a header box `[x]`, `[-]` or `[ ]` — a click on a row's box toggles the row as Ctrl+click does, and on the header box is Ctrl+A; a toned row's cells draw in the tone's style, keeping any inverse; the layout solver never squeezes a column below its header's width (a fixed column below its own width), and the columns past the table's edge are cut; a stretch column starts from its content and gives in the contract's four steps (`layout::planColumns`), in cells, with a 2-cell gutter and 1-cell gaps, a floor of `min(header, 4)` for a column that may `shrink`; the least width of a text cell in a wrapping column is its widest word and that of any other cell its natural width, so a text inside a container cell is never narrowed; a row's cells keep their own height and sit at its top, centre (rounded down) or bottom by their column's `valign`; a text cell cut at its column's width draws an ellipsis in its last cell, on each of its lines (spans too), because the terminal cannot wrap (a mono text outside a table, too); in a column that does not wrap (`wrap: false`) the spans share one line; a text, a badge, a check box or a push button is drawn at its natural width at its column's start, centre or end by the column's `align`, and the header's label with it; a text input keeps its text at the start, since `core::tui::InputField` has no alignment; the sorted column's label is followed by ` ▲` or ` ▼`, and a sortable column's header keeps room for it; a heading row is one cell across every column and their gaps, with nothing in its gutter, and widens no column; a hidden cell widens no column either; a spanning cell (`setRowSpans`) is drawn once, in its column over the lines of the rows it covers, placed down them by the column's `valign` (the centre rounded down), and every line of the span, covered rows' included, is drawn in the origin row's style (tone, selection, inverse), the rest of the covered rows in their own; `TableImpl` places a spanning cell itself, over the union of the covered rows' areas: a view is clipped to its parent's area, so the table lifts the cell's view out of its row into its own while the span holds (its tone, still its origin row's), and returns it when the span goes; the lifted cell is left out of the origin row's natural height and placement, and the table works out which cells span and which are covered from the rows' order at every frame, also before the layout that sizes it (a table holding spans is planned when the screen is fitted), so the frame that lifts a cell is already laid out with the shorter row; a table with no span does no such work; the covered cells widen no column, and when the span's text has more lines than the rows it covers have, the last covered row grows by the shortfall; the table scrolls by row, so with the origin row above the top and covered rows shown the cell is clipped at the table's top edge and placed again within the covered lines still shown, its text showing in the first of them; the cursor, `*` and `[x]` stay per row, and a click on a line in a spanning cell's column acts on its origin row, the hit-test taking the column's x as well as the line and covering the whole height of the rows the span covers, not only the lines its content is drawn on (a centred one-line cell leaves blank covered lines, and a click on one is a click on the span) | arrows, Space selects or toggles, Shift+Up and Shift+Down select a range from the anchor, Ctrl+A selects every row or clears them (Multiple), Enter activates; a click selects only its row, Ctrl+click toggles it and Shift+click selects a range where the emulator passes the modifier on (`clickWith`), and a plain double click activates; a click on a sortable column's header asks to sort by it (the header takes no keyboard focus); the cursor passes over a heading row, a click on one does nothing, and Ctrl+A, a range and the header box leave it out | +| Table | a header (set apart by its role: the terminal reads no table colour, so `color.table.header` and `color.table.headerRule` are not read and no rule is drawn under it) and keyed rows, `*` on selected rows, `>` on the cursor; a row's marks (`setRowMarks`): an unmatched row's cells draw dim, and a busy row shows `…` and a locked one `#` in gutter cells of their own after `*` and `>`, the glyph and a gap so the ellipsis is not read as a cut, which the gutter gains with the first busy or locked row and keeps, so the columns do not move as rows come and go busy; the marks' tooltip, or without one "Saving this row" or "Locked by another user", is the row's hover text over its own tooltip; with a select column a five-cell gutter, `[x]` or `[ ]` per row in place of the `*`, under a header box `[x]`, `[-]` or `[ ]` — a click on a row's box toggles the row as Ctrl+click does, and on the header box is Ctrl+A; a toned row's cells draw in the tone's style, keeping any inverse; the layout solver never squeezes a column below its header's width (a fixed column below its own width), and the columns past the table's edge are cut; a stretch column starts from its content and gives in the contract's four steps (`layout::planColumns`), in cells, with a 2-cell gutter and 1-cell gaps, a floor of `min(header, 4)` for a column that may `shrink`; the least width of a text cell in a wrapping column is its widest word and that of any other cell its natural width, so a text inside a container cell is never narrowed; a row's cells keep their own height and sit at its top, centre (rounded down) or bottom by their column's `valign`; a text cell cut at its column's width draws an ellipsis in its last cell, on each of its lines (spans too), because the terminal cannot wrap (a mono text outside a table, too); in a column that does not wrap (`wrap: false`) the spans share one line; a text, a badge, a check box or a push button is drawn at its natural width at its column's start, centre or end by the column's `align`, and the header's label with it; a text input keeps its text at the start, since `core::tui::InputField` has no alignment; each header of the sort chain is followed by its mark (`ui::sortMarkText`: ` ▲` or ` ▼`, and its place with two or more keys, ` ▲2`), and a sortable column's header keeps room for a one-key mark; a filterable column's header ends in its filter button, `▿`, `▾` while `setFiltered` names it; groups (`setColumnGroups`) draw a line above the headers, each label over its visible places and ending in its own filter button; with menus the header line keeps its last two cells for a gap and `⋯`, which opens the table's menu, so no column's header or filter button lies under it; a menu is a list below the header, as a button-style menu's is, and takes the keys; no drag or resize handle is drawn; a heading row is one cell across every column and their gaps, with nothing in its gutter, and widens no column; a hidden cell widens no column either; a spanning cell (`setRowSpans`) is drawn once, in its column over the lines of the rows it covers, placed down them by the column's `valign` (the centre rounded down), and every line of the span, covered rows' included, is drawn in the origin row's style (tone, selection, inverse), the rest of the covered rows in their own; `TableImpl` places a spanning cell itself, over the union of the covered rows' areas: a view is clipped to its parent's area, so the table lifts the cell's view out of its row into its own while the span holds (its tone, still its origin row's), and returns it when the span goes; the lifted cell is left out of the origin row's natural height and placement, and the table works out which cells span and which are covered from the rows' order at every frame, also before the layout that sizes it (a table holding spans is planned when the screen is fitted), so the frame that lifts a cell is already laid out with the shorter row; a table with no span does no such work; the covered cells widen no column, and when the span's text has more lines than the rows it covers have, the last covered row grows by the shortfall; the table scrolls by row, so with the origin row above the top and covered rows shown the cell is clipped at the table's top edge and placed again within the covered lines still shown, its text showing in the first of them; the cursor, `*` and `[x]` stay per row, and a click on a line in a spanning cell's column acts on its origin row, the hit-test taking the column's x as well as the line and covering the whole height of the rows the span covers, not only the lines its content is drawn on (a centred one-line cell leaves blank covered lines, and a click on one is a click on the span); a table over a `TableSource` (one the mount gives a horizontal-range handler; a long table over `rows` is told its realized window too, and is no source) draws what the mount realizes: it scrolls over every row of the view, one line each, and draws each realized row on the line of its view index (`setRowIndex`), a line whose row is not realized blank; each cell in the column `setCellColumn` gave it, a pooled cell nowhere; once the mount lays the columns out (`setColumnWindow`) the header and the cells show the window's columns only, at the mount's offsets and widths in cells (`tableMeasure`: a unit and a monospace character are a cell, a column's padding is its gap, which is the last cell of each, a content column starts at twelve and a `shrink` column goes down to four cells and its gap); the table reports its headers' and shown cells' natural and least widths, each with the gap, when one grew (`setOnColumnMeasured`), and the mount fits the stretch columns to the viewport by the contract's four steps, a viewport that is the table's width less the gutter and the menu's room, the pinned ones at the leading edge and the rest scrolling under them; it reports the columns, then the rows, in view before the next frame's layout when a frame found them changed (`fit` makes the reports, outside the drawing), and at once for the wheel; an `Unloaded` cell draws `···` and a `Failed` one `!` in its column's alignment in place of its content, neither widening the column; the status line (`setStatus`), while shown, is the last line: the counts, the state, `[Retry]` while the state offers it, and the message at the trailing edge | arrows, Space selects or toggles, Shift+Up and Shift+Down select a range from the anchor, Ctrl+A selects every row or clears them (Multiple), Enter activates; a click selects only its row, Ctrl+click toggles it and Shift+click selects a range where the emulator passes the modifier on (`clickWith`), and a plain double click activates; a click on a sortable column's header asks to sort by it, `Shift` with Shift held, and a click on a filter button presses it; a right click on a header opens its menu (`WidgetBase::contextPress`, the right button's press), and one on another header while a menu is open closes it and opens that header's; while a header can act (a column sorts, or the table has menus or moves columns), Up on the first row (the first view row over a source) focuses the header of the sort chain's first key, or the first visible column, and on it Left and Right move along the visible columns, Enter and Space sort, Shift+Enter and Shift+Space extend, Ctrl+Shift+Left and Ctrl+Shift+Right report a move one place over, Shift+F10 or the menu key opens its menu, and Down returns to the rows; Ctrl+C asks to copy (`setOnCopy`) and `copyText` writes an OSC 52 sequence to the terminal; the cursor passes over a heading row, a click on one does nothing, and Ctrl+A, a range and the header box leave it out; over a `TableSource` the arrows, Home, End, PageUp, PageDown, Ctrl+Home and Ctrl+End move the mount's focused cell (`setOnFocusMove`), which the view keeps in view, so Left and Right scroll sideways, and Space and Enter act on the focused row; Shift+Up and Shift+Down move it and, in Multiple mode, select from the anchor (the row last clicked or toggled, or the one the focus left) through `setOnSelectRange`, as a Shift-click does to the row clicked, and Ctrl+A and the header box select every row of the view through it (the mount refuses a range past `maxRangeRows`), so no range runs over the realized rows alone; a click does not move the mount's focused cell; a click on `[Retry]` calls `setOnRetry`'s handler | | DateTimeInput | `YYYY-MM-DD[ HH:MM]` in the display zone, or its pattern, as wide as the pattern writes, and a field too narrow for its text is cut with an ellipsis before the marks while it has no focus, as a text input is; the stepping keys work on the parsed instant | typing; Up/Down step | | Slider | `[====\|----] value` | Left, Right, Home, End, press and drag on the track | | FilePicker | a path field, prompted `Open: ` or `Save: ` | typing; Enter | diff --git a/docs/spec/ui/backend_contract.md b/docs/spec/ui/backend_contract.md index 03590f285..a0a7df93b 100644 --- a/docs/spec/ui/backend_contract.md +++ b/docs/spec/ui/backend_contract.md @@ -45,7 +45,9 @@ What the mount does with these widgets is [`view_tree.md`](view_tree.md). setters (`setReadOnly`, `setRequired`, `setErrors`, `setStale`) only to change them; it calls a dialog's `setOpen` at mount whatever the value, `false` included. - **Focus.** `focus()` moves keyboard focus to the widget. The mount calls it on the first - `autofocus` widget in document order once a mount completes ([view tree](view_tree.md#focus)). + `autofocus` widget in document order once a mount completes ([view tree](view_tree.md#focus)), and on the next or + the previous control of the focus chain when a table's key handler says focus leaves it (`KeyOutcome::FocusNext`, + `FocusPrevious`; [view tree](view_tree.md#the-focus-chain)). - **Hover.** `setOnHover(onHover)` calls `onHover` each time the pointer comes to rest over the widget. The default does nothing, so a backend without a pointer conforms. Hovering is a hint, such as a prefetch, never something a widget relies on. Qt Quick reports it through `MorphWidget`'s `HoverHandler` when a handler is set. @@ -54,7 +56,8 @@ What the mount does with these widgets is [`view_tree.md`](view_tree.md). is a hint, used to fetch again options whose fetch failed. Qt Quick reports the combo box's popup opening; the TUI reports the list opening, or the attempt to open it when there are no options. - **Chords.** `setKeys(chords, onChord)` declares the chords a widget handles while focus is inside - it, and `onChord` receives the chord pressed. A chord pressed while focus is inside several + it, and `onChord` receives the chord pressed. A widget that declares `Tab` or `Shift+Tab` receives them instead + of focus moving: a grid walks its cells with them, and moves focus along the chain itself at its ends. A chord pressed while focus is inside several widgets that declare it goes to the innermost of them only, and a chord pressed inside a widget that takes no input (below) goes to none. A key pressed with focus on a widget goes, the same on every backend: 1. to a chord the focused widget declares itself, since declaring it on that very node is how an author says the @@ -309,7 +312,21 @@ stretch columns share by weight whatever they hold, a deliberate behaviour chang content can no longer be said, and a literal `percent` table column stays refused. The terminal cannot wrap, so a text cell its column cuts ends in an ellipsis in its last cell, on each line (on one joined line in a column that does not wrap); its least width is the widest word of a text cell in a wrapping column and the natural width of any other cell, so the -terminal never narrows a container's text, which Qt Quick does. A table whose columns are wider than the +terminal never narrows a container's text, which Qt Quick does. A table over a `TableSource` realizes only the rows and +columns in or near view, and the mount lays its columns out (`setColumnWindow`) by the same rules, in the backend's +measure (`tableMeasure`) with each column's padding in every width. A fixed column keeps its width, as does a column +whose width the user set; a content column is as wide as the larger of its header and its widest cell measured (the backend's estimate until either is measured), which only grows once measured. A stretch column's +`n` is the larger of its header and the widest cell measured so far: a windowed table cannot see the rows it has not +realized, so measures only accumulate, and a change of the shown rows can only grow `n`, which is the source-path reading +of "the widths follow the shown rows". Its `l` is `n` in a column that does not wrap and, in one that wraps, the larger +of its header and the widest least width a cell reported (`ColumnMeasure::least`); its `f` is its header, or with +`shrink` `tableMeasure().shrinkFloor` (8 units on Qt Quick, 4 cells and the gap on the terminal), never above its +header. `L` is the horizontal viewport the backend reports (`setOnHorizontalRange`, which leaves out the select column, +the row mark and the menu's room) less the widths of the other visible columns. The mount computes the stretch widths +whenever `L` or a measure changes, so they narrow as well as widen; a table whose viewport is not reported yet keeps a +stretch column at the estimate. A backend reports each column's header (again when a sort mark or a font changes it) +and each shown cell's natural and least width through `setOnColumnMeasured`; the mount keeps the largest of each. A +table whose columns are wider than the table scrolls sideways on Qt Quick, with a bar that shows while it can; on the terminal the columns past its edge are cut and cannot be reached. **Content that does not fit.** A container does not shrink its children on its own: whether a text elides or a row @@ -389,7 +406,32 @@ child does. Across, a child its maximum stops from filling is placed by its alig | `DialogWidget` | `setOpen`, `setTitle`, `setDescription` (a line under the title in the head, not scrolled with the content, and the overlay's accessible description), `footer()`, `setSheet`, `setDismissLabel`, `setHeadNote` (a muted note on the title's row, trailing), `setFooterNote` (a muted note leading in the footer's row; the footer shows while it is not empty), `setCloseButton` (a dismiss control on the title's row, labelled by `setDismissLabel`; a `DrawerWidget` has the same four) (called only when the document binds or sets them) | `setOnDismiss` (Esc on the TUI), for an open dialog, which the dismissal closes first | | `ToastWidget` | `show(text, tone)` (one call: shows the message and restarts the dismiss interval regardless of whether the toast is already on-screen) | — | | `BusyWidget` | `setActive`, `setLabel` | — | -| `TableWidget` | `setColumns(vector)`, `setSelectionMode`, `setRowKey(row, key)`, `setRowTone(row, optional)` (after `setRowKey`, and on every change), `setSelection(keys)`, `setSelectColumn(bool)`, `setSelectAllLabel(text)`, `setRowLabel(row, text)`, `setRowHeading(row)` (once, after `setRowKey`: the row is never marked, reported or activated), `setRowSpans(row, vector)` (after `setRowKey`, and on every change; the spans are resolved ([Row spans](view_tree.md#row-spans)), so once a change settles a backend is told none out of range, overlapping, past the last row or on a heading; while it settles it may see one, so it derives coverage at layout or paint time from the rows' current order, never at this call, and clips a span that runs past its last row or onto a heading; a call with an empty list clears the row's), `setExistingKeys(keys)` (every key, in row order, above the virtualization threshold), `setSort(optional)` (marks the column's header with the direction, or none; only for a table with a sortable column) | `setOnSelectionChange(keys, SelectionChange)`, `setOnActivate(Key)` (Enter or a double click), `setOnSort(column)` (a click on a sortable column's header, or Enter or Space on it where the header takes focus; the index counts the columns `setColumns` gave, which the select column is not one of; another header reports nothing). The backend never reorders rows for a sort: it shows `setSort`, and what a click means is the lowering's | +| `TableWidget` | `setColumns(vector)`, `setSelectionMode`, `setRowKey(row, key)`, `setRowTone(row, optional)` (after `setRowKey`, and on every change), `setRowMarks(row, RowMarks)` (after `setRowKey` for a row whose look carries marks, and on every change: `unmatched` draws the row muted, `busy` with the theme's busy mark, `locked` with its locked mark, and `tooltip` is the row's tooltip, over its own; a busy or locked row whose `tooltip` is empty says why on hover, "Saving this row" or "Locked by another user"; `RowMarks{}` draws an unmarked row; default: ignored), `setSelection(keys)`, `setSelectColumn(bool)`, `setSelectAllLabel(text)`, `setRowLabel(row, text)`, `setRowHeading(row)` (once, after `setRowKey`: the row is never marked, reported or activated), `setRowSpans(row, vector)` (after `setRowKey`, and on every change; the spans are resolved ([Row spans](view_tree.md#row-spans)), so once a change settles a backend is told none out of range, overlapping, past the last row or on a heading; while it settles it may see one, so it derives coverage at layout or paint time from the rows' current order, never at this call, and clips a span that runs past its last row or onto a heading; a call with an empty list clears the row's), `setExistingKeys(keys)` (every key, in row order, above the virtualization threshold), `setSort(vector)` (the sort chain, most significant first: each key's header draws `sortMarkText(direction, place, count)` after its label — ` ▲` or ` ▼`, and with two or more keys its place from 1, ` ▲2` — and carries `sortDescription` as its accessible description, `sorted ascending` or, with two or more keys, `sorted ascending, key 2 of 3`; a header not in the chain draws no mark and has no description; only for a table with a sortable column), `setMenu(entries, onChoose)` (only for a table with menus: a header's menu opens on a right click on it, or `Shift+F10` or the context-menu key with it focused, and the table's menu, `entries(nullopt)`, from a `⋯` at the header row's trailing end named `Table options`, which keeps room of its own so that it covers no header or filter button; a menu opened from the keyboard is used from the keyboard, and Escape closes it however it was opened; the entries are asked for each time a menu opens; default: no menus), `setCellMenu(entries(row, column), chosen(row, column, path))` (pure: a right click, a long press, or `Shift+F10` or the context-menu key on the focused cell opens the cell's menu at the cell; first the row becomes the selection alone, reported as `Replace`, when it is not selected, a selected row keeping the selection; then `entries` is asked, which focuses the cell (`setFocusCell`) when it is not focused, and the menu shows what it returned; a choice calls `chosen` with the cell and the entry's path, never for a separator, a heading, a disabled entry or one with a submenu; while the table has the focus, a key it does not take itself that is one of the chords `setCellMenuKeys(chords)` gave asks for the focused cell's entries and is matched against their `keys` at every level, the first enabled entry without a submenu whose chord it is running as if chosen and the key stopping there; any other key asks for nothing; default for `setCellMenuKeys`: ignored, and then no key runs an entry), `setVisibleColumns(columns)` (the arrangement's visible columns in layout order, for a table over a `TableSource`, once built and on every change; the places a move and a group count in; untold, every column in its own order; default: ignored), `setFiltered(columns)` (each filterable column's header draws a filter button, filled for these columns, whose headers are then named `{label}, filtered`; default: ignored), `setColumnGroups(vector)` (a row over the headers: each group's label over the visible places `first` to `first + count - 1`, with its own filter button, filled while `filtered`; empty draws no row; default: ignored), `setStatus(TableStatus)` (the status line: counts, a failed fetch's or level's state with Retry when it offers it, what stands while its cause lasts (`standing`) with its entries, and the latest message with its entries; each entry is drawn as a button with its label, which `setOnStatusEntry` reports by id; one not `shown` takes no space; default: ignored), `setSelectionView(except)` (every row but these keys is marked, rows the backend does not hold included, until the next `setSelection`; in that state a `Ctrl`+click reports `Extend` with the keys now marked among the rows the backend holds, and a plain click `Replace`; default: ignored, which only a backend without `setOnSelectAll` may keep), `setCellLoad(row, column, CellLoad)` (after `setRowKey` and on every change, for a table over a `TableSource`: `Unloaded` a placeholder of a fixed width in the column's alignment, `Failed` an error mark of that width, over the cell's content, neither widening the column; default: ignored), `setCellAccent(row, column, CellAccent)` (after `setRowKey`, on every change, and whenever a cell is attached to a row at a column, for a table over a `TableSource`: `tone` tints the cell with the theme's tone surface under its selection and focus marks; `tooltip` shows on hover after the theme's delay and on keyboard focus at once, is the cell's accessible description and draws the theme's "more here" mark; `invalid` draws the theme's error mark in place of the cell's text; a cell no call names has no accent; default: ignored); a column's `unit` (in `setColumns`) is drawn after its label, as `headerText` writes it ("Mass [kg]") or on a second, muted line, and the header's accessible name is `headerAccessibleName` ("Mass, kg"); for a table over a `TableSource`, each default to nothing: `setColumnWindow(columns, offsets, widths, totalWidth, pinned)` (the columns the mount realizes, pinned first, with their offsets and widths and the full width; the header shows these only), `setHorizontalOffset(x)` (anchoring: the scroll moves without a report), `setFocusCell(viewRow, column)`, `setCounts(optional rows, columns)` (rows nothing under a lower bound), `scrollToRow(viewRow)`, `setHighlightedRow(optional viewRow)`, `setCellColumn(row, cell, optional column)` (places a cell; nothing pools it: not drawn, no place, its column blank; a backend places cells by this call, never by their order in the row), `setRowIndex(row, viewRow)` (a realized row's view index, once it is realized and whenever it changes; the focused row stays realized outside `setRealizedWindow`'s range, so a backend places each row by its index; `setRealizedWindow` names the contiguous range only; it is told to every source table after each pass, one that realizes every row, a document's `rows` table below its threshold, as `(0, count, count)`, since a backend takes the view's count from it), `tableMeasure()` (the backend's horizontal measure: one `Sizing` unit, one monospace character, a content column's starting width, the padding a column takes beyond its content, added to a fixed or user width, and the narrowest a `shrink` column goes, padding included, in the measure its scroll, viewport, measured widths and `setColumnWindow` use; default 1, 1, 100, 0, 8) | `setOnSelectionChange(keys, SelectionChange)`, `setOnActivate(Key)` (Enter or a double click), `setOnSort(column, HeaderClick)` (a click on a sortable column's header, or Enter or Space on it where the header takes focus, `Plain`; a `Shift`+click, `Shift+Enter` or `Shift+Space`, `Shift`; the index counts the columns `setColumns` gave, which the select column is not one of; another header reports nothing), `setOnColumnMove(column, position)` (dragging a header onto another, or `Ctrl+Shift+Left` and `Ctrl+Shift+Right` on a focused header, with the column's new visible place; a backend that draws no drag reports the keys only; default: ignored), `setOnColumnResize(column, optional units)` (only for a table whose columns resize: dragging a header's trailing edge, its width in `Sizing` units, and a double click on the edge none; a backend that draws no edge ignores it), `setOnFilter(column)` (a filterable column's filter button), `setOnGroupFilter(group)` (a group's filter button), `setOnCopy()` (`Ctrl+C` on the focused table), each defaulting to nothing, `setOnRetry()` (the status line's Retry; default: ignored), `setOnStatusEntry(id)` (a status line entry chosen, by its id; default: ignored), and for a `TableSource` table `setOnHorizontalRange(scrollX, viewport)`, `setOnColumnMeasured(column, ColumnMeasure{header, natural, least})`, `setOnFocusMove(FocusMove)`, `setOnSelectRange(anchorRow, focusRow, SelectionChange)`; and for an editable table, +each defaulting to nothing: `setOnText(text)` (printable text typed while a cell has focus and no editor is open), +`setOnCellClick(viewRow, column, doubleClick)` (a click on a cell, `false`; the second click of a double click calls it +again with `true`), `setOnFocusOut()` (focus moved to a widget outside the table, its cell editor and its popups: focus in a popup a +widget inside the table opened, a dropdown's list or a date picker, is not focus out, though the popup is drawn +outside the table), +`setCellEditor(row, column, editor)` (draws `editor`, a child of `row`, over the cell's area in place of its content, +and null draws the cell again; an editor that holds the focus when it closes gives it back to the table), `setCellMarks(row, column, CellMarks)` (after `setRowKey`, on every change, and +whenever a cell is attached to a row at a column: `readOnly` the theme's read-only cell surface, `modified` its +modified mark, `error` its error mark, `stale` and `muted` the stale and muted looks; a cell no call names has none) +and `setRowModified(row, bool)` (the row header's modified mark), `setCellSelection(optional>)` +(`{firstRow, rowCount, firstPosition, positionCount}` in view rows and visible places, the places of the layout and +not indices into the columns; empty draws none; it never calls the handler) and `setOnCellSelect(anchorRow, +anchorPosition, focusRow, focusPosition)` (the table selects cells: it draws no row selection and reports no +`onSelectionChange`; a drag from cell to cell, a `Shift`+click from the focused cell, a click on a row's header (anchor +`(row, 0)`, focus `(row, last position)`) and a column header's selection gesture (anchor `(0, position)`, focus +`(last row, position)`) report the rectangle; `Shift` with an arrow and `Ctrl+A` are the table's own chords, declared +with `setKeys`). The terminal marks the rows a rectangle spans with `*` in the gutter, as it marks selected rows, and +draws no column of it; a click in a row's gutter selects the row's cells and a `Ctrl`+click on a header the column's. +Qt Quick draws the rectangle over the cells it spans and gives each row a header, a leading strip before the first +column, whose click selects the row's cells; a `Ctrl`+click on a header selects the column's and does not sort, while +a plain click and a `Shift`+click sort as on any table. Its drag selection is a mouse's: a touch drag scrolls the rows, +so a grid past the window threshold still scrolls under a finger. The terminal draws an error mark `!` and a +modified one `+` at a cell's trailing edge, a modified row `+` in its selection mark's cell while it is not selected, +an open editor in its cell's slot, and reports focus leaving before the frame after the one that found it outside. +The backend never reorders rows for a sort: it shows `setSort`, and what a click means is the lowering's | | `DateTimeInputWidget` | `setValue(optional)` (`nullopt` or an empty `Timestamp` shows an empty field), `setCaption(label, shown)`; the calendar opens under the field, at the field's start when it fits in the window, else ending at the field's end, and always inside the window | `setOnChange(optional)` (`nullopt` for a cleared field) | | `SliderWidget` | `setRange(minimum, maximum, step)`, `setValue` | `setOnChange(value)`, `setOnCommit(value)` (a finished move: a release after a drag, a key step, or a wheel step) | | `FilePickerWidget` | `setPath` | `setOnPicked(path)` | @@ -414,6 +456,18 @@ recording backend records `size`, `margins`, `scale` and `displayed` on a `Page` `PageRegion`, and logs a change of the derived `scale`, `displayed`, `rect` and `overflow` (`setPageAvailableWidth`, `setRegionContentHeight`). +**The clipboard.** `IViewBackend::copyText(text)` puts text on the system clipboard and says whether it did: Qt Quick +through `QGuiApplication::clipboard()`, the terminal through an OSC 52 sequence written to its output (whether the +terminal honours it cannot be known, so it answers true), and `RecordingBackend` by recording it for `clipboardText()`. +The default answers false: a backend without a clipboard copies nothing. `IViewBackend::pasteText()` reads the +clipboard's text, what a grid's `Ctrl+V` pastes: Qt Quick from `QGuiApplication::clipboard()`, `RecordingBackend` the +text `copyText` last recorded, nothing while `setClipboard(false)`; the default, which the terminal keeps, answers +nothing. + +**Column indices.** The `column` of every `TableWidget` call and handler above is an index into the columns +`setColumns` gave, which hold every column, hidden ones included, and do not change when the layout does. Only a move's +`position` and a group's `first` are visible places of the arrangement. + **The width class.** `IViewBackend::widthClass()` is the class of the surface the backend draws on, now, and `setOnWidthClass(listener)` registers the one listener told of each later change, on the owner and outside any layout pass; empty clears it. Registering does not call the listener: the caller reads `widthClass()` for the current class, @@ -457,6 +511,11 @@ the list it refers to may arrive in either order. | Ctrl+A | goes on outwards | selects every row; with every row selected already, clears them | `Extend` | | Enter | activates the current row | activates the current row | — | + A table given `setOnSelectAll` calls it for Ctrl+A, and for its header box, in place of selecting and reporting: + the caller selects its whole view, rows the backend does not hold included, and sets the selection back. The + recording, terminal and Qt Quick backends take it, over a `TableSource` too, where it stands in for the range + through `setOnSelectRange`; a backend that does not, selects as the table above says. + A **select column** (`setSelectColumn(true)`) draws the same selection as a leading column of check boxes. A row's box is checked while the row is selected, and toggling it is a Ctrl-click on the row. The header box is checked while every row shown is selected, partly checked while some are, clear while none are, and disabled while the @@ -558,7 +617,7 @@ The headless reference backend and the test double for everything above the cont `axis` (Scroll); `tabs`, `selected`, `barShown` (Tabs); `open`, `title`, `description` (Dialog); `active`, `label` (Busy); `columns` (each `label:width`, then `;align=` and `;valign=` for a place other than the default), `selectionMode`, `selection` (the requested keys it marks, in the order requested), - `rowKey`, and `rowSpans` on a row (`column:rows` pairs joined by commas in column order, as `0:2,3:2`, `none` after a call with an empty list, and absent until the first call; Table); `mode`, `offset`, `value`, `pattern` (DateTimeInput); `range`, `value` + `rowKey`, and `rowSpans` on a row (`column:rows` pairs joined by commas in column order, as `0:2,3:2`, a span across columns as `column:rowsxcolumns`, as `0:2x3`, `none` after a call with an empty list, and absent until the first call; Table), `summary` (`true`) on a summary row, and `bands` on the table (each run `level:label|unit@first+count`, `;pinned` for a pinned run, `|unit` only with a unit); `mode`, `offset`, `value`, `pattern` (DateTimeInput); `range`, `value` (Slider); `mode`, `path` (FilePicker); `tone`, `text`, `spans`, `actionLabel`, `dismissible` (Banner); `tone`, `text`, `icon`, `style`, and `removable` (the remove control's name) of a removable one (Badge); `value`, `label` (Progress); `steps`, `current` (Steps); `items` `captions` and `captionWidth` (KeyValue); `title`, `text`, `icon`, `actionLabel` (EmptyState); `side`, `open`, `title`, `description` (Drawer); @@ -610,8 +669,14 @@ The headless reference backend and the test double for everything above the cont collapsible section), `dismiss` (a dialog, a drawer, a dismissible banner, or a removable badge, whose `onRemove` it runs), `resize(id, sizes)`, `dropFiles(id, paths)` (true when the zone took the drop), `selectRows` (reported as `Replace`, its last key the anchor), `clickRow(id, key, RowClick)` (a click with its modifiers, as the selection model has it), - `clickHeader(id, column)` (a sortable column's index reaches `onSort`; another header does nothing, as a - user's click on it does), `activateRow`, + `clickHeader(id, column, click = Plain)` (a sortable column's index reaches `onSort` with `click`; another + header does nothing, as a user's click on it does), `menuOf(id, optional column)` (a header's menu, or the + table's for none, as a user opening it sees it), `chooseMenu(id, optional column, labels)` (an entry by its labels + from the top, resolved to its path; nothing for a disabled entry, one inside a disabled entry or one with a + submenu), `moveColumn(id, column, position)` (nothing for the place the column holds or one past the last visible + column), `resizeColumn(id, column, + optional units)`, `clickFilter(id, column)` (a filterable column's), `clickGroupFilter(id, group)`, `pressCopy(id)` + (as `Ctrl+C`, which `press` also takes on a table that copies), `activateRow`, `setDateTime`, `slide`, `pick` and `drag`. A helper first changes what the native widget would change by itself — the field's text and cursor, the box's check mark, the marked option or rows, the highlighted tab, the collapsed or open state, a dismissed dialog's or drawer's `open`, the @@ -634,7 +699,8 @@ The headless reference backend and the test double for everything above the cont destroys `id` stops the key there. `press` returns whether any step took the key. It changes no recorded focus. - A helper used on a kind it does not apply to throws `std::logic_error`, and so does an action - no user could take: choosing a key the Select does not offer, collapsing a panel that is not + no user could take: a header helper given a column whose header is not drawn (one the visible columns leave + out), a menu label its level does not have, a group the table does not draw, choosing a key the Select does not offer, collapsing a panel that is not collapsible, selecting a key with no row, a row twice, any row in a `None` table or more than one in a `Single` one, activating a key with no row, dragging a widget onto itself, clicking a banner or empty state that shows no action button, dismissing a banner that is not @@ -645,6 +711,13 @@ The headless reference backend and the test double for everything above the cont nothing here, so a drop that lands on a mounted target without `accepts` shows the mount's accept-everything default at work. +- **Configuring a table.** A table records `sort` as its chain (`0:Ascending,2:Descending`, `none` when empty), + `filtered` as its columns (`[0,2]`) and `columnGroups` as `label:first+count` (`[Company:0+3]`, with + `;filtered=true` for a filtered group, and `:`, `+` and `;` in a label escaped); a filterable column's entry in + `columns` carries `;filterable=true`; `headerText(id, column)`, `headerName(id, column)` and + `headerDescription(id, column)` read a header as a terminal or a screen reader would, and `clipboardText()` is the + last text `copyText` was given, empty before any. + - **Text cursor.** A TextInput keeps a cursor, a byte offset into its text, read with `cursor(id)`. `edit` and `submit` leave it at the end of the new text, `moveCursor(id, position)` moves it (clamped to the text), `setCursor` moves it the same way without a log entry, and to the start of a code point for an offset inside one (`snapToCodePointStart`, which every backend places a cursor through), and `revealCursor` does nothing, `setText` with the text the field shows leaves it alone, and `setText` with @@ -751,7 +824,7 @@ after it; its reading operations report what the widget shows now. | `dismiss(dialog)` | Dismisses a dialog or drawer (Esc on the TUI), or a dismissible banner; removes a removable badge with its remove control | | `selectRows(table, rows)` | Selects rows by position, in the order the user picks them — at least one, and only one in a `Single` table — so the user's selection is exactly those rows | | `clickRow(table, row, click)` | Clicks a row by position as a user would, plain (`RowClick::Only`), with Ctrl (`Toggle`) or with Shift (`Range`) | -| `clickHeader(table, column)` | Clicks a column's header as a user would | +| `clickHeader(table, column, click)` | Clicks a column's header as a user would, with Shift held for `HeaderClick::Shift`; `click` defaults to `Plain` | | `selectedRows(table)` | The positions of the rows the table shows as selected, ascending | | `moveCursor(field, position)` | Moves a text field's cursor as the arrow keys or a click would, without changing the text | | `cursorOf(field)` | Where a text field's cursor is, as a byte offset into its text | @@ -762,6 +835,18 @@ after it; its reading operations report what the widget shows now. | `dropFiles(zone, paths)` | Drops files from the operating system onto a drop zone | | `boundsOf(widget)` | Where the widget is drawn, in the backend's units, for the layout cases; none by default, for a probe that reads no geometry | | `textExtentOf(text)` | The box around the lines a Text draws, in the units `boundsOf` uses; none by default, and a layout case that reads it then fails as one that reads no bounds does | +| `headerMenu(table, column)` | Opens a header's menu, or the table's for none, as a user would, reads its top level's entries and closes it | +| `chooseHeaderMenuEntry(table, column, path)` | Opens a header's or the table's menu and chooses an entry by its path | +| `moveColumn(table, column, position)` | Moves a column as a user would: a header drag, or the keys on a focused header | +| `headerText(table, column)` | The text a header draws: its label and its sort mark | +| `headerName(table, column)` | A header's accessible name | +| `headerDescription(table, column)` | A header's accessible description | +| `pressFilter(table, column)` | Presses a filterable column's filter button | +| `pressGroupFilter(table, group)` | Presses a column group's filter button in the group row | +| `clipboardText()` | What `copyText` put on the clipboard, read back from where the backend wrote it | + +The operations from `headerMenu` on have default bodies that drive nothing and read nothing, as `descriptionOf` and +`boundsOf` have: a probe that keeps them fails the cases that use them. A case reaches widgets only through `Mounted::root()`, `childAt` and further roots it mounts, or through widgets it makes with `backend()` itself, so a probe needs no lookup by name. @@ -862,6 +947,20 @@ Each case is named by the rule it checks: 56. In that table, with the spanning column's cells placed at the top of their rows, a click in the spanning cell's column at the third row's line, below the cell's content, selects the first row's key: a click anywhere on the span's height is a click on the span. +57. A `Shift`-click on a sortable header reports `Shift`, and a plain click `Plain`. +58. With the chain `Mass` descending, `Name` ascending, `Site` ascending, the headers read `Name ▲2`, `Mass ▼1` and + `Site ▲3`, and `Name`'s description is `sorted ascending, key 2 of 3`; with `Name` descending alone it reads + `Name ▼`, described `sorted descending`, and `Mass` has no description. +59. A header's menu of `Sort ascending`, a separator and `Hide column` shows those three, and choosing `[2]` in column + 1's menu reports column 1 and the path `[2]`. +60. The table's menu is the menu with no column: choosing its first entry reports none and `[0]`. +61. Moving column 0 to place 1 reports `(0, 1)`. +62. With `filtered = {0}` over two filterable columns, the first header is named `Name, filtered` and the second + `Mass`. +63. `Ctrl+C` on a focused table reports a copy once. +64. `copyText("a\tb")` answers true, and the clipboard then reads `a\tb`. +65. Pressing the filter button of a filterable column reports that column once. +66. Pressing a column group's filter button reports the group once. ### What the probe cannot reach diff --git a/docs/spec/ui/document.md b/docs/spec/ui/document.md index 47e05b970..b286f0006 100644 --- a/docs/spec/ui/document.md +++ b/docs/spec/ui/document.md @@ -307,7 +307,7 @@ weight and face, so `{role: display, tone: err}` is a large red figure. | `dialog`, `drawer` | `open`, `gap` (the spacing step between several `children`, default 3, read once), `title`, `description` (a line in the head under the title, ruled off from the body, which does not scroll with the content and is the overlay's accessible description), `descriptionSpans` (the line as runs, as a `text`'s `spans`: a client that knows it draws them in place of `description`, and the accessible description is their characters joined), `showErrors`, `side`, `scope`, `children` ⓘ, `default` ⓘ, `cancel` ⓘ, `actions` ⓘ (parts `actionButton`, [The head](#the-head)), `onDismiss`; a dialog's `sheet` (a condition: while true the dialog is drawn as a sheet that fills the window, with a head of a dismiss control and the title centred on the sheet, ruled off from the body, the document choosing by the width class, as `{"fn": "eq", "args": [{"env": "widthClass"}, "compact"]}`) and `dismissLabel` (the dismiss control's label, default `Close`, translated with `t`; only with `sheet` or `closeButton`); `headNote` (a muted note on the title's row, against its trailing edge) and `footerNote` (a muted note leading in the footer's row, opposite the actions, which shows the footer while it is not empty), both expressions, empty showing none; `closeButton` (a condition: while true a dismiss control labelled `dismissLabel` is drawn on the title's row, against the trailing edge; a sheet's head holds one already, so it adds nothing while `sheet` holds); the dismiss control dismisses exactly as Escape does, and a drawer takes no `sheet` | `open`, `ready`, `submitted` | | `busy` | `active`, `label` | | | `forEach` | `rows` (required), `key` ⓘ, `axis`, `gap`, `wrap` (a literal boolean, default `false`; the rows continue on the next line when they do not fit; the loader refuses `true` where a literal `axis` is not `horizontal`, and a computed `axis` that is not horizontal at lowering is reported and the rows do not wrap), `divided` (as a column's, for a vertical `forEach`; the loader refuses it where a literal `axis` is `horizontal`), `scope`, `children` ⓘ | | -| `table` | `rows`, or `model` and `action` with `body` and `mode`; `key` ⓘ, `columns` (parts `{id, label, width, role ⓘ, align, valign, sortable, wrap, shrink, sortBy ⓘ, cell ⓘ}`, or an expression of `{id, label, align, valign}` records — `role` styles the column's default cell and has no other effect on one with its own `cell`; it takes a text's role names, and a literal one is checked the same way; a `mono` role also sets the width unit of the column's `fixed(n)`: n mono characters, plus the cell padding, with or without a `cell`, so a column of identifiers says `mono` to hold them whole; `wrap` (a literal boolean, default `true`) with `false` draws the column's text cells on one line, cut at the column's width with an ellipsis, such as a value with its unit; `shrink` (a literal flag, default off, for a column whose `width` stretches; on any other column it is reported once and ignored) lets the column go narrower than its header when the table is narrower than its columns need, down to a floor of 8 units, its header and cells then cut, where otherwise no column is narrower than its header and the table scrolls sideways, and makes it give up width before the other stretch columns (the two meanings are one flag; a column that may go under its header but keeps its content late has no spelling); a stretch `width` starts from the column's content (its header and its widest shown cell) and its weight shares only the width the content leaves, so proportions that ignore the content cannot be said, a literal `percent` column stays refused, and a width the user sets would be a fixed column; `align` (`start`, the default, `center`, `end`) places a text cell's or a text input's text, a badge, check box or push button cell, and the header label across the column, while a container cell fills it; `valign` (`start`, `center`, the default, `end`) places every cell down its row; both are literal names, and a computed column's place of no known name is reported once and takes the default), `valign` (the default of every column that gives none), `selectionMode`, `selection` (a list of row keys: bound, it is controlled, as a select's `selected` is; refused without a `selectionMode` of `single` or `multiple`, and on a model-backed table), `onSelectionChange` (after each user change, with `event` the new keys; the same rules), `selectColumn` (a literal flag, only with a literal `selectionMode: multiple`: the table draws its selection as a leading column of check boxes under a select-all box), `selectAllLabel` (the select-all box's accessible name, only with `selectColumn`; default `Select all`, translated with `t`), `rowLabel` ⓘ (each row's accessible name, which its box carries; default the row's key as text), `sort` (a list of keys `{"column": , "direction": "asc" or "desc"}`, most significant first, `[]` the source order: the table orders its rows by it; bound, it is controlled, as `selection` is, and unbound the table holds it from `[]`; a literal one names sortable columns, each once; a column's `sortable`, a literal flag that needs its `id`, makes a click on its header sort by it alone, ascending, or descending when it already is the first key ascending; its `sortBy`, only with `sortable`, is the value the rows order by, read per row as `key` is, default the row's field of the column's `id`), `onSortChange` (after a header click, with `event` the new sort; needs a sortable column), `pageSize` (a positive integer: the table shows one page of that many of its sorted rows; absent or `null`, every row; a literal below 1 is refused), `group` (a part `{by ⓘ, heading ⓘ}`: a heading row before each run of adjacent rows whose `by` values are equal, drawn from `heading` in a row scope whose `row` is the run's record `{key, count, first, last, items}` of the whole group; a heading spans every column, is never selected, marked or activated, and counts in no element value; with a sort, each group keeps its place and its rows are sorted within it, and a group split across pages gets its heading on both; refused on a model-backed table; a heading's key is reserved, `"\u001Fgroup:"` then the canonical JSON of its run's key, `":"` and its ordinal among the runs with that key, and a data row with a field `"\u001Fgroup"` is taken for a heading), `page` (the page shown, from 0, clamped to the last; absent or `null`, the first; needs `pageSize`; `pageSize` and `page` are refused on a model-backed table, whose engine pages), `filters` and `highlightKey` (a model-backed table's only), `rowTone` ⓘ, `rowSpans` ⓘ (each row's spans, read in the row scope: a list of `{column, rows}` records, `column` the id of a column and `rows` an integer from 1 counting the row itself, whose cell in that column covers the rows below; `null` or `[]` none; the cells it covers are not shown and their content is ignored, though a client that does not know the key draws them, so a document leaves them empty; a table that is sorted, or above its virtualization threshold, draws no spans, and a span that names no column, repeats a column of its row, runs past the last row of the page the table holds, runs over a group heading, or starts in a column an earlier span covers, is refused and reported, the cell then standing in its own row (the interpreter's reports carry a path; the mount's for a span past the last row, onto a covered column, or above the virtualization threshold are bare and name none, so look at the rows' order); a spanned table should not page, or should page by groups, since a page boundary through a span refuses it; [`view_tree.md`](view_tree.md#row-spans)), `onActivate` ⓘ, `empty` (nodes: shown instead of the table while `rows` is an empty list), `scope` | `selection`, `activeKey`, `sort`, `filters`, `viewCount` (the rows the table orders, every page), `sourceCount` (the rows `rows` gave), `selectedCount`, `pending`, `error`, `hoveredKey`, `page` (the page shown, clamped), `pageCount` (at least 1), `pageFirst` and `pageLast` (the 1-based positions of the page's first and last rows, both 0 when there are none; a table that does not page reads page 0 of 1 over every row) | +| `table` | `rows` (a list the table orders on the client: one of more than 20,000 rows, or of more than 1,000,000 cells, rows times the column parts, is still ordered and is reported once for the table, "table holds rows; a table over rows is ordered on the client up to 20,000 rows or 1,000,000 cells — serve it as a model's table"), with `status` and `persist` as a model-backed table takes them, except that its status line takes space only while it has a message unless `status` is given, and that one with no `id` keeps no state, a `persist` other than `false` on it being refused ("a table over `rows` needs an `id` to persist its arrangement"); or `model` and `table`, one of the model's tables (`Table.
` and `Table.
.describe` are in the catalog and belong to the alias's model type, else "the table `
` is not in the catalog"; `table` without `model`, and `table` with `action`, are refused), with `body` (the query's fixed part), `status` (a literal flag, default `true`: the table's status line takes space; `false` sends its messages to the host's notifications) and `persist` (a literal: `true`, the default, keeps the table's sort, filters and column layout in the session's table-state store under the screen's id, a name keeps them under that name, `false` keeps none; any other value is refused, "`persist` is a literal: true, false or a name"), `editMode` (`cell`, the default: each committed cell of an editable column is sent as its own edit; or `row`: a row's committed cells are collected while focus stays in the row and sent together when focus leaves it or on `Ctrl+Enter`; refused on a table that is not a model's table, "`editMode` chooses how a model's table commits its cells; this table is not a model's table", and any other value refused, "`editMode` is `cell` or `row`, not ``") and `retainChanged` (a literal flag, default `false`: a row an action of this session changed stays in the view while it no longer matches the filter, at its sorted place, drawn muted with the tooltip "This row no longer matches the filter"; the rows retained are the keys of the `ChangedRows` such an action returned for the table, at most 10,000, and an action whose rows would pass that adds none of them and says so in the status line, "The changed rows are not kept in view: a table keeps at most 10,000"; while they show, the status line stands with "3 rows shown that no longer match" and the entry "Show only matching rows", which drops them, as a change of the filter does, and ends a selection of the view; while such an action runs, the table holds back the refetches its record's change events cause, for at most the session's `retainHold` (2 s), and sends one when the action settles; retained rows are not part of the table's stored state); or `form` and `field`, a grid of a form ([`../table/editing.md`](../table/editing.md#a-grid-of-a-form)): `form` the id of a `form` node of the document and `field` the path of one of its lists of records, in place of `rows` (`form` with `rows` is refused, "a table takes `rows` or a `form`, not both"; a `form` that names no form node, or a `field` that names no list of records of the form's schema, is refused), each column part's `field` naming the member of the row type the column edits (one that names no member is refused when the document loads, "`` names no member of ``"), or an expression read in the row's scope (`row` the row's record) naming the member each row edits, so one column holds a choice in one row and an amount in the next (a name that is no member is reported once and leaves that cell read-only), with the overlays per row `decimals` (the entry places of the row's member, also its wire `dp`, as a form field's `decimals` overlay; an expression here, where a table over `rows` takes only a literal), `unit` (the unit the row's member is entered in, an id of its units, applied with the draft converted when the row's value of it first appears or changes, so a unit the user then picks in the editor stays), `readonly` (a condition: the row's cell is read-only), `options` (a list narrowing the options of the row's choice to those values) and `placeholder`, each an expression in the row's scope; `readonly`, `options`, `placeholder`, and `field` or `unit` as an expression, on a column of any other table are refused, "`` is a grid column's, read per row; this table is not a grid of a form", or its `value` (read with `row` the row's record) a display column the walk skips and no edit reaches (a part with neither is refused, "a grid's column edits the member its `field` names, or shows its `value`"; with no column parts, a column per member in schema order), with `onActivate` run with `event` the row's key on `Enter` or a double click on a read-only cell, `layout` arranging the columns and the walk following the visible ones in layout order, an edit column sorting by its header when its part says `sortable` and filtering as a table's column does (its filter button, its values, `onFiltersChange`, the table menu's "Clear all filters") unless it says `filterable: false`, a display column doing neither, and a cell menu of "Copy", "Copy with headers", "Filter by this value" and "Exclude this value", then "Revert cell" and "Revert row", then a separator and the `cellMenu` parts, with `enterMoves` (`down`, the default, `right` or `none`: where `Enter` goes after it commits a cell) and `walk` (`rows`, the default, or `columns`: the order `Tab` visits the editable cells in), `selectionMode` `cells`, the default and only mode of a grid (any other is refused, "a grid of a form selects cells: its `selectionMode` is `cells`"; `cells` on a model's table is refused, "`selectionMode` `cells` selects cells of a table held on the client; a model's table selects rows", and on a table over `rows`, "`selectionMode` `cells` is a grid's; this table is not a grid of a form"): a rectangle of cells extended with `Shift` and an arrow or a drag, the whole grid with `Ctrl+A`, a row's cells by its header and a column's by its header's selection gesture, whose value `selection` and `onSelectionChange`'s `event` are `{"anchor": {"key", "column"}, "focus": {"key", "column"}}` or `null` (a bound `selection` is shown; `onSelectionChange` runs after each change of the selection), copied by `Ctrl+C` as tab-separated display text, pasted into by `Ctrl+V` from the focused cell (values on read-only cells, past the last column and past the last row dropped and counted in the status line, "Pasted 4 values; 2 on read-only cells were dropped"; a block of more than the session's `maxPasteCells` (10,000) values is refused, "A paste holds at most 10,000 values"), filled down by `Ctrl+D` and blanked by `Delete`, each one change of the form; or `layoutRows`, a fixed grid ([`../table/editing.md`](../table/editing.md#fixed-grids)), in place of `rows`: parts each a row `{key, label, cells}` or a block `{forEach, rows}`, with `form` the id of the form node whose fields its cells edit (absent for a grid of `value` and `text` cells only); a row's `cells` map column ids of the table's column parts to a cell part that names one of `field` (a path of the form's fields, `limits.density.min`; in a block, of its collection's row type, `mass`), `value` (an expression, read in a block with `row` the collection row's record) or `text` (a string), with `rows` and `columns` (literal counts from 1, default 1: the cell spans that many rows down and columns to the right), and a grid column's overlays, `decimals`, `unit`, `readonly`, `options` and `placeholder`, read as a grid column's (all but `readonly` only on a `field` cell, "`` is an overlay of the field a cell edits; this cell edits no field"), a `unit` given when the cell is first shown, or after a load, as the field's loaded unit, and two literal units given one form field by overlays anywhere in the document (cells, or grid columns over the same member) refused ("`` is given the units `` and `` by two overlays; a field is entered in one unit"); a row's `label` is read once, and in a block reads no `row`; a block's rows repeat for each row of the form's collection `forEach` names, each keyed `"/"`, so a key holding a `/` is refused ("the row key `` holds a `/`, which joins a block row's keys; give it another"); keys are unique across the grid, a block's rows included ("the row `` is declared twice in the grid"); `layoutRows` with `rows` ("a fixed grid's `layoutRows` are in place of `rows`"), with `field` ("a table with `layoutRows` takes no `field`"), on a model's table, with `sort`, `group`, `summaries`, `rowSpans`, `appendRows`, `rowsFixed` or `key` ("a fixed grid's rows are fixed …; it takes no ``"), with column parts that name a `field` or a `value`, a cell under an id the column parts lack, a cell naming none or more than one of `field`, `value` and `text`, a `field` cell or a block without `form`, a `field` that is no field of the form's schema, a `forEach` that is no list of records of it, and a block inside a block are refused; a fixed grid walks, selects cells, copies, pastes and validates as a grid of a form, with `enterMoves`, `walk`, `onActivate`, `selectionMode` `cells`, `selection` and `onSelectionChange` as it takes them, is never sorted or filtered, and names each row by its `label`; `appendRows` (a literal flag: `Tab` past the last cell and `Enter` below the last row add a row, and an "Add row" button under the grid, test id `_addRow`, does, disabled at the field's `maxItems` with the reason as its tooltip) and `rowsFixed` (a literal flag: no row is inserted, deleted or appended, and no entry offers it; with `appendRows` refused, "a grid with `rowsFixed` adds no rows; drop `appendRows`"), both refused on any other table ("`appendRows` is a grid's; this table is not a grid of a form"); `bands` (on any table and a field overlay's `grid` part: parts `{label, unit, columns, bands}`, `columns` a literal list of column ids and `bands` the parts one level down, drawn above the column headers, a band's unit after its label and not repeated by a column of the same unit; nested past 3 levels, a band naming no column or an id the table's column parts lack, a child over a column its parent lacks, or a column in two bands of one level is refused, naming the band's label; a model's table draws its description's bands unless it declares its own, and bands that do not fit its columns are reported and not drawn; a declared or user-formed column group draws as its one-level group line); a `rowSpans` part's `columns` (an integer from 1, default 1: the cell covers that many columns to the right in the layout, cut at a column the user moved away or hid); `summaries` (on a table over `rows`, a grid of a form and their `group` part: parts `{key, label, position, cells}`, `key` required and unique in its list, `position` `bottom` (the default) or `top`, refused otherwise, `cells` a record of expressions by column id, each column one of the table's, read with `rows` the records of the rows summarised, in view order, and `column` the column's id; a table's summaries are drawn before or after its rows (a paged table's on every page, over every row of the view) and a group's after each run, outside the order, the filter and the selection; a summary's `label` names its row; a copy whose rectangle spans a summary row copies its cells as drawn; a summary row's key is `"summary:"`, a group's `"summary:/"`, and a summary cell's test id `summary__`, a group's `summary___`; a model-backed table refuses `summaries` on itself and on its `group`, "a summary row summarises rows the client holds; a model-backed table refuses `summaries`, as it refuses `group`"; a grid of a form takes a `group` too, its runs over the array's order); unless `rowsFixed`, the cell menu offers, after "Revert row" and a separator, "Insert row above", "Insert row below" and "Delete row" ("Delete rows" when the cell selection spans more rows, deleting them all), and the table menu the same for the focused row, after its own entries and a separator; `Ctrl+Shift+=` inserts a row below and `Ctrl+-` deletes; an insertion is disabled at `maxItems` ("A grid holds at most 5 rows") and a deletion where it would leave fewer than `minItems` ("A grid holds at least 1 rows"); a deletion happens at once and, when a deleted row held a value, the status line says "Deleted 2 rows" ("Deleted 1 row") with "Undo", which puts them back until the grid's next change or for 6 s, whichever ends first; `selectionMode` `cells` on a table over `rows` is refused, its lowering there deferred; or `model` and `action`, a typed list action that takes a `TableQuery` and returns a `Page`, with `body` (the request's fixed part), `mode`, `status` and `persist` as a model's table takes them: the action's request schema marks one top-level member `x-table`, the member the query is written into (else "a table over an action needs a query member marked x-table", and two marked are refused too), and the table has its `columns` parts or the action has a view document (else "a table over an action needs its columns, or a view document for the action"), since its description is built on the client from them, its key from `key`, the view document's `v-rowKey` or `id`, and each column's kind from the part's `kind`, the view document's or the first reply's rows (each rule runs when the catalog supplies `schema` and `view`); `key` ⓘ, `columns` (parts `{id, label, kind, width, role ⓘ, align, valign, sortable, locked, filterable, wrap, shrink, sortBy ⓘ, cell ⓘ, decimals, rounding, padPlaces, grouping, empty, unit, date, labels, tone ⓘ, tooltip ⓘ}`, or an expression of `{id, label, align, valign}` records; `locked` (a literal flag) keeps its column where it is declared: the user cannot move, hide, pin, unpin or resize it, and each such gesture is refused in the status line, "{label} is locked"; `filterable` (a literal flag, default `true`): `false` draws no filter button on the column's header and leaves "Filter…" out of its menu; a column part with an id is otherwise filterable (on a model's table, while its description marks it so), and its menu offers its values and the conditions of its kind; a column's display parts override the description's display member by member on a model-backed table and are its only source on a table over `rows`, and change what a cell shows, never what a sort, a filter or a selection uses: `decimals` (a literal integer 0 to 18) the places a number shows, rounded by `rounding` (`halfEven`, the default, or `halfUp`, half away from zero), padded with zeros to them unless `padPlaces` (a literal flag, default `true`) is `false`; `grouping` (a literal flag, default `false`) groups digits by the locale; `empty` the text of an empty cell (an unloaded one draws its placeholder, an invalid one an error mark); `unit` the unit the header shows after its label, `Mass [kg]`; `decimals` and `unit` on a `Measure` column are reported and ignored, since its cells show their own units; `date` a `Date` or `DateTime` column's pattern, checked as `formatting`'s are; `labels` a literal list of `{operand, text}`, the text a cell shows for the value its operand names; on a table over `rows` a cell's kind is its value's, and a quantity keeps its unit after the formatted amount; `tone` and `tooltip`, read in the row's scope on a model-backed table (a table over `rows` reports them and draws neither), the cell's tone (a tone name; any other value shows none and is reported once for the column) and its tooltip, which win over the description's companion columns, whose columns are then not fetched for them; a description's companion column is never one of the table's columns, and a part that names one is reported; `kind` is a literal, one of `text`, `integer`, `decimal`, `number`, `date`, `dateTime` and `bool` (any other is refused, "`kind` is one of text, integer, decimal, number, date, dateTime, bool"): the kind a `rows` table orders the column's cells as, a cell of another kind being invalid and sorted last, and the kind a typed list action's reply is read as; absent, the kind is inferred from the cells — `role` styles the column's default cell and has no other effect on one with its own `cell`; it takes a text's role names, and a literal one is checked the same way; a `mono` role also sets the width unit of the column's `fixed(n)`: n mono characters, plus the cell padding, with or without a `cell`, so a column of identifiers says `mono` to hold them whole; `wrap` (a literal boolean, default `true`) with `false` draws the column's text cells on one line, cut at the column's width with an ellipsis, such as a value with its unit; `shrink` (a literal flag, default off, for a column whose `width` stretches; on any other column it is reported once and ignored) lets the column go narrower than its header when the table is narrower than its columns need, down to a floor of 8 units, its header and cells then cut, where otherwise no column is narrower than its header and the table scrolls sideways, and makes it give up width before the other stretch columns (the two meanings are one flag; a column that may go under its header but keeps its content late has no spelling); a stretch `width` starts from the column's content (its header and its widest shown cell) and its weight shares only the width the content leaves, so proportions that ignore the content cannot be said, a literal `percent` column stays refused, and a width the user sets would be a fixed column; `align` (`start`, the default, `center`, `end`) places a text cell's or a text input's text, a badge, check box or push button cell, and the header label across the column, while a container cell fills it; `valign` (`start`, `center`, the default, `end`) places every cell down its row; both are literal names, and a computed column's place of no known name is reported once and takes the default), `valign` (the default of every column that gives none), `selectionMode`, `selection` (a list of row keys: bound, it is controlled, as a select's `selected` is; refused without a `selectionMode` of `single` or `multiple`, and on a model-backed table), `onSelectionChange` (after each user change, with `event` the new keys; the same rules), `selectColumn` (a literal flag, only with a literal `selectionMode: multiple`: the table draws its selection as a leading column of check boxes under a select-all box), `selectAllLabel` (the select-all box's accessible name, only with `selectColumn`; default `Select all`, translated with `t`; on a model-backed table with `selectionMode: multiple`, `Ctrl+A` and the select-all box select the view, fetching no row: a `Ctrl`+click then leaves a row out of it or takes it back, a `Shift` range does so for the range by its anchor, a plain click selects that row alone, a change of the filter ends it and a sort keeps it; it is refused in the status line while rows are undecided, "Select all is available once 40 rows are decided", or a filtered column's level is awaited, "Select all is available once recipe data has loaded"; an action refused with `morph.table.viewChanged` over such a selection is offered again in the status line, "The rows changed since you selected them: n rows now. Run on these?", with the entry "Run on these" that sends it again on the view as it is), `rowLabel` ⓘ (each row's accessible name, which its box carries; default the row's key as text), `sort` (a list of keys `{"column": , "direction": "asc" or "desc"}`, most significant first, `[]` the source order: the table orders its rows by it; bound, it is controlled, as `selection` is, and unbound the table holds it from `[]`; a literal one names sortable columns, each once; a column's `sortable`, a literal flag that needs its `id`, lets its header build the sort chain: a click sorts by it alone, ascending, or descending when it already is the first key ascending; `Shift` with the click adds it as the last key, ascending, or flips its key's direction in place when the chain holds it; its header menu's "Sort ascending", "Sort descending", "Add to sort" and "Remove from sort" do the same without a modifier; on a model-backed table the description says which columns sort; its `sortBy`, only with `sortable`, is the value the rows order by, read per row as `key` is, default the row's field of the column's `id`), `onSortChange` (after a sort gesture, with `event` the new sort; on a table over `rows` it needs a sortable column), `maxSortKeys` (a literal integer 1 to 32, a `rows` table's only, default 8: the most keys the sort chain holds, which the header and menu gestures are held to; a key past it is refused in the status line, "A table sorts by at most {n} columns", and the chain is kept; on a model-backed table it is refused, since a model's table carries its bound in its description, from its `limits`), `layout` (the column layout `{"order": [id…], "hidden": [id…], "pinned": n, "widths": {id: units}}`: bound, any expression but a literal `null`, it is controlled, as `sort` is, and the stored layout is neither applied nor saved; unbound the table holds it from its declared columns, and a model-backed table's columns the description does not show start hidden; on a table over `rows` a derived `columns` expression is read once, when the table is made, for the layout's columns, and a stored layout is fitted against the column parts alone, so a derived column it places is kept as stored rather than applied; a column with no `id` is named `#` in `layout`, `visibleColumns` and the stored layout, `n` its place among the table's columns from 0, derived columns first, and it is locked: the name follows the place, so a column inserted before it gives a stored `#` to another column), `onLayoutChange` (after a user's change of the layout, with `event` the new layout), copying (`Ctrl+C` and the table menu's "Copy" and "Copy with headers" copy the selected rows, or with none the focused cell, as tab-separated text of what each cell shows, for at most the session's `maxCopyRows` (10,000) rows; a larger selection is refused in the status line, "A copy holds at most 10,000 rows", and copies nothing), saved views (a table that keeps a state has `Views` in its table menu: the user's own views, each applied with its layout, sort and filters and marked `{name} (modified)` once the arrangement differs from it, "Save view…" (a name the user already has replaces that view), "Rename view…" (onto a taken name refused, "A view named {name} exists"), "Remove view", "Set as default" and "Start from the default view"; with no stored arrangement the default view is applied at mount, and with "Start from the default view" its sort and filters are applied at every mount over the stored arrangement's; over a store that shares, the shared views under "Shared views", "Save as my view" and "Publish view…"), `configurable` (a literal: `true`, the default, `false`, or a list of `"reorder"`, `"hide"`, `"pin"` and `"resize"`, what the user may change about the columns; any other value is refused, "`configurable` names ``; it lists reorder, hide, pin and resize"; `false` offers no header or table menu; a gesture the list does not allow is refused in the status line, "This table's columns cannot be moved" (`hidden`, `pinned`, `resized`), and a table that does not allow `resize` has no header edge to drag), `onFiltersChange` (after a user's change of the filters from the header's filter menus or "Clear all filters", with `event` the new filters; the table holds the change and keeps it in its persisted state unless the document binds `filters`; a table with `configurable: false` has no menus but keeps its filter buttons), `groups` (a table over `rows`'s only, refused on a model-backed table, whose description declares its groups: parts `{id, label, columns}`, `columns` a constant list (`{"lit": [...]}`) of 2 to 16 of the table's column part ids of one literal `kind`, each column in at most one group, else "a group has 2 to 16 columns", "a group's columns are the ids of the table's column parts", "the column `` is in another group" or "a group's columns hold one kind of value"; a group's values list is pooled over its columns, its filter names it by `id`, and its header stands over its columns while they stand side by side), `pageSize` (a positive integer: the table shows one page of that many of its sorted rows; absent or `null`, every row; a literal below 1 is refused), `group` (a part `{by ⓘ, heading ⓘ}`: a heading row before each run of adjacent rows whose `by` values are equal, drawn from `heading` in a row scope whose `row` is the run's record `{key, count, first, last, items}` of the whole group; a heading spans every column, is never selected, marked or activated, and counts in no element value; with a sort, each group keeps its place and its rows are sorted within it, and a group split across pages gets its heading on both; refused on a model-backed table; a heading's key is reserved, `"\u001Fgroup:"` then the canonical JSON of its run's key, `":"` and its ordinal among the runs with that key, and a data row with a field `"\u001Fgroup"` is taken for a heading), `page` (the page shown, from 0, clamped to the last; absent or `null`, the first; needs `pageSize`; `pageSize` and `page` are refused on a model-backed table, whose engine pages), `filters` and `highlightKey` (a model-backed table's only; `filters` written as an object of `columns` and `groups` alone is the literal filter, read as a `table::FilterSpec` and refused when it does not read, "`filters` is not a filter: ", the default a stored filter replaces; any other value is an expression that binds the filters), `rowTone` ⓘ, `rowSpans` ⓘ (each row's spans, read in the row scope: a list of `{column, rows}` records, `column` the id of a column and `rows` an integer from 1 counting the row itself, whose cell in that column covers the rows below; `null` or `[]` none; the cells it covers are not shown and their content is ignored, though a client that does not know the key draws them, so a document leaves them empty; a table that is sorted, or above its virtualization threshold, draws no spans, and a span that names no column, repeats a column of its row, runs past the last row of the page the table holds, runs over a group heading, or starts in a column an earlier span covers, is refused and reported, the cell then standing in its own row (the interpreter's reports carry a path; the mount's for a span past the last row, onto a covered column, or above the virtualization threshold are bare and name none, so look at the rows' order); a spanned table should not page, or should page by groups, since a page boundary through a span refuses it; [`view_tree.md`](view_tree.md#row-spans)), `onActivate` ⓘ, `cellMenu` (parts in the `menu` node's entry shape, `{label, icon, keys, checked, enabled, onClick, items, description, visible}` or `{separator: true}`, checked and reported as a `menu`'s entries are. A right click, a long press, or `Shift+F10` or the context-menu key on the focused cell opens the cell's menu: it focuses the cell and selects its row alone when the row is not selected, a selected row keeping the selection. It shows "Copy", "Copy with headers", "Filter by this value" (the column's filter becomes `{include: [{oneOf: []}]}`, replacing the column's entries), "Exclude this value" (the operand joins the column's `exclude` `oneOf` entry, made when absent) and, on a column of a declared group, "Filter by this value in any " (the group's filter becomes `{group: , include: [{oneOf: []}]}`, replacing that group's); on an empty cell they use `{isEmpty: true}`, and on a cell not loaded or not readable, in a column that does not filter, or while `headerEnabled` is false, they are disabled; one chosen anyway is refused as a header gesture is. On a table over `rows` a cell is read as the column's filter reads it, by the kind its cells infer. Then a separator and the parts, read in the row's scope with `row` (the row's record, as `{"ref": "row.id"}`), `column` (the column's id) and `value` (the cell, as the record holds it) bound, each as it was when the menu opened; the menu has a row scope of its own, so state the table's row scope declares reads its initial value there. An entry's `keys` work while the table has the focus, on the focused cell: only a key that is some entry's `keys` asks for the focused cell's entries, and asking moves no focus. What the parts read of the row is fetched with every row, as `rowTone`'s is), `headerMenu` (parts in the same shape: a header's menu shows its own entries, a separator, then these, read with `column` bound to the header's column id, so `"visible": {"fn": "eq", "args": [{"ref": "column"}, "mass"]}` shows an entry on one header; a header whose parts are all hidden adds nothing, separator included; a table with `configurable: false` has no header menu, so none shows), `headerEnabled` (a condition, default `true`, read at each gesture: while it is false a header click, a filter button, a column's move or resize and a group's filter button change nothing and send no query, each refused in the status line, "Sorting, filtering and arranging are unavailable right now"; every entry of a header's own menu, every entry of the table's menu but "Copy" and "Copy with headers", and the cell menu's filter entries are disabled, and a menu entry opened before and chosen after the condition turned false is refused the same way. Selecting, scrolling, copying and the `cellMenu` and `headerMenu` entries stay, so a screen that runs a long operation over the rows sets it to keep them from reordering or leaving the view), `empty` (nodes: shown instead of the table while `rows` is an empty list; on a model-backed table, below it once a reply said the view has exactly no row and no row is undecided), `scope` | `selection`, `activeKey`, `sort`, `filters` (the filters the rows hold, `{"columns": {id: filter}, "groups": [group filter…]}`, each group filter naming its group or its columns, never an empty one of the two), `viewCount` (the rows the table orders, every page; on a model-backed table the reply's total, `null` before the first), `viewCountKind` (a model-backed table's: `exact`, or `atLeast` when the total is a lower bound), `undecided`, `awaiting` and `failed` (a model-backed table's: rows its filter cannot decide yet, and the levels its order waits for or failed to load), `sourceCount` (the rows `rows` gave), `selectedCount` (on a model-backed table holding a selection of the view, the view's total less the keys of `except` the window holds), `selectedCountKind` (`exact`, or `approximate` while the total is a lower bound or a key of `except` is not accounted for; the status line then says "about n of m selected"), `selectionSet` (every table's selection as an action's body takes it: `{"keys": […]}`, or on a model-backed table after select-all `{"view": {"filters", "retained", "revision"}, "except": […]}`, the view's filter with its default members left out; `selection` is then `[]`), `busyCount` (a model-backed table's: how many rows an action of this session is working on, those its input names as a `RowSelection` or a `RowRef` of the table's record, until it settles whatever its outcome; with a selection of the view in flight, the view's selected count at the run's start; such a row draws busy and takes no cell edit, and the status line stands with "Saving 40 rows"; a row the action's `ChangedRows::failed` names draws `err` with its message as its tooltip until the next action on it, a change event naming it after the action settled, or "Clear marks", and the status line stands with "12 rows could not be saved" and "Select them", which selects them; a row whose `rowLock` companion holds text draws locked with that text as its tooltip and takes no cell edit; a `ChangedRow` with `from` moves the selection, the focus, the retained rows and the busy and failed states the session holds by `from` to the new key, and while such an action is in flight a selected key that leaves the view is kept until it settles), `modifiedCount`, `modifiedRows` and `errorCount` (a grid of a form's: its cells whose value differs from the one the form was loaded with, its rows with such a cell or added since, and its cells whose draft does not encode or that the last submission refused; 0 on any other table), `editing` (a grid of a form's open cell editor, `{"key", "column"}`, or `null`), a grid's `selection` (its cell selection, `{"anchor": {"key", "column"}, "focus": {"key", "column"}}` or `null`), `pending`, `error`, `hoveredKey`, `layout` (the layout the table holds or the document binds, fitted to the table's columns; `groups` and `units` only while they hold anything), `visibleColumns` (the ids of the visible columns, in order), `hiddenCount` (how many columns are hidden), `page` (the page shown, clamped), `pageCount` (at least 1), `pageFirst` and `pageLast` (the 1-based positions of the page's first and last rows, both 0 when there are none; a table that does not page reads page 0 of 1 over every row) | | `dateTimeInput` | `value`, `mode`, `label`, `showLabel`, `onChange`, `onCommit` | as `textInput` | | `slider` | `value`, `min`, `max`, `step`, `label`, `onChange`, `onCommit` | as `textInput` | | `filePicker` | `accept`, `multiple`, `mode`, `label`, `onPick` | | @@ -324,7 +324,7 @@ weight and face, so `{role: display, tone: err}` is a large red figure. | `actionBar` | `children`, `align`, `justify` (as a `row`'s). An action bar holds the actions of what holds it: the footer of the dialog or drawer it is inside, at any depth, else the place it is written, as a row. The buttons are the theme's `actions.gap` apart (spacing step 2 while the theme sets none), so it takes no `gap`, which the loader refuses; `wrap` (a literal flag, as a `row`'s) lets actions that do not fit continue on the next line, and is refused at mount in an overlay's footer. A horizontal `forEach` that is a direct child of the bar is part of its row of actions and takes the theme's gap too, so a `gap` on it is refused at `/…/gap`: at load when its `axis` is the literal `"horizontal"`, at lowering when a computed `axis` evaluates to horizontal. A vertical `forEach`, or one inside a `row` in the bar, is unchanged | | | `customize` | `point` (required) | | | `boundary` | `loading`, `error`, `children` | | -| `form` | `model`, `action` (required), `prefill`, `key` (the identity of the record `prefill` holds), `submit` (`explicit` or `auto`; absent keeps the schema's mode), `showErrors`, `fields` (field name to overlay of expressions: `omit`, `hidden`, `label`, `unit`, `decimals`, `widget`, `blankAs`; an overlay may also name a `component` that draws the field, with `props`, a record of expressions. An overlay's `decimals` overrides the schema's `x-decimalPlaces` for that field and means exactly what the key means in `InstanceConstraints`: the canonical unit's entry places (the most fraction digits it accepts) and the wire `dp`. Another unit of a Quantity keeps its own places, so a unit switch never rewrites or rejects a draft by places that belong to another unit; a literal overlay and a served key mean the same. On a Decimal, a Quantity and a plain Number it bounds what is accepted and is the places a value is shown at (on a Number, in place of `x-displayDecimals`); on an Integer it does nothing. A prefill is shown at the places the expression gives when it loads (the canonical unit's, as a served key would show it; the schema's when it gives none), so a Decimal or Quantity record with fewer places than the schema loads without trailing zeros, a Number record with fewer places is padded with zeros to them, and one with more places is not rounded. It follows its expression: a change re-checks the draft the field holds, a prefilled one included, which stays as typed and shows the field's `too-precise` error when it no longer fits. An expression that gives no places (null, negative, not an integer) restores the schema's places, whatever it gave before. The form builds from the catalog's static schema for the action, so the overlay is how a screen gives a field its record's places; the schema a form builds from is not decorated per instance, which is also why an instance's `minimum` and `maximum` have no client half here), `onSubmit`, `onSuccess`, `onError`, `title`, `submitLabel`, `showStatus` (a literal `bool`; default `true`), `columns` (a literal integer, 1 to 12), `fieldLayout` (`stacked`, the default, or `inline`: each label beside its control), `captionWidth` (the width of the inline label column in units, a literal integer from 1 to 64, refused without `fieldLayout: inline`; absent keeps the engine's 16; it is the document spelling of `inlineLabelWidth`, and means what it means on `keyValue`) | `ready`, `body`, `submitted`, `pending`, and each field as a record of `value`, `draft`, `valid`, `required`, `visible`, `readonly` and `errors` (`form.field.value`) | +| `form` | `model`, `action` (required), `prefill`, `key` (the identity of the record `prefill` holds), `submit` (`explicit` or `auto`; absent keeps the schema's mode), `showErrors`, `fields` (field name to overlay of expressions: `omit`, `hidden`, `label`, `unit`, `decimals`, `widget`, `blankAs`; an overlay may also name a `component` that draws the field, with `props`, a record of expressions. An overlay whose `widget` is the literal `grid` may give a `grid` part, the keys a `table` over a `form` takes beside its `form` and `field` (`columns`, `enterMoves`, `walk`, `onActivate`, `layout`, `onLayoutChange`, `configurable`, `onFiltersChange`, `cellMenu`, `headerMenu`, `headerEnabled`, `testId`), read as such a table's are: the grid that draws the field is that table; a `grid` part beside any other `widget` is refused, "a field's `grid` gives a grid widget its columns; give it `widget: \"grid\"`". An overlay's `decimals` overrides the schema's `x-decimalPlaces` for that field and means exactly what the key means in `InstanceConstraints`: the canonical unit's entry places (the most fraction digits it accepts) and the wire `dp`. Another unit of a Quantity keeps its own places, so a unit switch never rewrites or rejects a draft by places that belong to another unit; a literal overlay and a served key mean the same. On a Decimal, a Quantity and a plain Number it bounds what is accepted and is the places a value is shown at (on a Number, in place of `x-displayDecimals`); on an Integer it does nothing. A prefill is shown at the places the expression gives when it loads (the canonical unit's, as a served key would show it; the schema's when it gives none), so a Decimal or Quantity record with fewer places than the schema loads without trailing zeros, a Number record with fewer places is padded with zeros to them, and one with more places is not rounded. It follows its expression: a change re-checks the draft the field holds, a prefilled one included, which stays as typed and shows the field's `too-precise` error when it no longer fits. An expression that gives no places (null, negative, not an integer) restores the schema's places, whatever it gave before. The form builds from the catalog's static schema for the action, so the overlay is how a screen gives a field its record's places; the schema a form builds from is not decorated per instance, which is also why an instance's `minimum` and `maximum` have no client half here), `onSubmit`, `onSuccess`, `onError`, `title`, `submitLabel`, `showStatus` (a literal `bool`; default `true`), `columns` (a literal integer, 1 to 12), `fieldLayout` (`stacked`, the default, or `inline`: each label beside its control), `captionWidth` (the width of the inline label column in units, a literal integer from 1 to 64, refused without `fieldLayout: inline`; absent keeps the engine's 16; it is the document spelling of `inlineLabelWidth`, and means what it means on `keyValue`), `derive` (an action of the form's model, checked against the catalog as the form's `action` is, that the form calls with `{"body": }` after a grid's commit to load its derived members, [`../table/editing.md`](../table/editing.md#derived-values)), `deriveDebounce` (a literal integer, milliseconds of no commit before a round of derived values, default 150: a round evaluates the action, for its computed members, and calls `derive` when the form names one, so the debounce times both and is taken without `derive`; refused when it is not a literal of 0 or more, "`deriveDebounce` is a literal count of milliseconds, 0 or more") | `ready`, `body`, `submitted`, `pending`, and each field as a record of `value`, `draft`, `valid`, `required`, `visible`, `readonly` and `errors` (`form.field.value`) | | `collection`, `wizard` | `model`, `action` (required), and `submitLabel`, `showStatus`, `columns`, `fieldLayout` and `captionWidth` as on `form`, reaching every form the view draws; `title` replaces its heading | | | `custom` | `name` (required), `props` (record of expressions), `on` (record of command lists) | | @@ -501,7 +501,7 @@ evaluated. - **Components and points.** A custom node names a declared component and only its props and events; a component names exactly one of `qml` (`sha256:` and 64 lower-case hex digits) and `host` with an integer `version`, prop types from `string`, `bool`, `int`, `exact`, `number`, `json`, and - a fallback. A `customize` node names a declared point; a `columns` point names a table; a `choice` + a fallback. A `customize` node names a declared point; a `columns` point names a table, and a `saved` point that gives `of` names one; a `choice` lists its options and defaults to one of them; a `value` point declares its type and its default has it; an `arrange` point's `of` names a `column` or `row` of the same screen whose children all have ids, no other `arrange` point names the same container, and the app document, which has no view, diff --git a/docs/spec/ui/interpreter.md b/docs/spec/ui/interpreter.md index a99d6dfdd..c4e6b0fc2 100644 --- a/docs/spec/ui/interpreter.md +++ b/docs/spec/ui/interpreter.md @@ -192,6 +192,36 @@ canonical body is the body's JSON with record fields in name order. `replace: true` set whatever order the owner and the cache acted in, and the cache dropping its last entry on the record does not unwatch it. `removeExtraWatch(record)` sends the `unwatch` unless an entry still holds the record. Events arrive through `deliverEvent` as any other. +- **Open, partial and opaque entries.** The catalog's `ActionRecordInfo` carries, beside a record's key + field and paths, `open` and `partial` (paths of members a holder of the record's rows declares through + `openMembers()` and `partialMember()`, as a table's `Page` declares `awaiting`, `distinct` and + `unloadedRows`) and `opaque` (the result holds the record at no path, as `Table.` holds its table's + record). A member is set when its value is a non-empty list, a record, `true`, or a number other than zero. + - **An open entry is marked by every change of its record**, whatever the keys: while an `open` member is + set, a row the entry does not hold may come to belong to it. + - **A partial entry is not merged into.** While an `open` or `partial` member is set, an `updates` effect + on the record acts as `changes` for that entry: a merge replaces rows by key and cannot update what such + a member says about rows by position. + - **An opaque entry is both,** always: its rows cannot be found by key. Its reply is read with + `detail::tableValueFromJson`, which keeps a JSON number with a fraction or an exponent as the decimal its + shortest round-trip text in fixed notation spells (`table::parseDecimal`; `0.0001` stays a decimal), or as + its shortest text where no decimal holds it; a page's + `Number` cells are such numbers, and the strict `valueFromJson` would refuse the whole page. Every other + entry keeps the strict rule. +- **Reading and watching without an entry.** A page window's fetches are not queries. + - `Session::read(channel, action, body, stop)` sends the action and settles with the reply's JSON text, + unparsed: a `Value` holds no number with a fraction or an exponent, and a page's `Number` cells are such + numbers, so the caller decodes the text against the table's description (`table::readGenericPage`). It + makes no entry, reads none and applies no effects. `stop` goes to the channel as `CallOptions::stop`, + which sends the wire's `cancel` where the server takes one; a stop settles the read with + `core::async::OperationCancelled` and drops the reply. + - `Session::watchRecord(record, handler)` counts the record into the watch set as an entry does and + resolves with a `WatchHolder` once the server has the watch (at once when it already had it, or there is + no watcher). The holder is copyable: the watch lasts while any copy lives, and the last copy's death + removes the handler and counts the record out. A `Completion` hands its value as `const&`, so a caller + keeps the watch by copying the holder in its `then` handler. The handler hears each `changes` event that + names the record, after the entries are marked, and a whole-type change on reconnect and on `resync`. A + holder that outlives its session releases nothing. - **Invalidation** (`refetch`, a backend switch) marks the entry stale and refetches it. - **A mark during a fetch is kept.** `Session::markStale` marks an entry stale. While the entry's fetch is @@ -424,10 +454,19 @@ keeps its operands' 0 places and still fills 0.29 of a bar. scope and gives the row its tone: `"neutral"`, `"info"`, `"ok"`, `"warn"`, `"err"`, or `null` for none; another value shows no tone and is reported once for the table (`rowTone is ; a tone is neutral, info, ok, warn or err`). `rowSpans` is evaluated in each row's scope as a slot, like `rowTone`, and gives the - row its `TableRowView::spans`: a list of `{column, rows}` records, `column` a column's id (a derived column's too) - turned into its index and `rows` an integer from 1. A record that is not of that shape, names an id the table has - not, or has a `rows` that is no integer of at least 1 is dropped and reported once for the table (`rowSpans is ; - a span is {column: a column's id, rows: an integer from 1}`); `null` and `[]` give none. What follows from the rows' + row its `TableRowView::spans`: a list of `{column, rows, columns}` records, `column` a column's id (a derived column's + too) turned into its index, `rows` and `columns` integers from 1, each 1 when absent. A record that is not of that + shape, names an id the table has not, or has a `rows` or `columns` that is no integer of at least 1 is dropped and + reported once for the table (`rowSpans is ; a span is {column: a column's id, rows: an integer from 1, columns: an + integer from 1}`); `null` and `[]` give none. A span's `columns` is cut by the table's layout (`cutColumns`): it covers + its column, then each next visible column while that is the next declared one, so a span across a column the user + moved away or hid stops there, and a span whose own column is hidden is dropped. A table over `rows` with + `summaries`, or with a `group` part that has them, is mounted over a `SummaryRows` it keeps over its page's entries: + the table's summaries before or after the page's rows and each run's after the run. A summary reads `rows` as every + row of the view in view order (a paged table's summary is the same on every page), a run's summary its run's rows, + and `column` the column's id; its cell shows the value by the column's display parts, as a default cell does, and + its part's `label` names its row. The table's `bands` parts become + `TableOptions::bands`. What follows from the rows' order (a span past the last row, over a group heading, onto a covered column) is the mount's to refuse. The pipeline pages before the table sees its rows, so a span reaching past the page's last row is refused and reported. The table's sort is the one `options.sort` carries: while it names a column the table draws no spans. The selection the table shows is a slot over the bound `selection` @@ -438,52 +477,301 @@ keeps its operands' 0 places and still fills 0.29 of a bar. The mount re-asserts the slot after the handler, so a bound selection the document does not write back snaps back, and a literal one never changes. The element values `selection` and `selectedCount` read the bound value when there is one and the table's own otherwise. - **The rows' pipeline.** The table's element holds a computed made when the element is wired, beside its - `rows`, so every reader of its element values (a pager drawn before the table included) and the table's own - lowering see one order, and `rows` is evaluated once per change. It evaluates `rows`, then sorts the list by - the table's sort: the bound `sort`, or the table's own (starting at `[]`) when no key binds one. Each key - names a sortable column; the column's `sortBy`, or the row's field of the column's `id`, is read once per row - with the row bound, in the table's scope, and the rows are ordered by those values as `sort` orders - (`expressions.md`, Sorting), key by key. A sort of `null` or `[]` keeps the source order; one that is not a - list of `{column, direction}` records naming sortable columns, or whose values cannot be ordered, keeps the - source order and is reported once at the table's `sort` path, so a data error does not blank the screen. - `sortBy` runs before any row's scope exists, as `key` does, so a row-scope name in it reads `null`. Then it - pages the sorted list, so page 2 holds the second page of the whole sorted list: `pageSize` and `page` are read - in the table's scope; a `pageSize` of `null` does not page, and one that is no positive integer is reported once - at its path and does not page either; a `page` of `null` is the first, one that is negative or no integer is - reported once and shows the first, and one past the last shows the last, unreported, since a filter that shrinks - the rows under the user is normal. The backend holds the page's rows alone, as it would a short table. On a - user's change of the selection, an `Extend` report keeps the selected keys of the rows on other pages, in their - order, before the reported keys; a `Replace` report is the whole new selection, so a plain click or a range - clears the other pages' keys as it clears the rest of its own, and every `Single` change is one. A key whose row - `rows` no longer has drops on any user change. `empty` shows while `rows` is empty, not while a page is. - **Groups.** With `group`, the pipeline splits the source rows into runs by `by` (read per row as `sortBy` is, - adjacent rows with equal values, `null` equal to `null`), gives each row its run's index, and sorts by that index - first and the sort's keys second, so every group keeps its place and its rows are ordered inside it. It pages the - data rows, and puts a heading entry before the first row of each run the page holds: the run record of the whole - group, computed before paging, so a group split across pages reads the same `count`, `first` and `last` on both, - with its key in a reserved field. The row view lowers `heading` for that entry as one cell, in a row scope of its - own whose row is the record, and the table makes it a heading row (`TableRowView::heading`). A heading's key is - `"\u001Fgroup:"`, the canonical JSON of the run's key, `":"` and its ordinal among runs with an equal key, so - groups A, B, A get three headings; a data key equal to one is reported as a duplicate by the mount. Heading keys - never reach `onSelectionChange`: the lowering drops them from a report, since a virtualized backend's Ctrl+A or - range can name a row it has not realized. `viewCount`, `selectedCount` and the page positions count data rows. A table - lowered where names are bound (a component's `props`) sorts its own copy with those names, which its element - values cannot see. The mount's keyed reconciliation moves the sorted rows, so each keeps its widget, its - native state and its selection. The header marks the sort's first key (`Table::sort`); a header click on a - sortable column (`Table::onSort`) makes that column the single key, `desc` when it already is the first key - and `asc`, `asc` otherwise, sets the table's own sort when no key binds one, and runs `onSortChange` with - `event` the new sort, as a user event, in one batch. The element value `sort` reads the bound sort or the + **The rows' pipeline.** The interpreter does not sort or page a table: its element holds, from when it is + wired, the table's rows on the engine, so every reader of its element values (a pager drawn before the table + included) and the table's own lowering see one order, and `rows` is evaluated once per change. The evaluated list + goes to a `ValueRowsSource`, matched by `key`, under a `table::Engine` whose owner is the runtime's, with no worker, + owner steps of 4 ms and `ValueRowsCollator` for text, read through an `EngineRows`; a changed row is repaired in + place, not sorted again, and a row whose fields changed is drawn again even when no sort reads them. The table's + sort, the bound `sort` or the table's own (starting at `[]`), is the engine's sort chain. A key names a sortable + column, whose cells the source holds while a key reads it: the column's `sortBy`, read per row in a tracked + computation with the row bound in the table's scope, or the row's field of the column's `id`, converted to the + column's kind, its literal `kind` or else the kind its cells infer. A quantity reads its unit from a registry of + the screen's unit table, each unit in its canonical unit's dimension; a unit the table does not list is its own + canonical unit, as an expression reads it: when a row's field brings one, the source and the engine are made + again over a registry that holds it (a unit only a `sortBy` produces is not seen, and is an invalid cell). Values of one kind order as `sort` orders + them (`expressions.md`, Sorting). A cell not of its column's kind is invalid, sorts last in either direction, + and is reported once for the table at its `sort` path. A sort that is not a list of `{column, direction}` records + naming sortable columns keeps the source order and is reported at the table's `sort` path, so a data error does + not blank the screen. `sortBy` runs before any row's scope exists, as `key` does, so a row-scope name in it reads + `null`. A list of more than 20,000 rows, or of more than 1,000,000 cells (rows times the column parts), is still + ordered, and reported once for the table: `table holds rows; a table over rows is ordered on the client + up to 20,000 rows or 1,000,000 cells — serve it as a model's table`. The page is a slice of the engine's view, so + page 2 holds the second page of the whole sorted list: `pageSize` and `page` are read in the table's scope; a + `pageSize` of `null` does not page, and one that is no positive integer is reported once at its path and does not + page either; a `page` of `null` is the first, one that is negative or no integer is reported once and shows the + first, and one past the last shows the last, unreported, since a filter that shrinks the rows under the user is + normal. The mount reads the page through a `TableSource` whose `alwaysWindowed` is `false`, the path a + model-backed table's mount takes: below the virtualization threshold it realizes every row of the page, as a + short table does, and above it the rows in view. A column with its own `cell` content is lowered in its row's + one scope, found by its key, and is marked in `rowScopedCells`, so a realized row the mount gives to another key + has those cells built again rather than rebound; a plain column's text reads the record alone and is rebound. A + change of the engine's view reaches the mount as the engine's + own operations when the page is the whole view and the table is not grouped, and as a reset otherwise; the + mount rebinds only the rows whose record changed. Each change still costs the lowering a pass over every row: the + view's records are read again for `TableView`, the page's entries are rebuilt, each evaluation of `rows` reads + every field of every row for a unit the screen does not list, and above the virtualization threshold the mount + gives the backend every key (`setExistingKeys`). A `multiple` table's `Ctrl+A` (`Table::onSelectAll`) selects + the engine's whole view, every page, through `table::Selection::selectAll`, or clears the selection when every row + of the view is selected already; a backend that does not take the handler selects the rows it holds. On a user's change of the selection, an `Extend` report keeps + the selected keys of the rows on other pages, in their order, before the reported keys; a `Replace` report is the + whole new selection, so a plain click or a range clears the other pages' keys as it clears the rest of its own, + and every `Single` change is one. A key whose row `rows` no longer has drops on any user change. `empty` shows + while `rows` is empty, not while a page is. + **Its state and its status line.** A table over `rows` with an `id`, while the session has a table-state store and + its `persist` is not `false`, keeps its sort under the key `{application, model "", table , qualifier , part "state"}`: its sort and its column layout. Its rows are held back (`EngineRows::setRestoring`) until the + stored state has been applied and the engine has ordered by it, or until `tableStateTimeout` passes (without a + scheduler, once the work the stored sort posted has run), so the first rows drawn are in the stored order, the + mount drawing placeholder rows meanwhile; a state that arrives later is applied unless the user changed the table + meanwhile. The stored state is fitted to the node's column parts, of the kinds their cells infer, and its layout + is in place in the turn the rows are let through. A sort or layout gesture is saved as a model-backed table's is, + debounced, and an unmount saves at once. A table with no `id` keeps no + state. Its status line shows its counts and the latest message (`ScreenCore::tableMessage`), and takes space only + while it has a message; `status: true` shows it always, and `status: false` never, its messages going to the + host's notifications. + **Saved views.** A table that keeps a state, model-backed or over `rows`, also holds a `TableViews` over the + same key: its `views` part, and its `shared` part when the store shares, loaded in the turn its `state` loads, so + a store that batches reads every part of a screen in one call, and a second mount reads them from the session's + kept copies. A change applies a views operation to the document loaded and saves it with the revision loaded, or + `kNoDocument` when nothing was; a `Conflict` reads the document again from the store, applies the operation to it + and saves once more, with its revision, or with an empty `expected` when nothing is stored; a second `Conflict` + is "Views could not be saved: another window changed them at the same time", and an operation that does not + apply to the document read again ("A view named … exists", "No view named …") saves nothing. A mounted table does + not follow saves made elsewhere. Views that cannot be read are left unsaid at mount. The table's stored state is + applied once both its state and its views have answered: with no stored `state`, the `default` view is applied, + its name the state's `view`; with `defaultOnMount`, the default view's sort and filters replace the stored ones + and the stored layout still applies (`stateAtMount`). Either is fitted as a stored state is. A default view applied + with nothing stored is the table's state from then on (`TableStates::start`), unsaved until the next change, which + saves on top of it, so its layout, sort, filters and name outlast that change. Under `defaultOnMount` the stored + `view` stays, so the menu marks it modified while its sort or filters differ from the default's. A stored `view` + names one of the user's own views: a shared view applied is marked as shared only until the table mounts again. + **The `Views` submenu.** The table menu of a table that keeps a state (model-backed, over `rows` with an `id`, or a + collection) has `Views` (`viewsMenu`): each of the user's own views, checked while it is the state's `view` and + labelled `{name} (modified)` while the arrangement (the layout laid over the table's columns, the sort and the + filters) differs from that view as fitted to the table; then "Save view…", "Rename view…", "Remove view", "Set as + default" (the last three enabled while the state's `view` is one of the user's own) and "Start from the default + view", checked with `defaultOnMount`, which it toggles. Applying a view fits it as a stored state is fitted and sets + its layout, sort and filters through the gestures' own paths (held and saved unless the document binds them, + `onLayoutChange`, `onSortChange` and `onFiltersChange` run), then writes its name to the state's `view`; a filter or + sort key on a column the table lacks is not applied. A table over `rows` knows a column's kind only while the column + is in use, and its engine takes the kind in when it next flushes its changes: the columns a stored state or a view + sorts and filters by are put in use before it is fitted, and its filters (a view whole) go to the engine a task + later. "Save view…", "Rename view…" and "Publish view…" open the view + name dialog (`viewNameDialog`, test id `table_view_dialog`: the input `table_view_name`, the buttons + `table_view_save`, enabled while the name is not blank, and `table_view_cancel`), whose state lives in the + element. Saving under a name the user already has is a `ReplaceView`, any other an `AddView`, decided against the + views document the save is applied to (`TableViews::saveView`), so a name another window took after the table + loaded, met as a `Conflict` and read again, is replaced too; done, the state's + `view` is that name and the status line says "Saved view {name}". A rename onto a taken name is refused in the + status line, "A view named {name} exists", and changes nothing. "Remove view" clears the state's `view`. Every + refusal or failure of a views change goes to the status line, and a change answering after the table is gone + reaches nothing. Every menu choice clears the status line's message first. + **Shared views.** While the store's `shared` part holds views, `Views` adds the heading "Shared views" and each + shared view, applied as an own view is; while the state's `view` is a shared view so applied, "Save as my view" + adds it to the user's views (an `AddView`) and says "Saved view {name}". While the store shares, "Publish view…" + names the arrangement and publishes it (`TableViews::publishView`, the model's `publish` action, never `save`): an + `AddView`, or a `ReplaceView` over a shared view of that name in the shared document it is applied to, as a save + decides; done, "Published view {name}", refused or failed, + "This view could not be published: {reason}". Over a store that does not share, neither entry is offered and no + shared part is read. + **Groups.** With `group`, the source splits its rows into runs by `by` (read per row, untracked: what `by` reads + besides the row regroups the rows when it changes; adjacent rows are one run while their `by` is the same element + as the run's first row's, by the rule of `runs`, quantities compared through the screen's unit table), holds each + row's run index as a hidden leading sort key, and the engine sorts by it first and the sort's keys second, so + every group keeps its place and its rows are ordered inside it. The lowering pages the data rows, and puts a + heading entry before the first row of each run the page holds: the run record of the whole group, so a group + split across pages reads the same `count`, `first` and `last` on both, with its key in a reserved field. The row + view lowers `heading` for that entry as one cell, in a row scope of its own whose row is the record, and the table + makes it a heading row (`TableRowLook::heading`). A heading's key is `"\u001Fgroup:"`, the canonical JSON of the + run's key, `":"` and its ordinal among runs with an equal key, so groups A, B, A get three headings; a data key + equal to one is reported as a duplicate. Heading keys never reach `onSelectionChange`: the lowering drops them + from a report, since a virtualized backend's Ctrl+A or range can name a row it has not realized. `viewCount`, + `selectedCount` and the page positions count data rows. A table lowered where names are bound (a component's + `props`) has a source and an engine of its own, read with those names, which its element values cannot see, and + keeps no state. A row keeps its widget, its native state and its selection while its key stays on the page. Its + header, menus and arrangement are configured as below ("Configuring a table"), its sort bound the node's literal + `maxSortKeys`, else 8. The element value `sort` reads the bound sort or the table's own, `viewCount` the rows the table orders (every page), and `page`, `pageCount`, `pageFirst` and - `pageLast` the page. `filters` and `hoveredKey` are not lowered: the - loader refuses `filters` and `highlightKey` on a table over `rows`. With `empty`, + `pageLast` the page, and `filters` the filters its user set from the header, which the table holds (and keeps in + its persisted state) and does not take from the document: the loader refuses `filters` and `highlightKey` on a + table over `rows`. `hoveredKey` is not lowered. Its `groups` parts are the groups its source declares to the + engine, by which a group filter and a pooled values list name them. With `empty`, the table lowers to a `Column` holding the table and the lowered `empty` content, in the table's own scope: while `rows` evaluates to an empty list the table is hidden and the content shown; while it is a non-empty list, or `null` (a query not answered yet), the reverse. The column takes the node's `visible` and its layout, so it is placed as the table would be, and has no test id; every other common property stays on the table (`testId`, the element id `focus` finds, `enabled`, `tooltip`, `a11y`, `keys`, drag and drop). A hidden table - keeps its element values. No view-tree kind is added, so both backends draw it with what they have. A - model-backed table's `empty` waits for the table engine, as the table does. + keeps its element values. No view-tree kind is added, so both backends draw it with what they have. +- **`table`** of a model's table (`model` and `table`): its rows come by view index from a `WindowRows` + ([`../table/table.md`](../table/table.md), "The client table model"), which the element makes when it is wired, + together with a query of `Table.
.describe` on the model's channel (one per mounted table, an entry of the + query cache like any query). The rows send no page before the description, and none before the stored state + below. The node lowers to a list of one row keyed by the held description's revision, whose row is the `Table` + built from that description (`Table::source`, a `TableSource` over the rows); before a description, and after + one that does not read, the row is a `Table` with no columns and no source, so its status line keeps its place + and `empty` is not shown. A new revision is a new key, so the table is mounted again from it: the rows, their + sort and filters, the selection and the status-line message are the element's and stay; the realized rows, the + cells and the scroll offset are the mount's and are built again. A reply that names another revision than the + one held asks for the description again, once per revision; the fitting of the new one drops a sort key, a + filter and a fetched column that name a column it lacks, and reports a dropped filter once at the table. + Columns are the description's columns but its companions, those it does not show hidden by the layout until the + user shows them, or the node's `columns` parts, each naming a described column by `id` (one it lacks is reported + and left out) and setting its label, width, role, places, `wrap` and `locked`; a column is sortable as the + description says. Its header, menus and arrangement are configured as below ("Configuring a table"), its sort + bound the description's `capabilities.maxSortKeys`, which its server's `limits` set. A column's `cell` is lowered per cell, in a row scope over the cell's own row + signal; without one the cell is a text of the record's field. `rowTone` and `rowLabel` are lowered once per + realized row, in a row scope over the row's signal, which `onActivate` runs in. The rows fetch, with every + page, the description's key and each field `{"row": ""}` names in `rowTone`, `rowLabel` and `onActivate`; a + column's cell's fields (`TableSource::cellReads`) while the column is in the window; and every column when one of + them passes `{"row": ""}` on whole (reported once). A column without a `cell` is the default cell, one text that + follows the column the mount gives it (`defaultCellView`), so a cell of one role serves any column of it. A + path read out of the whole row with `get` is the row's own read: a row scope of a model-backed table has + `RtScope::onMissingRowField`, which a read of a field the record lacks calls from inside the binding; it + writes nothing there, and one task posted for the turn fetches every missed field that is a described column, + once, for the rows in view (a field that is not one is never sent). The read is `null` meanwhile, and the + binding runs again when the column arrives. `body` is evaluated once and is the query's fixed part; its + `query` member's `sort`, `filters`, `page`, `columns`, `keys` and `retry` are the table's own and replace + what the body gives; each the body gives is reported once, at its pointer under `body/query`. A literal `sort` is the default a stored one replaces, any other expression binds it; a + literal `filters` object (`columns` and `groups` only) is likewise the default, an expression binds them. The + headers of the columns the rows' filter names are marked filtered (`Table::filtered`). **Persisted state.** With a session store and `persist` not `false`, + the state's key is `{application, model type, table, persist's name or the screen's id, "state"}`; its load + starts when the element is wired, and the rows wait for it at most `tableStateTimeout`. A state that comes in + time is read (`readState`), fitted to the description held, and its sort, filters and layout applied where the + document binds none of them, before the first query; one that comes later is applied the same way, one more query, + unless the user scrolled, selected or sorted the table meanwhile. A state that does not read is reported once + (`the stored state of table is not used: …`) and a failed load once (`… could not be loaded: …`); the + table starts from its defaults and changes still save. A sort or layout gesture saves its part + (`TableStates::changed`, debounced), and unmounting saves a pending change at once. **The status line** (`Table::status`) always takes + space, unless `status` is `false`: its counts are `countsText` of the rows' counts and the selection's size; a + failed level fills its state with " data could not be loaded." and a failed fetch with "The rows could + not be loaded: ", both with Retry (`WindowRows::retry`). `ScreenCore::tableMessage(table, text)` shows + a refusal or notice there for `kStatusMessageHold` (6 s) on the session's scheduler, until the table's next + gesture (a header click, a menu choice, a column moved or resized, a selection change, a scroll, Retry) clears + it; under `status: false` it goes to + `InterpreterHost::notify` as a warning. A table state's save that does not end `Saved` is said there by every + mounted table with its key: "The table's arrangement could not be saved: ". `empty` shows once a reply + said the view has, exactly, no row and no row is undecided. Its element values are a table's, with + `viewCount` the reply's total (`null` before one), `viewCountKind` (`exact` or `atLeast`), `undecided`, + `awaiting`, `failed`, `pending` (the description or a fetch in flight) and `error`. + **Range selection.** A range the backend reports as two view rows (`Table::onSelectRange`) is resolved + through `TableRows::keysOf`: the rows held give their keys, and every page of the range with a row not held is + fetched naming no columns (`"columns": []`), so its reply carries keys alone and the window holds none of it. + The keys select as the gesture says (`Replace`, or `Extend` with the keys selected), and `onSelectionChange` + runs. A range of more than `SessionOptions::maxRangeRows` (10,000) rows is refused in the status line, "A range + selects at most 10,000 rows" (the number grouped by the locale), and selects nothing. **`highlightKey`.** Each + non-null key, once a description is held, is located by one keyed fetch (`Table.
`, or a typed list + action itself, `keys` the key, `columns` none, the table's sort and filters; `WindowRows::locate`), which stops + the one an earlier key still has in flight; the reply's `indices[0]` is the row's view index, and `Table::highlight` becomes + `TableHighlight{key, index}`, which the mount scrolls to and marks. A reply with no row, and a `null` key, set it + to nothing. A reset of the rows (a new sort or filter) clears it and locates the key again. It never changes + the selection or the keyboard focus. An element in a column's `cell` is focused by the row the cell shows now + (`RtScope::rowKeyNow`), since the mount rebinds a pooled cell to other rows. +- **`table`** over a typed list action (`model` and `action`): lowered as a model's table is, through the same + element state, `WindowRows` (`WindowRowsOptions::action`) and `Table`, with no `describe` query: a catalog carries + an action's request schema and never its reply's, so the description is built when the element is wired, from + the node's `columns` parts (each part's id, its label from the action's view document when that names the + column) or else the view document's `v-columns` (its `field`, `label`, and `v-hidden` as not `shown`). The key + is the node's `key` when it reads one row field (`{"row": ""}`), else the view document's `v-rowKey`, else + `id`. A column's kind is the part's literal `kind`, else its `v-columns` entry's `kind`, else inferred from the + first reply that has rows (`readTypedPage`'s vote over the JSON members of its id) and then fixed for the + window's life: a later member not of it is an invalid cell, and a fractional number makes the column `Number` + where the same number in a document's `rows` is a `Decimal`. The description's revision is empty and never + changes, so the table is mounted once. Every fetch is the action itself, with `body` evaluated once as the + request and the query written into the request's one member the schema marks `x-table` + (`tableQueryMembers`); the reply is a `Page` read with `readTypedPage`, which turns each row object into + cells for every described column, whatever the query named. The rows watch each record the action's catalog + entry names; a reconnect or `resync` of the session drops their pages whether they watch one or none + (`Session::onReconnected` for a window that watches none). A keyed refetch sends `keys` in the query member; a + reply with no `indices` for it drops the window's pages and costs a page refetch. **Units.** A `v-columns` + entry's `ExtUnits` is a unit (`unitAscii` its id, `unitUnicode` its symbol, `x-decimalPlaces` its places) and + each `x-unitAlternatives` entry another of its dimension (`num`/`den` its factor to the first, 1 when absent; a + factor of zero or less is reported and the unit left out), which the description lists; such a `quantity` column + is read as `Measure`. Columns that share a unit share its dimension whatever their order: a column one of whose + units is listed already joins that unit's dimension, its factors scaled through it, and a unit two columns + declare differently is reported and kept as first listed. A unit a reply's member names that the description + does not list is its own canonical unit, in a dimension of its own, as an expression reads a unit missing from + the screen's table, so the cell is a measure in that unit and not an invalid one; a window lists at most + `kMaxUnlistedUnits` (64) such units, the rest staying unknown and their cells invalid. **Filters on + inferred columns.** Until the first reply has fixed the inferred kinds, a filter (stored, literal or bound) is + held, not compiled against the placeholder: the first query goes without it, and once the kinds are fixed the + stored filter is fitted to them (each filter it drops is reported once, "the stored filter on `` is not + applied: it does not apply to the column's kind") and the document's is set, or reported as refused; either is a + second query, so the first page drawn is unfiltered until the second reply arrives. A filter the user set through + the table meanwhile wins over a held literal or stored one; any other gesture (a sort, a scroll) does not, since + a stored state held here arrived in time; a bound filter is the document's and is applied. A held literal or + bound filter is fitted as a stored one is, so a column filter the inferred kind refuses is reported and dropped + and the rest applied, where on a table of known kinds the same filter is refused whole. A filter the rows hold that was compiled against the + placeholders, the user's among them, is fitted again to the inferred kinds, each column filter they refuse + reported ("the filter on `` is not applied: …") and dropped. A stored state set after the kinds are fixed + replaces a filter still held. Persisted state is kept as a model's table's, its `table` the action's id. A node the loader would + refuse (no member marked `x-table`, or neither `columns` nor a view document) is reported at the table when a + catalog that lacks the lookup let it load, and a `key` that is not one row field is reported and the view + document's `v-rowKey`, or `id`, is used. +- **Configuring a table**, of either kind (`ScreenCore::configureTable`, over the `ui/table_config.hpp` gestures; + [`../table/table.md`](../table/table.md), "Configuring a table"). The element keeps the table's columns as its + layout knows them (id, label, `locked`, kind), its declared hidden columns, the layout it holds and what + `configurable` allows, across every mount. A table over `rows` takes its columns when it is made: a derived + `columns` expression is read once there, and a column with no `id` is named `#` by its place, derived columns + first, and locked. `Table::sort` is the whole chain, each key marking its column. + `Table::onSort` maps a plain click to `SortGesture::Click` and `Shift` to `Extend` and applies + `applySortGesture` with the table's bound; a refusal ("A table sorts by at most {n} columns") goes to the status + line and keeps the chain; a change sets the table's own sort when no key binds one, saves it, and runs + `onSortChange` with `event` the new sort, in one batch. A column move (`Table::onColumnMove`, `MoveColumnTo`) + and a resize (`Table::onColumnResize`, `ResizeColumn`, offered only while `resize` is allowed) go through + `applyLayoutGesture` with the columns and what the table allows; a refusal ("{label} is locked", "This table's + columns cannot be moved", …) goes to the status line; a change sets the table's own layout when `layout` binds + none, saves it, and runs `onLayoutChange` with `event` the new layout. `Table::arrangement` follows the layout, + so the mount shows the visible columns in order, pinned and at their widths, and fetches the columns it shows; + a layout that is the declared one is the default arrangement. Unless `configurable` is `false`, `Table::menu` + builds a header's menu (`headerMenu`) or the table's (`tableMenu`) from the chain and the layout of the moment, + and `Table::onMenu` builds it again and carries out the chosen entry: the sort entries as sort gestures, "Move + left" and "Move right" as `MoveColumn` by one, "Pin column", "Unpin", "Hide column" and "Reset columns" as their + layout gestures, and "Columns…" and "Sort…" open the column chooser and the sort dialog (`ui/table_dialogs.hpp`), + which the lowering mounts beside the table in a column that takes the table's layout and visibility; their open + state and the group being formed live in the element, so a new mount keeps them. The chooser lists the table's + columns in the layout's order (a companion is not one of them), and applies `ShowColumn`, `HideColumn`, + `MoveColumn` by one, `ResetColumns`, `FormGroup` and `RemoveGroup`, which also drops the group filter that names + the removed group's columns, as a user's filter change; the sort dialog applies `applySortEdit`, whose + add, remove and direction are the header's sort gestures, so a key past the bound is refused as a Shift-click's + is. Each change goes the way the same gesture from the header goes: refused in the status line, or set, saved and + run through `onLayoutChange` or `onSortChange`. "Display unit" sets or, for the checked unit, clears + `SetDisplayUnit` in the layout. A filterable column (a column part with an id whose `filterable` is not `false`, + on a model's table also one its description marks filterable) draws a filter button (`Table::onFilter`) that, + like its menu's "Filter…", opens its filter menu (`ui/table_filter_menu.hpp`), a `FilterMenu` the element keeps + and a dialog (`table_filter`) mounted beside the chooser; a group, declared or user-formed, is named in its + members' header menus and in the table's menu ("Filter {group}, {k} columns…"), and while its columns stand side + by side in the layout as a header over them (`Table::columnGroups`, `Table::onGroupFilter`), each opening the + group's menu. The menu asks the rows for values (`TableRows::distinctValues`; a table over `rows` keeps the + listed columns in use while it is open); a search asks again, and a condition is sent, + `SessionOptions::tableFilterDebounce` (250 ms) after the last edit, while ticks apply on Apply. It sets the filters through one + path: the rows take them, the table holds them unless the document binds `filters`, they are saved with the + table's state, and `onFiltersChange` runs with `event` the new filters; a refusal goes to the status line. + "Clear all filters" sets empty filters the same way. `Table::filtered` names every column with a filter, a hidden + one included, so the header says so again once it is shown; the filter keeps applying while its column is hidden. + A table with `configurable: false` has no menus, and keeps its filter buttons and their menu. A table that keeps + a state has `Views` in its table menu (see Saved views above). A menu entry the lowering does not carry out is not + offered, and a separator left beside another or at an end goes with it. + `Ctrl+C` (`Table::onCopy`) and the table menu's "Copy" put the selected rows on the clipboard through + `IViewBackend::copyText`: in view order, by the visible columns in layout order, each cell's text as its column + shows it (`formatCell` with the session's formatting and the layout's display units on a model's table; a column + with its own `cell` copies its value's text, not the template's), written by `ui::copyText`, so a tab or line + break in a cell is a space. "Copy with headers" adds a first line of the columns' headers, each with its unit + (`headerText`). With no row selected the focused cell (`Table::onFocusCell`) is copied alone. More than + `SessionOptions::maxCopyRows` (10,000) selected keys are refused in the status line, "A copy holds at most + 10,000 rows", and nothing is copied. A model's table copies the rows its window holds and fetches the others + with `TableRows::fetchRows`: keyed queries naming the copied columns, `maxKeys` keys each, through the read that + makes no cache entry; a key no reply holds is left out. A cell of a level its row has not loaded is copied empty + and counted, and no copy waits for a level. The status line then says "Copied {n} rows", with ", {m} cells were + not loaded" when there were any; a failed fetch says "The rows could not be copied: {reason}", and a backend + whose `copyText` wrote nothing "The rows could not be copied: there is no clipboard". A copy that finds none of + its rows leaves the clipboard and the status line alone, and a copy's rows that arrive after a later copy started + are dropped. The slots a mount sets on the table's configuring (its filter targets, display units and copy + gathering) are cleared when that mount's handlers go, so a slot may hold the mount's scope without keeping the + screen alive. Each + gesture the lowering receives clears the status line's message before it acts, so the next gesture on the + table clears a refusal. The element values `layout`, `visibleColumns` and `hiddenCount` read the layout the + table holds or the document binds, fitted to its columns. - **`boundary`** is a `Switch` over loading, error and children. It owns the queries its children read (found statically, through `let`s, not inside a nested boundary): loading while one has neither a value nor a failure, error when one failed with no value to keep, children otherwise. Inside `error`, @@ -506,6 +794,110 @@ keeps its operands' 0 places and still fills 0.29 of a bar. `bool` as a bool and `number` as a double. An event runs the node's `on.` commands with its payload read as the declared type: `i:`, `s:`, or JSON text. The fallback is lowered too, with `props` bound, for a backend that loads nothing. +- **A grid of a form.** A `table` with `form` and `field` lowers to `ui::makeFormGrid` over the form element's + session and the named collection, made when the table is first lowered and kept in the table's element, so every + mount of the table shows the same grid, its focus, its open editor, its layout, its sort and its filters. Its + columns are the column parts, each editing the member its `field` names, or a display column showing its `value`, + read with `row` bound to the row's record (each member's encoded value, `null` when blank), which the walk skips; + each is labelled by its `label` read once; with no parts, every member of the row type in schema order. A `field` + expression becomes the column's `GridColumn::fieldOf`, read in the row's scope as `value` is, and a name it gives + that is no member is reported once (the cell has no field, so it is read-only); such a column sorts and filters + its drafts as text. The column's `decimals`, `unit`, `readonly`, `options` (each value's JSON literal kept) and + `placeholder` become its per-row overlays, read in the same scope; `FormGridSource` applies `decimals`, `unit`, + `options` and `placeholder` to each row's member (`FieldState::places`, `switchUnit`, `narrowOptions`, + `overridePlaceholder`) in an effect that follows them, a row's `unit` only when it first gives one or gives another + (converting the draft), so a unit the user picks in the editor stays, and `readonly` is the cell's `CellFacts::overlayReadOnly`. + `enterMoves`, `walk`, `appendRows` and `rowsFixed` give its `GridOptions`, with the session's `maxPasteCells`, and + `onActivate` runs with `event` the row's key when `Enter` or a double click lands on a read-only cell. The grid + selects cells (`Table::cellSelection`, bound to `GridController::selection`); a document's bound `selection` is + shown through `GridController::select`, and `onSelectionChange` runs with `event` the range after each change of it + (`GridController::onSelectionChange`); the element value `selection` is the range. `Ctrl+C` on the table copies the + cell selection (`GridController::copy`) through the backend's clipboard, "Copied 2 rows" in the status line (over + `maxCopyRows` rows refused, "A copy holds at most 10,000 rows", by `GridController::copyRefusal`), and + with no cell selection the table's copy runs; `Ctrl+V` pastes the backend's `pasteText` (`GridController::useClipboard`). + The table menu offers the focused row's `GridController::rowEntries` after its own entries and a separator, and + `appendRows` draws "Add row" under the table. What a display column and `onActivate` keep holds the scope weakly. + The grid's `bands` parts become `TableOptions::bands`. A `group` part groups the grid's rows by its `by`, read with + `row` the row's record, over the array's order (`GridRows::setGroup`, `FormRowsSource::setGroup`): a sort the grid + is given is led by `kGroupRunColumn`, so each run keeps its rows, and an empty sort stays empty, since the array's + order already keeps a run together. A grid with a `group` or with `summaries` is mounted over a `SummaryRows` built + over the grid's rows, which the element keeps: the table's `summaries` before (`position: "top"`) or after its rows, + each run's after the run, each run's heading (the group's `heading`, read in the run record's scope, as a `rows` + table's) before it. The grid's walk, paste and cell rectangle stay over the grid's own rows: a click, a move or a + rectangle's corner that lands on a summary or heading row goes to the nearest data row (`SummaryRows::data`), and + the grid's focus is shown at its row's mounted index (`SummaryRows::mounted`). A copy of a rectangle copies the rows + between its corners as they are drawn, a summary row's cells as their text (`GridController::copySummaries`), a + heading row not at all. A summary cell's text is its part's `cells` + expression for the column, read with `rows` the records of the data rows in its scope (`summaryScopeRows` over the + grid's view, so a summary follows the filter) and `column` the column's id, shown at its member's places and empty + for `null`; a column the part does not name shows an empty cell. A summary cell's test id is `summary__`, + a group's `summary___`. Every column's cells are built per row + (`TableSource::rowScopedCells`), so a cell built for a data row is never rebound to a summary row. Its + header, menus, cell menu and arrangement are a table's (`configureTable` over a `TableConfig` the grid keeps): an + edit column whose part says `sortable` sorts by its header, and the sort orders the grid's rows; every edit column + filters unless its part says `filterable: false`, with its header's filter button, its values list, `onFiltersChange` + and the table menu's "Clear all filters"; a display column neither sorts nor filters; the layout (the document's + `layout` while it binds one, else the grid's own, which the header and the column chooser change) arranges the + columns and is fed to `FormGridSource::setLayout`, so the walk follows the visible columns in layout order. The rows' + columns are the edit columns by their own ids, so a sort and a filter name a column as the table does. The cell menu + shows "Copy", "Copy with headers", "Filter by this value" and "Exclude this value", then the grid's "Revert cell" and + "Revert row", then, unless `rowsFixed`, a separator and "Insert row above", "Insert row below" and "Delete row" (or + "Delete rows"), then a separator and the document's `cellMenu` entries, read in a row scope with `row`, `column` and + `value` bound as a table over `rows` reads them. A copy with no row selected copies the focused cell. The scope's + formatting is followed (`FormGridSource::setFormat`). The grid's notices are posted through `tableMessage`, held as + a table's messages are, a repeated one posted again, and what stands while its cause lasts is the status line's + `standing`. A grid the form cannot make (a column naming no member) is reported and drawn as muted text. The form's + `form_submit` submits through `FormSession::submit`, whose before-submit hooks commit the grid's open editor first. + Element values `modifiedCount`, `modifiedRows`, `errorCount` and `editing` read the grid. A form field overlay's + `widget: grid` (or the schema's `x-widget: grid`) draws the field as a grid of every member inside the form's own + view; with a `grid` part, through a `forms::Overrides::byField` for the field, the same table a `table` node with + those keys makes, kept in an element of its own on the form's element (`ElementState::fieldGrids`, by the field's + name, its node the part) so every mount of the form shows the same grid. +- **A fixed grid.** A `table` with `layoutRows` lowers to a `ui::FixedGridSource` over the session of the form + element `form` names (none without `form`) and a `GridController`, made when the table is first lowered and kept in + the table's element as a grid of a form is (`GridTable::fixed`, its controller `GridTable::grid`). Each row part + becomes a `FixedRow`, its `label` read once, and each block part a `FixedBlock` of them; a cell's `field` and `text` + are kept as given, its `rows` and `columns` as counts, and its `value`, `readonly`, `decimals`, `unit`, `options` + (each value's JSON literal kept) and `placeholder` become functions read in the table's scope, with `row` bound to + the block's collection row's record (each member's encoded value) in a block. `FixedGridSource` applies + `decimals`, `unit`, `options` and `placeholder` to each cell's field in an effect that follows them, as + `FormGridSource` applies a grid column's (`detail::applyUnitOverlay` for the unit, given as loaded when first + applied, and again after each load of the form, `FormSession::loadGeneration`, to a field the user has not + changed), and `readonly` is the cell's `CellFacts::overlayReadOnly`. The source keeps one row per row part and per block row and collection row, in order: a block's rows + are expanded again on each change of its collection's rows, keyed `"/"`, so a row's focus, draft and + marks stay with it while collection rows are added above it. Its view is an `EngineRows` over a `table::VectorSource` + of the rows' keys, never sorted or filtered. The columns are the column parts, labelled by their `label` read once, + each of `TableColumn` and `LayoutColumn` kind text and not sortable; `layout` and the column chooser arrange them and + feed `FixedGridSource::setLayout`, so the walk follows the visible columns and a span is cut where they part. Its + walk options, `onActivate`, its cell selection, its copy and paste, its status line and its table menu are a grid of + a form's (`gridOptions`, `gridTableNode`); its copy writes each cell's text as shown, and each row's accessible name + is its label (`TableRowLook::label`). A grid the source cannot make (a field the form lacks at run time) is + reported and drawn as muted text. Element values `modifiedCount`, `modifiedRows`, `errorCount` and `editing` read + it as they read a grid of a form. +- **An editable model column.** A model's table whose description gives a shown column an `EditInfo` mounts through + `GridController::node(columns, options, base)` over a `ModelGridSource`, `base` the `TableSource` the lowering + builds for any model table, so every column keeps its `cell`, tone, tooltip and accent, and each cell draws its + marks from its own row (`markedCell`). No default cell is shared across columns, and a plain cell shows the cell's + draft while one is held. Each editable column's field is `forms::FormModel::fromSchema` over + `Catalog::schema(action)`, `value` of a `CellEdit` and `values.` of a `RowEdit`; a column whose action the + catalog has no schema for has no field, so it is read-only, and one whose schema does not read is reported. A + column is read-only where `Session::can(action)` does not hold, so a principal the server refuses the action sees + it read-only. The rows the mount reads are the source's decorator over the table's rows, which ends a row's + modified marks when the window fetches it. The drafts and commits are the element's `table::CellEdits`, made with + the table: its commit sends through the model alias's calls, never as a run of the session, so the table's own + edits make no row busy, one call per `CellEdit` cell and one per `RowEdit` action with every cell of the request + it edits; a reply's `errors` member, a `FailedRow` of the row or a failure's sentence refuses the cells it names, + and a success whose `ChangedRows` does not name the row counts the row as fetched at once. A changed row's `from` + moves the rows' and the drafts' keys, as a mutation's does, and a keyed refetch that finds a row gone drops its + drafts (`WindowRows::onRowsAbsent`). `editMode` (`cell`, the default, or `row`) chooses when a row's edits are sent; + `enterMoves` and `walk` give the walk, which follows the layout's visible columns. The grid's refusals reach the + status line through `tableMessage` ("This value is not loaded yet", "This row is being saved", a locked row's lock + text, "This cell is read-only"), and the rows' busy and failed states, which are not reactive, reach the cells + through the table's marks revision. The table keeps its row selection: the grid takes no + rectangle of cells, no paste and no fill, and `Delete` blanks the focused cell. Focus follows its row's key through + a key change. Where a focused row the window no longer holds is, and which row takes focus when the focused row + leaves the view, are the mount's, as for any table: the mount locates the row, and hands the grid the key that + took focus. Row mode sends no held cell that became read-only meanwhile. A table with no editable column is lowered as a plain model table. - **A form field's component.** A top-level field whose overlay names a `component` is drawn by it: the form's view is given a `forms::Overrides::byField` per such field, whose render builds the `custom` node `lowerCustom` would, with the field's built-in control as the fallback. The form fills the props it knows: @@ -524,7 +916,12 @@ keeps its operands' 0 places and still fills 0.29 of a bar. another model therefore fails its fetch); `prefill` is followed, each non-null value loading the form as a programmatic change: the first value, and a value whose `key` equals the previous one's, `refill` the form, so a field the user changed keeps what they entered; a new `key`, - or any later value of a form without a `key`, `prefill`s every field. It lowers to `forms::formView` inside a column that + or any later value of a form without a `key`, `prefill`s every field. A form whose model has a computed member + (at any depth), or that names `derive`, makes rounds of derived values (`FormSession::deriveWith`): `evaluate` is + the alias's channel `execute(action, body, {.evaluate = true})` while a member is computed, and `derive` is + `execute(derive, {"body": body})` when the form names one, on the session's timers, `deriveDebounce` (150 ms when + absent) after a grid's last commit; each path a derive reply names that is no derived member is reported once. It + lowers to `forms::formView` inside a column that carries the node's common properties. `title` (a heading over the fields) and `submitLabel` (the explicit-mode button, and the status line's `ready: press
`. + +## Implementer models + +Per the user's standing instructions: Task 1 is fully specified (Haiku). Tasks 0, 0a and 2 need investigation across layers (the Emscripten build, the examples' data access, the dispatcher's handler call) and go to Opus. Every review goes to Opus. + +## Review Focus + +1. **A `columns` list that is not clean.** Duplicates, ids out of the description's order, an id the description lacks next to valid ones, an empty list: the page names each valid column once, in the description's order; an unknown id is `UnknownColumn`; an empty list is a page of keys. Test in Task 1: `"table query: a columns list is answered in the description's order, once each"`. +2. **Numbers JSON cannot hold.** `NaN`, `+inf` and `-inf` in a `Number` column; `INT64_MIN`/`INT64_MAX` integers; a `Rational` whose scaled numerator would overflow: each crosses the wire and reads back as the same cell, so the client keys it as the server did. Test in Task 1: `"generic page: numbers at the edges cross the wire unchanged"`. +3. **A reply that is malformed.** A row whose length differs from `columns`, `keys` and `rows` of different lengths, a `columns` entry the description lacks, a cell `[1, 0]` or `{"x": 1}`: the structural faults refuse the page with a `TableError`; a cell fault keeps the page and makes that one cell invalid. Test in Task 1: `"generic page: a malformed reply is refused and a malformed cell is invalid"`. +4. **The same seed on two machines.** A fixture that agrees with itself on one machine and differs between MSVC and Clang passes every same-process test. Test in Task 0: `"wide table: seed 7 has the pinned digest"`, run in the Windows and Linux CI legs and under Node. +5. **A model whose table function misbehaves.** It throws, or returns a source without a column its description declares: the action replies with an error, the next request to the same model succeeds, and no reply holds a partial page. Test in Task 2: `"table action: a failing table function is an error reply and the model stays usable"`. + +None of the roadmap's Review Focus items falls in this part. + +--- + +### Task 0: The fixture and the baseline (table.md step 0) + +**Files:** +- Create: `tests/table/wide_table_model.hpp`, `tests/table/wide_table_model.cpp` (static library `morph_wide_table_model`), `tests/table/test_wide_table.cpp` (in `morph_table_tests`), `tests/qt_quick/bench_qt_quick_table.cpp` (in `morph_qt_quick_tests`), `tests/qt_quick/wide_rows_document.hpp` (the `rows` document F2–F5 and B5 both mount), `tests/qt_quick/wasm/wide_rows_baseline.cpp` and `tests/qt_quick/wasm/CMakeLists.txt` (B5's browser harness) +- Modify: `include/morph/table/data_source.hpp:71-76` (`QuantityCell` gains `[[nodiscard]] bool operator==(QuantityCell const&) const = default;` with its Doxygen, so `Cell == Cell` compiles; index decision 38), `tests/table/table_fixtures.hpp` (`tabletest::sameCell`) +- Modify: `CMakeLists.txt:1252` (an `if(EMSCRIPTEN AND MORPH_BUILD_QT_QUICK AND MORPH_BUILD_TESTS)` branch adding `tests/qt_quick/wasm`), `tests/CMakeLists.txt:882-909` (the library; `morph_table_tests` links it and `test_wide_table.cpp`; `morph_tests` links it; an `if(EMSCRIPTEN)` branch that builds only `morph_wide_table_model` and `morph_table_tests`), `tests/net/CMakeLists.txt:13-17`, `tests/qt_quick/CMakeLists.txt` (link and the bench file), `tests/table/bench_table.cpp`, `tests/bench_interpreter.cpp`, `tests/table/test_table_engine.cpp:210` (tag `[threads]`), `.github/workflows/ci.yml` (new job `table-wasm`), `docs/spec/table/table.md` (a "Recorded baselines" table at the end of "Performance", before "## Invariants") + +**Interfaces:** +- Consumes: `table::DataSource`, `RowSnapshot::readColumn`, `ColumnSink`, `table::apply`, `Engine` (all existing, `include/morph/table/`). +- Produces (namespace `bench`, header `tests/table/wide_table_model.hpp`): + +```cpp +enum class WideRole : std::uint8_t { Key, Integer, Decimal, Quantity, Measure, Text, LongText, Date, DateTime, Bool }; + +struct WideColumn { + morph::table::ColumnInfo info; // id and kind; Measure-role columns are ColumnKind::Decimal until Task 8c + WideRole role; + bool sparse = false; // 10% of its cells empty + std::string level; // "recipe" or empty; used from Task 2 on (ColumnInfo::level lands in Task 3) + std::string group; // "g3", "g16" or empty +}; + +struct WideTableOptions { + std::int64_t rows = 100'000; + int columns = 300; // 300 or 30; anything else throws std::invalid_argument + std::uint64_t seed = 1; + std::chrono::microseconds loadDelay{0}; // read by the slow level from Task 5 on +}; + +[[nodiscard]] std::uint64_t cellBits(std::uint64_t seed, std::string_view column, std::int64_t row) noexcept; +[[nodiscard]] std::vector wideColumns(int columns); +[[nodiscard]] std::size_t approximateCellBytes(morph::table::Cell const& cell) noexcept; + +class WideTableSource final : public morph::table::DataSource { +public: + explicit WideTableSource(WideTableOptions options); + std::span columns() const override; + std::shared_ptr snapshot() const override; + void subscribe(morph::table::ChangeListener& listener) override; + void unsubscribe(morph::table::ChangeListener& listener) override; + [[nodiscard]] std::vector const& layout() const noexcept; + [[nodiscard]] WideTableOptions const& options() const noexcept; + [[nodiscard]] std::size_t residentBytes() const noexcept; // bytes of the column arrays, capacity included + void setCell(std::int64_t row, std::string_view column, morph::table::Cell value); // copy-on-write of that one column; notifies Updated + void regenerate(std::uint64_t seed); // notifies Reset + // snapshot(), setCell() and regenerate() hold one mutex around reading or swapping the snapshot pointer; listeners are + // notified after the lock is released. The source is shared by every model instance's strand (Part B's fifty clients). +}; +``` + +- Produces (namespace `tabletest`, `tests/table/table_fixtures.hpp`): `[[nodiscard]] inline bool sameCell(morph::table::Cell const& a, morph::table::Cell const& b)`, true when both hold the same alternative and equal values, and, for a `Rational`, equal `decimalPlaces` too (for a `QuantityCell`, of `amount` and of `toCanonical`). `Rational::operator==` compares the value only (`util/rational.hpp:692`), so `Cell == Cell` means "the same value" and `sameCell` means "the same cell, places included"; a test that pins places uses `sameCell`. + +**The layout** (`wideColumns(300)`, in declared order; position `p` counts from 0): + +| Ids | Role, kind | Count | +|---|---|---| +| `id` | `Key` role, `ColumnKind::Integer`, the row key, value `row + 1`, never empty | 1 | +| `i001`…`i099` | Integer | 99 | +| `d000`…`d059` | Decimal; `d000`…`d009` have `level = "recipe"` | 60 | +| `q000`…`q029` | Quantity, canonical unit gram | 30 | +| `m000`…`m009` | Measure role, `ColumnKind::Decimal` | 10 | +| `t000` | LongText, `ColumnKind::Text` | 1 | +| `t001`…`t069` | Text; `t001`…`t010` have `level = "recipe"`; `t004`…`t006` have `group = "g3"`; `t011`…`t026` have `group = "g16"` | 69 | +| `a000`…`a009` | Date | 10 | +| `s000`…`s009` | DateTime | 10 | +| `b000`…`b009` | Bool | 10 | + +`sparse` is true exactly when `p % 12 == 11` (25 columns). `wideColumns(30)` keeps, in the same order, `id`, `i001`…`i009`, `d000`…`d005`, `q000`…`q002`, `m000`, `t000`…`t006`, `a000`, `s000`, `b000`, each with every attribute it has in the 300 layout, `sparse` included, so a column shared by `wide` and `small` has the same cells in both (table.md, "The fixture": the two tables share the rows they have in common). + +**The generator.** A cell depends only on `(seed, column id, row)`, so `wide` and `small` agree on the rows and columns they share: + +```cpp +// splitmix64: z += 0x9E3779B97F4A7C15; z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9; +// z = (z ^ (z >> 27)) * 0x94D049BB133111EB; return z ^ (z >> 31); +cellBits(seed, column, row) = splitmix64(splitmix64(seed ^ fnv1a64(column)) + static_cast(row)); +``` + +`fnv1a64` is `morph::model::detail::fnv1a64` (`include/morph/core/payload_schema.hpp:213`). With `b = cellBits(...)`: a sparse column's cell is empty when `b % 10 == 0`; otherwise by role — +Integer `static_cast(b % 2'000'001) - 1'000'000`; +Decimal `Rational{Numerator{static_cast(b % 20'000'001) - 10'000'000}, Denominator{100}, DecimalPlaces{2}}`; +Quantity with `n = b % 10'000'001`: when `(b >> 32) & 1` a `QuantityCell{Rational{n, 1'000'000, 6} /* kg */, Rational{1000, 1, 0}}`, otherwise `Rational{n, 1000, 3}` (grams); +Measure role `Rational{static_cast(b % 1'000'001), 100, 2}`; +Text: length `4 + b % 57` (LongText: `200 + b % 1801`) characters, each the entry `syllables[splitmix64(b + i) % 32]` of the fixed table `{"a","e","i","o","u","b","c","d","f","g","k","l","m","n","p","r","s","t","v","z","É","é","Ä","ä","Ö","ø","Ü","ç","ß","Z","K","M"}`, truncated to the length in UTF-8 code points; +Date `static_cast(b % 20'000)`; DateTime `static_cast(b % 1'700'000'000)`; Bool `(b & 1) != 0`. + +**The column store.** One typed array per column (`std::vector` for integer, date, date-time, decimal numerators at a fixed denominator and quantity numerators; one `std::uint8_t` unit flag for quantities and one for booleans; texts as one `std::string` pool with `std::uint32_t` offsets; a `std::vector` empty mask for sparse columns), generated once in the constructor. The snapshot holds `std::shared_ptr` to each column's arrays; `readColumn` converts into a local buffer of 256 cells and hands each run to the sink in one `cells` call. + +- [ ] **Step 1: Write the failing tests** in `tests/table/test_wide_table.cpp` + +```cpp +TEST_CASE("wide table: the same seed gives the same cells", "[table][wide]") { + bench::WideTableSource const a{{.rows = 1'000, .columns = 300, .seed = 7}}; + bench::WideTableSource const b{{.rows = 1'000, .columns = 300, .seed = 7}}; + auto const sa = a.snapshot(); auto const sb = b.snapshot(); + REQUIRE(sa->rowCount() == 1'000); + for (std::size_t r = 0; r < 1'000; ++r) { + REQUIRE(sa->rowId(r) == sb->rowId(r)); + for (std::size_t c = 0; c < 300; ++c) { REQUIRE(tabletest::sameCell(sa->cell(r, c), sb->cell(r, c))); } // Mutation: seed from std::random_device + } + bench::WideTableSource const other{{.rows = 1'000, .columns = 300, .seed = 8}}; + CHECK_FALSE(other.snapshot()->cell(0, 1) == sa->cell(0, 1)); // Mutation: generator ignoring the seed +} + +TEST_CASE("wide table: the column mix is the spec's", "[table][wide]") { + auto const roles = [](int n) { std::map count; for (auto const& c : bench::wideColumns(n)) ++count[c.role]; return count; }; + auto const wide = roles(300); + CHECK(wide.at(bench::WideRole::Key) + wide.at(bench::WideRole::Integer) == 100); + CHECK(wide.at(bench::WideRole::Decimal) == 60); + CHECK(wide.at(bench::WideRole::Quantity) == 30); + CHECK(wide.at(bench::WideRole::Measure) == 10); + CHECK(wide.at(bench::WideRole::Text) + wide.at(bench::WideRole::LongText) == 70); + CHECK(wide.at(bench::WideRole::LongText) == 1); + CHECK(wide.at(bench::WideRole::Date) + wide.at(bench::WideRole::DateTime) == 20); + CHECK(wide.at(bench::WideRole::Bool) == 10); + auto const columns = bench::wideColumns(300); + CHECK(std::ranges::count_if(columns, &bench::WideColumn::sparse) == 25); + CHECK(std::ranges::count(columns, std::string{"recipe"}, &bench::WideColumn::level) == 20); + CHECK(std::ranges::count(columns, std::string{"g3"}, &bench::WideColumn::group) == 3); + CHECK(std::ranges::count(columns, std::string{"g16"}, &bench::WideColumn::group) == 16); + CHECK(bench::wideColumns(30).size() == 30); + // One column in twelve has 10% empty cells: 1,000 rows of a sparse column hold between 50 and 150 empties. + bench::WideTableSource const source{{.rows = 1'000, .columns = 300, .seed = 7}}; + auto const snap = source.snapshot(); + auto const empties = [&](std::size_t c) { int n = 0; for (std::size_t r = 0; r < 1'000; ++r) n += std::holds_alternative(snap->cell(r, c)); return n; }; + CHECK(empties(11) > 50); CHECK(empties(11) < 150); // position 11 is sparse + CHECK(empties(0) == 0); // `id` is never empty + // Mutation: sparse every 11th column instead of every 12th. +} + +TEST_CASE("wide table: shared rows agree between 300 and 30 columns", "[table][wide]") { + bench::WideTableSource const wide{{.rows = 2'000, .columns = 300, .seed = 7}}; + bench::WideTableSource const small{{.rows = 1'000, .columns = 30, .seed = 7}}; + auto const ws = wide.snapshot(); auto const ss = small.snapshot(); + auto const wideIds = wide.columns(); + int empties = 0; + for (std::size_t c = 0; c < small.columns().size(); ++c) { + auto const at = std::ranges::find(wideIds, small.columns()[c].id, &morph::table::ColumnInfo::id); + REQUIRE(at != wideIds.end()); + auto const w = static_cast(at - wideIds.begin()); + CHECK(small.layout()[c].sparse == wide.layout()[w].sparse); + for (std::size_t r = 0; r < 1'000; ++r) { + REQUIRE(tabletest::sameCell(ss->cell(r, c), ws->cell(r, w))); + empties += std::holds_alternative(ss->cell(r, c)) ? 1 : 0; + } + } + CHECK(empties > 0); // `t003` is sparse in both layouts, so empty cells were compared + // Mutation: wideColumns(30) recomputing `sparse` from the 30 layout's positions. + // Mutation: hashing the column's position instead of its id. +} + +TEST_CASE("table fixtures: sameCell tells places apart and operator== does not", "[table][wide]") { + using morph::math::Rational; using morph::math::Numerator; using morph::math::Denominator; using morph::math::DecimalPlaces; + Cell const two{Rational{Numerator{5}, Denominator{2}, DecimalPlaces{2}}}; + Cell const four{Rational{Numerator{5}, Denominator{2}, DecimalPlaces{4}}}; + CHECK(two == four); + CHECK_FALSE(tabletest::sameCell(two, four)); + CHECK(tabletest::sameCell(two, two)); + Cell const kg{QuantityCell{std::get(two), Rational{Numerator{1000}, Denominator{1}, DecimalPlaces{0}}}}; + Cell const g{QuantityCell{std::get(two), Rational{Numerator{1}, Denominator{1}, DecimalPlaces{0}}}}; + CHECK(kg == kg); + CHECK_FALSE(kg == g); // Mutation: QuantityCell::operator== comparing `amount` only + CHECK_FALSE(tabletest::sameCell(two, Cell{std::int64_t{2}})); // Mutation: sameCell delegating to operator== +} + +TEST_CASE("wide table: seed 7 has the pinned digest", "[table][wide]") { + // FNV-1a 64 over displayText(cell) of rows 0..999, columns 0..299, each followed by '\x1f'. + CHECK(bench::digestForTesting(bench::WideTableSource{{.rows = 1'000, .columns = 300, .seed = 7}}) == kPinnedDigest); + // kPinnedDigest is computed once by the implementer on MSVC and checked unchanged by the Linux leg and Node. + // Mutation: a std::uniform_int_distribution in the generator (passes on one standard library, fails on another). +} + +TEST_CASE("wide table: apply reads only the sorted and filtered columns", "[table][wide]") { + // Gate S3. A RecordingSource wraps a WideTableSource{1'000, 300, 7}; its snapshot counts cells handed out per column + // through both cell() and readColumn(). + // Query: sort {i001 asc}, filter t001 contains "a", page {0, 200}. + // CHECK: counts[i001] == 1'000, counts[t001] == 1'000, and the other 298 counts are 0. + // Mutation: apply listing every column in JobInput::needed. +} + +TEST_CASE("wide table: an edit changes one cell and copies one column", "[table][wide]") { + // setCell(5, "i001", Cell{std::int64_t{42}}): the new snapshot's cell(5, i001) is 42; the snapshot taken before + // still reads the old value; a subscribed listener got one RowChange{Updated, {5}}. + // Mutation: setCell writing into the shared array (the old snapshot changes too). +} +``` + +`bench::digestForTesting(WideTableSource const&) -> std::uint64_t` is declared in the fixture header for this test. + +- [ ] **Step 2: Run them to see them fail** + +Run: `cmake --preset cl-debug && cmake --build --preset cl-debug --target morph_table_tests` +Expected: compile failure, `wide_table_model.hpp` not found (add `table/test_wide_table.cpp` to `morph_table_tests` in `tests/CMakeLists.txt` first, so the build sees it). + +- [ ] **Step 3: Implement the fixture** in `tests/table/wide_table_model.{hpp,cpp}` with the interface, layout and generator above, `QuantityCell::operator==` in `data_source.hpp`, `tabletest::sameCell` in `table_fixtures.hpp`, and add to `tests/CMakeLists.txt`: + +```cmake +add_library(morph_wide_table_model STATIC table/wide_table_model.cpp) +target_link_libraries(morph_wide_table_model PUBLIC morph::morph) +target_include_directories(morph_wide_table_model PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +apply_warnings(morph_wide_table_model) +``` + +`morph_table_tests`, `morph_tests`, `morph_net_tests` and `morph_qt_quick_tests` link it as `"$"` (the ladder's precedent, `cmake/morph_add_rung.cmake:209`), so the registrars Task 2 adds are never dropped. Tag the case at `tests/table/test_table_engine.cpp:210` `[threads]`. + +- [ ] **Step 4: Run the tests to see them pass** + +Run: `cmake --build --preset cl-debug --target morph_table_tests && ctest --test-dir build/cl-debug -R "wide table" --output-on-failure` +Expected: 6 tests pass, and `ctest --test-dir build/cl-debug -R "table fixtures" --output-on-failure` 1 more; then the rest of the target: `ctest --test-dir build/cl-debug -R "^table" --output-on-failure` all pass. + +- [ ] **Step 5: Build the table tests for WebAssembly and run them under Node** + +In `tests/CMakeLists.txt`, at the top after the pinned-facts block: under `if(EMSCRIPTEN)`, define `morph_wide_table_model` and `morph_table_tests` exactly as above, register no `catch_discover_tests`, and `return()`. Emscripten's default heap is a fixed 16 MiB and no target in this repository sets another, so the branch also gives the executable a heap that grows: + +```cmake +target_link_options(morph_table_tests PRIVATE -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=4GB) +``` + +That holds the 100,000 × 300 column store B2 runs S1 and S2 over. S8's `VectorSource` of the same rows (near 1.7 GB of cells, and its keys beside them) is native only: its case is compiled out under `__EMSCRIPTEN__`. Add to `.github/workflows/ci.yml` a job: + +```yaml + table-wasm: + name: Table tests (WebAssembly, Node) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: mymindstorm/setup-emsdk@v14 + with: { version: 4.0.7 } + - name: Configure + run: emcmake cmake -S . -B build-wasm -G Ninja -DCMAKE_BUILD_TYPE=Release -DMORPH_BUILD_TESTS=ON -DMORPH_BUILD_EXAMPLES=OFF + - name: Build + run: cmake --build build-wasm --target morph_table_tests + - name: Run + run: node build-wasm/tests/morph_table_tests.js "~[threads]" +``` + +Run locally (with emsdk active): the same three commands. +Expected: `All tests passed` with the digest case among them. If a header of `morph::morph` does not build under Emscripten, the fix belongs to this commit (AGENTS.md: build configuration is fixed in the change that needs it); a defect in `include/morph` found this way is filed. + +- [ ] **Step 6: Write the baseline benchmarks** + +Each case is `"[.benchmark][baseline]"`, prints Markdown rows as `bench_table.cpp`'s `printRow` does, and first `REQUIRE`s the guard in the last column. + +| Id | File, case name | What it times or counts | Guard | +|---|---|---|---| +| S1 | `bench_table.cpp`, `"table baseline: S1 S2 S7 over the wide table"` | `apply`, sort `d000` asc, page {0, 200}, 100,000 × 300 | the page has 200 rows and the view 100,000 | +| S2 | same case | `apply`, filter `t001` contains `"ka"` | the view is neither empty nor all rows | +| S7 | same case | ten consecutive `apply` calls of S1's query, offsets 0, 200, … 1,800: total and per call | each page's first key differs | +| S8 | `bench_table.cpp`, `"table baseline: S8 resident bytes"` | `WideTableSource::residentBytes()` at 100,000 × 300, and the sum of `approximateCellBytes` over the same rows held as a `VectorSource` | the `VectorSource` has 100,000 rows | +| B1 | `bench_table.cpp`, `"table baseline: B1 client mode with no worker"` | an `Engine` over `WideTableSource{rows, 30}` with an owner and no worker, at 10,000, 20,000, 100,000 rows: sort on `a000` asc, `d000` desc, `i001` asc, then filter `t001` contains `"ka"`; request to result, and the longest owner step | the view's first row changed after the sort | +| B2 | the S1, S2 and B1 cases and W2's decode (Task 1) | run under Node from the `table-wasm` build: `node build-wasm/tests/morph_table_tests.js "[.benchmark][baseline]"`; recorded as a factor over native | as the native case | +| W7 | `bench_table.cpp`, `"table baseline: W7 as a typed page"` | bytes and encode time of a page of 200 rows × 300 columns written as row objects keyed by column id, each cell as glaze writes the typed member (`Rational` as its `{"num","den","dp"}` object) | the page holds 60,000 cells | +| U1 | `tests/bench_interpreter.cpp`, `"interpreter baseline: U1 U2 a rows table of 100,000"` | a `ui/1` document whose `table` reads state `items` (100,000 rows of `id`, `name` from `t001`, `qty` from `i001`) and binds `sort` to state `order`; a button sets `order` to `[{"column":"name","direction":"asc"}]`; click to settled | the first rendered row's `name` changed | +| U2 | same case | the sorted table, a button replacing one row's `name` in `items`; click to settled | that row moved | +| U3 | `bench_interpreter.cpp`, `"interpreter baseline: U3 folds per sort"` | the U1 sort with a counting collator installed where the interpreter takes its collator; folds performed | the count is above 100,000 | +| U4 | `bench_interpreter.cpp`, `"interpreter baseline: U4 memory of a rows table"` | 10,000 × 300 rows as document values, sorted on one column: `approximateCellBytes` sum against the document's value bytes | the table mounted with 10,000 rows | +| U5 | `bench_interpreter.cpp`, `"interpreter baseline: U5 a collection of 20,000"` | a forms-engine collection over a `ListRows` reply of 20,000 rows, as `tests/test_forms_engine_collection.cpp` builds one: mount, sort, one row edited | the collection holds 20,000 rows | +| F2–F5 | `tests/qt_quick/bench_qt_quick_table.cpp`, `"qt quick baseline: F2 to F5 on a rows table of 2,000 x 300"` | a `rows` table of `WideTableSource{2'000, 300}` cells in a 1,280 × 800 offscreen window: widgets alive (F2), frame time of vertical (20 rows/s, 2,000 rows/s, thumb drag) and horizontal (10 and 100 columns/s) scrolls timed as table.md "How a frame is timed" says for CI (F3, F4), memory per realized row (F5) | the table realized at least 30 rows | +| B5 | `tests/qt_quick/wasm/wide_rows_baseline.cpp` | a Qt WebAssembly executable (`tests/qt_quick/wasm/CMakeLists.txt`, reached from the root branch below) that mounts F2's table, scrolls one screen and prints mount time and the scroll's frame times to the console; run locally in a headless browser with `emrun --browser chrome --browser_args=--headless=new` | its console shows 2,000 rows mounted | + +- [ ] **Step 7: Record the baselines** + +Run on a Release build, machine load recorded: +`cmake --preset cl-release && cmake --build --preset cl-release --target morph_table_tests morph_tests` +`build/cl-release/tests/morph_table_tests.exe "[.benchmark][baseline]"` and `build/cl-release/tests/morph_tests.exe "[.benchmark][baseline]"`; +`cmake --preset cl-qt-release -DMORPH_BUILD_QT_QUICK=ON && cmake --build --preset cl-qt-release --target morph_qt_quick_tests`, then with `QT_QPA_PLATFORM=offscreen`: `build/cl-qt-release/tests/qt_quick/morph_qt_quick_tests.exe "[.benchmark][baseline]"`; +B2 under Node as in the table above. B5: in the root `CMakeLists.txt`, beside `:1252` (which adds `tests/qt_quick` only when `NOT EMSCRIPTEN`), add `if(EMSCRIPTEN AND MORPH_BUILD_QT_QUICK AND MORPH_BUILD_TESTS) add_subdirectory(tests/qt_quick/wasm) endif()`; configure with the form of `.github/workflows/wasm-demo.yml:114-119`: `"$WASM/bin/qt-cmake" -S . -B build-wasm-qt -G Ninja -DCMAKE_BUILD_TYPE=Release -DQT_HOST_PATH="$HOST" -DMORPH_BUILD_TESTS=ON -DMORPH_BUILD_EXAMPLES=OFF -DMORPH_BUILD_QT=ON -DMORPH_BUILD_QT_QUICK=ON`, build `cmake --build build-wasm-qt --target wide_rows_baseline`, and run it with `emrun` as the table says. (The `if(EMSCRIPTEN)` branch of `tests/CMakeLists.txt` returns before anything else, so this build compiles only `morph_table_tests`, its fixture and this harness.) +The B5 harness, so that nothing in it is left to choose: + +- `tests/qt_quick/wide_rows_document.hpp`: `namespace bench { [[nodiscard]] std::string wideRowsDocument(WideTableSource const& source); }`, the `ui/1` document text of one `table` whose `rows` are the source's cells as literal row objects keyed by column id and whose `columns` are its 300 ids. `bench_qt_quick_table.cpp` (F2–F5) and the harness both mount this text, so B5 measures the table F2 measures. +- `tests/qt_quick/wasm/CMakeLists.txt`: + +```cmake +qt_add_executable(wide_rows_baseline wide_rows_baseline.cpp) +target_link_libraries(wide_rows_baseline PRIVATE morph::qt_quick morph_wide_table_model) +target_include_directories(wide_rows_baseline PRIVATE ${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/tests) +target_link_options(wide_rows_baseline PRIVATE -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=4GB) +apply_warnings(wide_rows_baseline) +``` + +- `wide_rows_baseline.cpp`: a `main` that owns the `QGuiApplication` and a 1,280 × 800 window as `tests/qt_quick/test_qt_quick_main.cpp` and `qt_quick_harness.hpp` set one up, mounts `wideRowsDocument(WideTableSource{{.rows = 2'000, .columns = 300, .seed = 7}})`, and on the first frame after the mount prints `mounted rows=2000 ms=`; it then scrolls the table down by one viewport over one second and prints `frame ms=` per frame and `done` at the end. It links no Catch2: its guard is the `mounted rows=2000` line. + +Expected: every case prints its rows and none fails its guard. Add to table.md, at the end of "Performance": + +```markdown +### Recorded baselines + +| Id | Step | Figure | Machine, load | Date | +|---|---|---|---|---| +``` + +one row per figure (S1, S2, S7, S8, B1 ×3 native, B2 for S1, S2, B1 ×3 and W2 under Node, B5, U1–U5, W7, F2–F5), the figure as median and p10–p90. + +- [ ] **Step 8: Mutations, then commit** + +Apply each mutation named in Step 1, see its test fail, revert; paste the failing lines into the commit body. + +```bash +git add include/morph/table/data_source.hpp tests/table/table_fixtures.hpp \ + tests/table/wide_table_model.hpp tests/table/wide_table_model.cpp tests/table/test_wide_table.cpp \ + tests/table/bench_table.cpp tests/table/test_table_engine.cpp tests/bench_interpreter.cpp \ + tests/qt_quick/bench_qt_quick_table.cpp tests/qt_quick/wide_rows_document.hpp tests/qt_quick/wasm tests/qt_quick/CMakeLists.txt \ + CMakeLists.txt tests/CMakeLists.txt tests/net/CMakeLists.txt .github/workflows/ci.yml docs/spec/table/table.md +git commit -m "test(table): wide-table fixture and baselines" +``` + +--- + +### Task 0a: Remove paging in a database (table.md step 0a) + +**Files:** +- Delete: `include/morph/table/plan_conformance.hpp`, `tests/table/test_table_database_pages.cpp`, `examples/lims/org/include/lims/org/core/plan_sql.hpp`, `docs/spec/table/database_pages.md` +- Modify: `include/morph/table/query.hpp:1-16` (file comment: "or with a database query that honours the same semantics" goes), `:252-268` (`escapeLikePattern` goes), `:354-592` (the "Query plans" section: `PlanUse`, `FilterOp`, `PlannedOperand`, `PlannedSortKey`, `PlannedCondition`, `PlannedColumnFilter`, `PlannedGroup`, `QueryPlan`, `detail::plannedOperand`, `detail::plannedCondition`, `detail::plannedColumnFilter`, `detail::untranslatable`, `planQuery`); no `QueryLimits` member is used only by plans, so `QueryLimits` is unchanged +- Modify: `include/morph/table/filter.hpp:645` (the comment becomes "The one compile step `apply` and `Engine` share, so a throwing service is an error value in both."), `CMakeLists.txt:722`, `tests/CMakeLists.txt:36`, `tests/table/test_table_query.cpp` (receives the moved cases; loses `"table: LIKE patterns keep % and _ ordinary"`) +- Modify: `docs/spec/table/engine.md:52-53` (the `query.hpp` row loses `escapeLikePattern`, `QueryPlan`, `planQuery`; the `plan_conformance.hpp` row goes), `:300-306` and `:311-312` (see Step 5), `docs/spec/README.md:138-139` +- Modify: `examples/lims/lab/include/lims/lab/models/sample_model.hpp:96-110`, `examples/lims/lab/src/models/sample_model.cpp:280-390`, `examples/lims/ledger/include/lims/ledger/models/ledger_model.hpp:166-191`, `examples/lims/ledger/src/models/ledger_entries.cpp:535-580`, `examples/lims/tests/test_sample_pages.cpp`, `examples/lims/tests/test_ledger_entries.cpp:1440-1785`, `examples/lims/README.md:1795-1846` + +**Interfaces:** +- Consumes: `table::apply(std::vector const&, RowKey, TableQuery const&, ApplyOptions const&)` (`query.hpp:891`), `validate` (`query.hpp:228`). +- Produces: `lims::SampleModel::pageSamples(std::vector const& sites, ::morph::table::TableQuery const& query) -> ::morph::table::Page` and `lims::LedgerModel::pageEntries(CompanyId company, ::morph::table::TableQuery const& query) -> ::morph::table::Page`, each throwing `ValidationError{": " + error.message}` on a `TableError`. `canTranslateSampleColumn` and `canTranslateEntryColumn` go. + +**Test inventory.** `tests/table/test_table_database_pages.cpp` holds 14 cases: + +| Case | Fate | +|---|---| +| `"table: a total is exact or a lower bound, and a lower bound does not end the window"` | Moved to `test_table_query.cpp`, tag `[table][query]`, with its mutation line ("`PageWindow` stopping at an `AtLeast` total") | +| `"table: a total kind goes over the wire by name"` | Moved, tag `[table][query]` | +| `"table: a plan is refused as apply refuses"` | Replaced by `"table: apply refuses what validate and compile refuse, by code"` (below); its other queries are already pinned by `"table: an untrusted query is bounded"` and `"table: a column the principal may not read is refused"` | +| `"table: a throwing collator is a ServiceFailed error from planQuery"` | Deleted: `"table: a collator that throws while the filter compiles is a ServiceFailed error from apply"` (`test_table_query.cpp:457`) pins the shared step | +| `"table: a model that follows the plan answers as apply does"`, `"…the conformance helper reports a model that disagrees with apply"`, `"…a model refuses what it cannot translate with Unavailable"`, `"…a plan carries the clamped page, the cap and operands typed by their column"`, `"…the standard corpus filters every column kind with operands that parse"`, `"…an exact total above the cap must equal the true count"`, `"…the corpus holds a translation to non-integral operands on integer columns"`, `"…the corpus writes date operands the date parser reads"`, `"…the corpus holds a translation to the floor of a negative instant"`, `"…the helper reports a column whose queries every side refused"` | Deleted with the file (they test plans, the corpus or the helper) | + +In the lims tests: + +| File, case | Fate | +|---|---| +| `test_sample_pages.cpp`, `"lab: a page of samples from the database equals the engine's page over the same rows, for every sort and filter the list offers"` | Deleted (SQL translation against `apply`) | +| `test_sample_pages.cpp`, `"lab: a plan the statement cannot translate is refused"` | Deleted | +| `test_sample_pages.cpp`, `"lab: the sample list answers through the action with an exact total"` | Kept unchanged: it pins scope (bob's total is his sites' rows) and the unknown-column refusal | +| `test_ledger_entries.cpp`, the four `"ledger: a page of entries from the database equals the engine's page … (part N of 4)"` | Deleted, with `checkEntryPagesAgainstEngine`, `kCorpusParts`, `dateQueries`, `groupQueries` | +| `test_ledger_entries.cpp`, `"ledger: the entry page refuses the columns the database cannot compare, and nothing else"` | Deleted | +| `test_ledger_entries.cpp`, `"ledger: text operands that look like SQL or like patterns are only data"` | Deleted | +| `test_ledger_entries.cpp`, `"ledger: a page of entries is the caller's, with an exact total from the database"` | Kept; renamed `"ledger: a page of entries is the caller's, with an exact total"`; it pins scope (dave gets no row) | + +A helper left with no caller (`journalRowsFromLedger`, `visibleViews`, the sample `dateQueries`, anything in `lims_test_support.hpp` only these cases used) is deleted; the compiler's unused-function warning finds them. + +- [ ] **Step 1: Move the cases and write the replacement** in `tests/table/test_table_query.cpp` + +```cpp +TEST_CASE("table: apply refuses what validate and compile refuse, by code", "[table][query]") { + auto const source = tabletest::makeSource({tabletest::col("id", ColumnKind::Key), tabletest::col("n", ColumnKind::Integer)}, + {{Cell{std::int64_t{1}}, Cell{std::int64_t{5}}}}); + auto const code = [&](TableQuery const& q) { auto r = apply(*source, q); REQUIRE_FALSE(r.has_value()); return std::pair{r.error().code, r.error().column}; }; + TableQuery far; far.page.offset = 10'000'001; + CHECK(code(far).first == TableErrorCode::LimitExceeded); + CHECK(code(withFilter("n", FilterEntry{.contains = "1"})) == std::pair{TableErrorCode::UnsupportedOperator, std::string{"n"}}); + CHECK(code(withFilter("n", FilterEntry{.eq = "1", .ne = "2"})) == std::pair{TableErrorCode::InvalidSpec, std::string{"n"}}); + TableQuery group; group.filters.groups.push_back(GroupFilter{.columns = {"n"}, .combine = Combine::Any, .include = {FilterEntry{.contains = "x"}}}); + CHECK(code(group) == std::pair{TableErrorCode::UnsupportedOperator, std::string{"n"}}); + // Mutation: apply skipping validate (the offset case answers an empty page). +} +``` + +(`withFilter` is the one-column helper the moved cases bring with them; keep a single definition.) + +- [ ] **Step 2: Delete** the four files listed, remove `include/morph/table/plan_conformance.hpp` from the `FILE_SET` at `CMakeLists.txt:722` and `table/test_table_database_pages.cpp` from `tests/CMakeLists.txt:36`, remove the query-plans section and `escapeLikePattern` from `query.hpp`, and delete `"table: LIKE patterns keep % and _ ordinary"`. + +- [ ] **Step 3: Rewrite the lims list actions** to read their rows and answer with `apply` + +- `SampleModel::pageSamples(sites, query)`: one `mapper.Query().WhereIn(::Lightweight::FieldNameOf<&db::SampleRecord::siteId>, siteIds).All()` (the `WhereIn` form `examples/bank/src/models/statement_model.cpp:62` uses), each record through `toView`, then `::morph::table::apply(rows, [](SampleView const& s) { return RowId{*s.id}; }, query)` (the row type is named: a lambda does not deduce `Row` through `RowKey`, a `std::function`). An empty site list reads nothing (`WHERE IN ()` is not issued). `execute(ListSamples)` calls it with `OrgModel::visibleSites(currentPrincipal())`; `samplesWhere` builds its `TableQuery` as now and calls it with `callerSitesAt(company)`. +- `LedgerModel::pageEntries(company, query)`: the entries `execute(ListEntries)` already reads (`ledger_entries.cpp:520-532`, one query on `companyId` and `toView(mapper, loadWritten(…))` per entry), then `apply`; the read is one helper both actions share. `execute(ListEntriesPage)` validates the query against the journal columns first (an invalid query is refused for every caller, as before), then keeps its visibility check and empty page. +- Doc comments on both say what they now do: "reads those rows (the sites' samples, the company's entries) and runs the query over them with `table::apply`; the total is the count up to `QueryLimits::totalCap` and omitted above it". A refusal names the action the caller sent (`samplesWhere` passes `CountSamplesToVerify` or `SearchSamples`), and `pageSamples` validates before it reads. +- `examples/lims/tests/test_ledger_scale.cpp`'s 10^6-entry `ListEntriesPage` case asserts no total (it is above `totalCap`), not an exact one. +- `plan_sql.hpp`'s includes leave `sample_model.cpp` and `ledger_entries.cpp`. + +- [ ] **Step 4: Prove scope is still pinned** + +Mutation: make `pageSamples` ignore `sites` (read every sample) and `execute(ListEntriesPage)` skip its visibility check, one at a time. +Expected: `"lab: the sample list answers through the action with an exact total"` fails on the first (`page.total` is all samples), `"ledger: a page of entries is the caller's, with an exact total"` on the second (dave gets rows). If either passes, add `"ledger entries: a principal never receives a row outside its scope"` asserting the failing condition, and run the mutation again. + +- [ ] **Step 5: Update the documentation** + +- `engine.md:300-306` becomes: "A model whose rows live in a database reads them as a `DataSource`, whole or lazily by column, and the server sorts, filters, pages and counts them with `apply`; `Page::totalKind` says whether a total is the count or a lower bound (`AtLeast`). `compileFilterGuarded` is the one compile step `apply` and `Engine` share, so a collator or date parser that throws is `ServiceFailed` in both." The `escapeLikePattern` bullet (`:311-312`) goes. +- `docs/spec/README.md:138-139`: the `database_pages.md` entry goes. +- `examples/lims/README.md:1795-1819`: replace the database-page section with one paragraph (the trial-balance paragraph after it stays and keeps its 10^7-line measurement): the sample and ledger lists read the caller's rows with one query and answer with `table::apply`, so their order is the engine's on every surface. The two findings that describe `plan_sql.hpp` and the conformance corpus (`:1830-1847`) go. + +- [ ] **Step 6: Verify nothing names the removed code** + +Run: `git grep -n -E "planQuery|QueryPlan|PlanUse|plan_conformance|standardCorpus|conformanceFailures|database_pages|escapeLikePattern|plan_sql|canTranslate" -- include src tests examples docs/spec ':!docs/spec/table/table.md'` +Expected: no output. (`table.md` names the removals in its API, Neighbouring-specs and Delivery-order rows, which stay.) + +- [ ] **Step 7: Run the suites** + +Run: `cmake --build --preset cl-debug --target morph_table_tests && ctest --test-dir build/cl-debug -R "^table" --output-on-failure` +Run: `cmake --preset cl-qt-debug -DMORPH_BUILD_LADDER=ON -DMORPH_LADDER_RUNGS=lims && cmake --build build/cl-qt-debug --target ladder_lims_tests -j 6 && ctest --test-dir build/cl-qt-debug -L ladder-lims --output-on-failure` +(The ladder needs `MORPH_BUILD_QT=ON`, so `cl-debug` refuses it at configure. Where Qt is not on the preset's path, add `-DCMAKE_PREFIX_PATH=/lib/cmake`; where the SQLite ODBC driver is registered under another name than `SQLite3`, set `ODBC_CONNECTION_STRING` to name it.) +Run the docs build of the roadmap's Global Constraints. +Expected: all green; the docs build prints no warning. + +- [ ] **Step 8: Commit** + +```bash +git add -A include/morph/table tests/table tests/CMakeLists.txt CMakeLists.txt examples/lims docs/spec +git commit -m "refactor(table): remove paging in a database" +``` + +--- + +### Task 1: The description and the generic page (table.md step 1, first half) + +**Files:** +- Create: `include/morph/table/description.hpp` (add to the `FILE_SET` beside `query.hpp`, `CMakeLists.txt:723`), `tests/table/test_table_description.cpp` (in `morph_table_tests`) +- Modify: `include/morph/table/query.hpp:67-78` (`TableQuery::columns`), `:102-121` (`QueryLimits::maxColumns`), `:228-250` (`validate` checks `columns` and normalises it; `detail::orderedColumns` beside `detail::checkColumn`), `tests/table/wide_table_model.{hpp,cpp}` (`bench::wideDescription`), `tests/table/bench_table.cpp` (W1, W2, W5, W6, W7) + +**Interfaces:** +- Consumes: `PageRows` (`query.hpp:282`), `TotalKind`, `DataSource`, `ColumnInfo`, `Cell`, `RowId`, `TableError` (existing); `morph::model::detail::fnv1a64`, `hex64` (`core/payload_schema.hpp`); `bench::WideTableSource` (Task 0). +- Produces, in `namespace morph::table`: + +```cpp +// query.hpp +struct TableQuery { std::vector sort; FilterSpec filters; PageRequest page; + std::optional> columns; /* absent: every column */ }; +struct QueryLimits { /* … */ std::size_t maxColumns = 512; }; +namespace detail { +/// `asked` in the order of `columns`, each id once; an id `columns` lacks is dropped (validate has refused it first). +[[nodiscard]] std::vector orderedColumns(std::span columns, + std::vector const& asked); +} + +// tests/table/wide_table_model.hpp, namespace bench +/// The description of `wideColumns(columns)`: `id` as given, `label` = `id`, each column's label its id, `group` and +/// `groups` (`g3`, `g16`, labels their ids) from the layout, key `"id"`, `levels` empty, `revision` empty. +[[nodiscard]] morph::table::TableDescription wideDescription(std::string id, int columns); + +// description.hpp +struct TableColumn { ColumnInfo info; std::string label; std::string group; + bool sortable = true; bool filterable = true; bool shown = true; + bool operator==(TableColumn const&) const = default; }; +struct ColumnGroupInfo { std::string id; std::string label; std::vector columns; + bool operator==(ColumnGroupInfo const&) const = default; }; +struct TableCapabilities { bool keys = true; bool distinct = true; std::uint32_t maxSortKeys = 8; + bool operator==(TableCapabilities const&) const = default; }; +struct TableDescription { std::string id; std::string label; std::vector columns; std::string key; + std::vector groups; std::vector levels; + TableCapabilities capabilities; std::string revision; + bool operator==(TableDescription const&) const = default; }; +[[nodiscard]] TableDescription describe(TableDescription description); +[[nodiscard]] std::vector columnInfos(TableDescription const& description); + +using GenericRow = std::vector; +struct GenericPage { std::string revision; std::vector columns; std::vector keys; + std::vector rows; std::optional total; + TotalKind totalKind = TotalKind::Exact; std::int64_t offset = 0; }; +[[nodiscard]] GenericPage writeGenericPage(PageRows const& page, DataSource const& source, + std::span columns); +[[nodiscard]] std::expected readGenericPage(std::string_view json, + TableDescription const& description); +namespace detail { +void appendCellJson(std::string& out, Cell const& cell); +[[nodiscard]] Cell cellFromJson(std::string_view json, std::optional kind); +} +``` + +Members later tasks insert, at the place table.md's block puts them: `TableColumn::{display, tone, tooltip}` (Task 15), `TableColumn::edit` (Task 24), `TableDescription::bands` after `groups` (Task 22), `units` after `levels` (Task 8c), `rowTone`, `rowLock` after `units` (Task 15); the generic page's sidecar members (Task 4). `TableQuery::keys` is Task 4's. + +**Pinned rules.** +- `describe` returns the description with `revision = hex64(fnv1a64(glz::write_json(d with revision cleared)))`: 16 lowercase hex digits. The canonical JSON is glaze's default write of the struct, members in declaration order. +- The page's JSON members, in this order: `revision`, `columns`, `keys`, `rows`, `total` (absent when not counted), `totalKind` (`"exact"`/`"atLeast"`), `offset`. `glz::meta` maps `rows` through a `glz::custom` pair that writes each cell with `appendCellJson` and reads each with `cellFromJson(json, std::nullopt)`; `readGenericPage` re-reads the cells with their column's kind. +- A cell is written by its alternative (table.md, "Rows on the wire"): `null`; an integer; a finite `double` as glaze writes it, with `.0` appended when that text has no `.`, `e` or `E` (so `2.0` is `2.0` and `-0.0` is `-0.0`, never the integer token `2`), a non-finite one as the string `"nan"`, `"inf"` or `"-inf"`; a string; `true`/`false`; a `Rational` with `p = decimalPlaces` as `[numerator × (10^p / denominator), 10^p]` when `10^p` is a multiple of the denominator and the product fits `int64`, otherwise `[numerator, denominator]`; a `QuantityCell` as `[n, d, [fn, fd]]` with amount and factor written by the `Rational` rule, and as the plain `Rational` `[n, d]` when its factor is 1. +- `cellFromJson` reads by shape: `null` → empty; a number whose token has no `.`, `e` or `E` → `int64` (a `double` when `kind` is `Number`, or when it does not fit `int64`); any other number → `double`, whatever the kind, so a `double` the server held in an `Integer` or `Decimal` column, which it keyed invalid (`sort.hpp`'s `readInteger` and `readExact` take no `double`), is a `double` and invalid on the client too; a string → `std::string` (in a `Number` column, `"nan"`, `"inf"`, `"-inf"` → that `double`); a boolean → `bool`; `[n, d]` with `d > 0` → `Rational{Numerator{n}, Denominator{d}, DecimalPlaces{k}}` where `k` is such that `d == 10^k` (`k ≤ 18`), otherwise `kMaxDecimalPlaces`; `[n, d, [fn, fd]]` → `QuantityCell`; anything else (an object, `[n, 0]`, a negative denominator, a third element of another shape, another length) → the `std::string` of its JSON text, which no kind but `Text` reads as valid. Read this way, the client's cell keys exactly as the server's did, so a cell the server keyed as invalid is invalid on the client. +- `readGenericPage` refuses with `TableError{.code = InvalidValue}` (naming the column where there is one) when the JSON is not a page, a `columns` entry is not in the description (`UnknownColumn`), a row's length differs from `columns`, or `keys` and `rows` differ in length. +- `writeGenericPage` writes `columns` as given (the caller orders and deduplicates them), `keys[i] = snapshot->rowId(page.rows[i])`, the cells of those columns only, `total` and `offset` from `page`; `revision` is left for the caller. +- `validate` checks `query.columns` when present, and normalises it (table.md, "Data levels": "`validate` bounds `columns` by `QueryLimits::maxColumns` (512), puts it in the description's order and removes duplicates"): more than `maxColumns` entries, counted as received, is `LimitExceeded`; each entry through `detail::checkColumn` (`UnknownColumn`, `ColumnNotReadable`); the query it returns holds `detail::orderedColumns(columns, *query.columns)`. An absent list stays absent and an empty one stays empty. Every caller of `validate` or `apply` therefore sees the list in the order of the columns it validated against, each id once. + +- [ ] **Step 1: Write the failing tests** in `tests/table/test_table_description.cpp` + +```cpp +TEST_CASE("description: equal descriptions have equal revisions", "[table][description]") { + TableDescription base{.id = "designs", .label = "Designs", + .columns = {TableColumn{.info = {.id = "id", .kind = ColumnKind::Integer}, .label = "Id"}, + TableColumn{.info = {.id = "name", .kind = ColumnKind::Text}, .label = "Name"}}, + .key = "id"}; + auto const a = describe(base); auto const b = describe(base); + CHECK(a.revision.size() == 16); + CHECK(a.revision == b.revision); + CHECK(describe(a).revision == a.revision); // Mutation: hashing with the old revision in + auto relabelled = base; relabelled.columns[1].label = "Title"; + CHECK(describe(relabelled).revision != a.revision); // Mutation: hashing the columns' ids only + auto hidden = base; hidden.columns[1].shown = false; + CHECK(describe(hidden).revision != a.revision); +} + +TEST_CASE("generic page: every cell kind round-trips", "[table][description]") { + // Description: id Integer, name Text, net Decimal, share Decimal, dose Quantity, ratio Number, flag Bool, on Date. + // Rows (keys 101, 102): + // 101: 101, "Alpha", 12.50 (places 2), 0.003 (places 3), QuantityCell{5 (places 0), 1/1000 (places 3)}, 0.1, true, 19'000 + // 102: 102, "Beta", empty, empty, Rational 250 (places 0), 2.5, false, empty + // writeGenericPage over a VectorSource of these rows, PageRows{.rows = {0, 1}, .total = 9093, .offset = 0}, + // columns {"id","name","net","share","dose"}, revision set to "9f2c"; glz::write_json gives exactly: + // {"revision":"9f2c","columns":["id","name","net","share","dose"],"keys":[101,102], + // "rows":[[101,"Alpha",[1250,100],[3,1000],[5,1,[1,1000]]],[102,"Beta",null,null,[250,1]]], + // "total":9093,"totalKind":"exact","offset":0} + // readGenericPage(that JSON, description) gives back: keys, columns, total, offset equal; tabletest::sameCell(read, + // written) for every cell (so a Rational's decimalPlaces and a QuantityCell's amount and toCanonical are compared). + // The same page with all eight columns: `ratio` reads as double 0.1 and 2.5, `flag` as bool, `on` as int64 19'000. + // Mutation: writing a Rational as glaze's {"num","den","dp"} object. + // Mutation: reading [1250, 100] with DecimalPlaces{kMaxDecimalPlaces} (operator== still holds; sameCell fails). +} + +TEST_CASE("generic page: a cell that does not read as its column's kind is invalid", "[table][description]") { + // readGenericPage of a one-column Integer page whose rows are ["abc"], [2.5], [[1,0]], [{"x":1}], [2.0], [7]: + // buildKeys over a VectorSource of the read rows gives states {Invalid, Invalid, Invalid, Invalid, Invalid, Valid}. + // The same values in a Text column: the last five keys are Valid (a Text column has no invalid cell). + // Server and client agree: a VectorSource of one Integer column holding Cell{2.0} keys Invalid; its page through + // writeGenericPage and glz::write_json holds the token 2.0; read back, the cell holds a double and keys Invalid. + // The same for a Decimal column. In a Number column 2.0 writes 2.0 and reads as double 2.0, Valid. + // Mutation: cellFromJson parsing "abc"-like strings for the column's kind on read (2.5 read as Integer 2). + // Mutation: writing a double as glaze does (2.0 becomes 2, an int64 the client keys Valid). +} + +TEST_CASE("generic page: numbers at the edges cross the wire unchanged", "[table][description]") { // Review Focus 2 + // Number column: NaN, +inf, -inf, -0.0, 1e308 → written as "nan", "inf", "-inf", -0.0, glaze's 1E308 → read back equal + // (NaN by std::isnan). Integer column: INT64_MIN, INT64_MAX. Decimal column: Rational{INT64_MAX, 3, places 2} + // (10^2 is not a multiple of 3, so written [INT64_MAX, 3]) and Rational{INT64_MAX / 10, 1, places 18} + // (the scaled numerator overflows, so written [n, 1]) → read back equal by value. + // Mutation: writing a non-finite double with glaze's default (the page fails to write, or reads back empty). +} + +TEST_CASE("generic page: a malformed reply is refused and a malformed cell is invalid", "[table][description]") { // Review Focus 3 + // Refused, code and column: + // a row of 2 cells under 3 columns → InvalidValue; keys [1,2] with one row → InvalidValue; + // "columns":["nope"] → UnknownColumn, column "nope"; "not json" → InvalidValue. + // Kept, one cell invalid: an Integer cell [1,0] in an otherwise valid page reads, and that cell keys Invalid. + // Mutation: readGenericPage padding a short row with empty cells. +} + +TEST_CASE("table query: columns round-trip and are bounded", "[table][query]") { + // glz::write_json(TableQuery{.columns = std::vector{"a","b"}}) contains "columns":["a","b"] and reads back + // equal; R"({"sort":[],"filters":{},"page":{"offset":0,"limit":10}})" reads with columns == std::nullopt. + // validate against columns {id, a, b} with mayRead refusing "b": + // columns {"zz"} → UnknownColumn "zz"; {"b"} → ColumnNotReadable "b"; 513 entries → LimitExceeded (513 copies of + // "a" too: the bound counts entries as received); {} → accepted, and the returned query's columns are present and empty. + // Mutation: validate ignoring `columns`. +} + +TEST_CASE("table query: a columns list is answered in the description's order, once each", "[table][query]") { // Review Focus 1 + // infos = columnInfos(bench::wideDescription("small", 30)): + // validate(TableQuery{.columns = std::vector{"t000","id","t000","i001"}}, infos)->columns + // == std::vector{"id","i001","t000"}; + // validate(TableQuery{}, infos)->columns == std::nullopt (absent stays absent: every column); + // validate with columns {"t000","zz"} → UnknownColumn "zz" (an unknown id is refused, not dropped); + // apply(WideTableSource{1'000, 30, 7}, the first query) succeeds: apply validates through the same step. + // detail::orderedColumns(infos, {"i001","nope","id"}) == {"id","i001"}. + // writeGenericPage of rows 0..199 of WideTableSource{1'000, 30, 7} with an empty column list gives 200 keys and + // 200 rows of zero cells. + // Mutation: validate returning `columns` as received (the query's order, the duplicate kept). +} + +TEST_CASE("generic page: a page names only the asked columns", "[table][description]") { // gate W1 + // WideTableSource{1'000, 300, 7}; PageRows of rows 0..199; 40 columns: positions 100..139. + // The JSON's "columns" has 40 entries; every row array has 40 cells; no other column id appears in "columns". + // Mutation: writeGenericPage ignoring `columns` (writes all 300). +} + +TEST_CASE("generic page: a whole page fits an envelope", "[table][description]") { // gate W7 + // The same 200 rows with all 300 columns: every row holds 300 cells (60,000 in all), and + // glz::write_json(page)->size() + 4'096 < morph::wire::kMaxEnvelopeBytes; the size is also above 600'000, so the + // page measured is the wide one (ten bytes a cell is a floor no 300-column page is under). + // Mutation: writeGenericPage writing the first 40 columns whatever it is given (the row length and the floor fail). +} + +TEST_CASE("description: a 300-column description round-trips", "[table][description]") { // W6's codec + // d = bench::wideDescription("wide", 300) with d.levels = {"recipe"} set by the test (the fixture serves none in + // this part); through describe, glz::write_json and glz::read_json: equal to the original, with 300 columns, + // groups g3 (3 columns) and g16 (16), and the 16-digit revision. + // Mutation: a glz::meta for TableDescription that leaves out `groups` (the read description has none). +} +``` + +`detail::orderedColumns` is declared in `query.hpp` beside `detail::checkColumn`; `bench::wideDescription` in the fixture header. + +- [ ] **Step 2: Run them to see them fail** + +Run: `cmake --build --preset cl-debug --target morph_table_tests` +Expected: compile failure, `morph/table/description.hpp` not found. + +- [ ] **Step 3: Implement** `TableQuery::columns`, `QueryLimits::maxColumns`, `detail::orderedColumns`, `validate`'s check and normalisation in `query.hpp`, `bench::wideDescription` in the fixture, and every symbol listed in Produces in `description.hpp`, with the pinned rules above. Every public symbol gets complete Doxygen. + +- [ ] **Step 4: Run them to see them pass** + +Run: `ctest --test-dir build/cl-debug -R "description|generic page|table query" --output-on-failure` +Expected: the 10 tests of `test_table_description.cpp` pass (the pattern also matches `morph_tests` cases whose names contain "description", when that executable is built); then `ctest --test-dir build/cl-debug -R "^table" --output-on-failure`, all pass. + +- [ ] **Step 5: Write the wire benchmarks** in `bench_table.cpp`, `"table benchmark: the generic page"`, `"[.benchmark][wire]"`: W1 (bytes of the 200 × 40 page in an `ok` envelope), W2 (encode from the column store, and `readGenericPage`), W5 (the same 200 × 30 page as generic rows and as a typed `Page`, where `WideRow30` is a 30-member struct in the bench file mirroring `wideColumns(30)`), W6 (bytes, encode and decode of the 300-column description), W7 (the 200 × 300 page: bytes, encode, decode). Each first `REQUIRE`s its page's cell count. Run on `cl-release` and add rows W1, W2, W5, W6, W7 to "Recorded baselines". + +- [ ] **Step 6: Mutations, docs build, commit** + +Apply each mutation named in Step 1; paste the failing lines into the commit body. Run the docs build (Global Constraints). + +```bash +git add include/morph/table/description.hpp include/morph/table/query.hpp CMakeLists.txt \ + tests/table/wide_table_model.hpp tests/table/wide_table_model.cpp \ + tests/table/test_table_description.cpp tests/table/bench_table.cpp tests/CMakeLists.txt docs/spec/table/table.md +git commit -m "feat(table): table descriptions and the generic page" +``` + +--- + +### Task 2: Tables of a model on the bridge (table.md step 1, second half) + +**Files:** +- Modify: `include/morph/table/description.hpp` (the bridge-facing types below) +- Modify: `include/morph/core/detail/result_walker.hpp:139-165` (a holder reports its record at a member), `include/morph/core/records.hpp:43-58` (`RecordInfo::table`) and a `registerTableRecordOnce`, `include/morph/core/effects.hpp:113-127` (`ActionRecord::opaque`), `:410-418` (`sameRegistration` compares `table`), `:520-527` (a table record may be keyed and derived), `:543-560` (an opaque slot), `:73-89` (`updatesTable`, `changesTable`) +- Modify: `include/morph/core/registry.hpp:841,967,1030,1039` and `include/morph/core/bridge.hpp:612,625,2245,2434` (call `invokeExecute`), and `BRIDGE_REGISTER_TABLE` after `BRIDGE_REGISTER_ACTION_SOURCE` (`registry.hpp:2206`) +- Create: `include/morph/table/runtime.hpp` (`TableRuntime`, `currentTableRuntime`, `TableRuntimeScope`; it includes only `core/executor.hpp`, so `core/remote.hpp` includes it without reaching the table headers; add it to the `FILE_SET` beside `query.hpp`); define the thread-local behind `currentTableRuntime()` in `src/ui/process_state.cpp` beside `tlsCurrent()` (`:144`), as a `MORPH_API` function so a shared build has one copy +- Modify: `include/morph/core/remote.hpp:310-367` (`ServerConfig::tableWork`), `:2861` and `:2875-2885` (`startRemote` and `startTaskRemote` install a `table::TableRuntimeScope` beside `ScopedContext`, with `work` = `tableWork` or, when null, the server's worker pool) +- Modify: `include/morph/forms/forms.hpp` (`forEachNamedMember` walks a type glaze writes as one of its members, its `glz::meta` value a member pointer, through that member: `QueryTable`'s JSON is its `TableQuery`'s, and the action's schema extras are built by that walk) +- Modify: `tests/table/wide_table_model.{hpp,cpp}` (`bench::WideTableModel`), `tests/table/test_table_description.cpp`, `tests/table/bench_table.cpp` (Step 6) +- Create: `tests/net/test_push_tables.cpp` (in `morph_net_tests`, `tests/net/CMakeLists.txt:1-12`) +- Docs: `docs/spec/core/registry.md` (a section `### BRIDGE_REGISTER_TABLE(M, ID, FN, ...)` after `### BRIDGE_REGISTER_ACTION(M, A, NAME, ...)`, `:999`, and a paragraph on `invoke` under `### ActionTraits`, `:217`), `docs/spec/core/backend.md` (`tableWork` in the `ServerConfig` table, `:2491`, and one bullet in "Fan-out", `:1221`, saying a table action's reply is built on `tableWork` and its fan-out is the record machinery's) + +**Interfaces:** +- Consumes: Task 1's `TableDescription`, `describe`, `GenericPage`, `writeGenericPage`, `columnInfos`, `bench::wideDescription`; `validate` (which orders and deduplicates `columns`), `apply`, `RowsSource`, `detail::reflectedColumns`; `effects::updates`, `changes`; `session::current()`; `forms::detail::findFieldMeta`, `forms::detail::inferTitle`; `morph::async::DelayAwaiter` as the model for an awaiter that resumes on the strand. +- Produces, `namespace morph::table`: + +```cpp +class LevelSource; // defined by Task 5 as a class +struct TableContext { session::Context const& session; }; +struct ServedTable { + TableDescription description; + std::shared_ptr source; + std::vector> levels; // empty until Task 5 gives it meaning + std::function mayRead; + std::string scope; + Services services; + QueryLimits limits; +}; +struct ChangedRow { RowId key; }; // Task 17c adds `from` +template struct ChangedRows { // Task 17c adds `failed` + std::vector rows; + using heldRecord = TableOf; + static constexpr std::string_view heldMember() noexcept { return "rows"; } +}; +template struct TableTraits { static constexpr bool registered = false; }; // specialised by the macro +template struct TableOf { static_assert(TableTraits::registered, "not a registered table"); }; +template struct Typed { Fn function; }; +template [[nodiscard]] constexpr Typed typed(Fn function) noexcept; +struct rowScoped {}; +template struct derivedFrom {}; +[[nodiscard]] std::shared_ptr scoped(std::shared_ptr source, std::vector keys); +template struct QueryTable { TableQuery query; /* JSON is the TableQuery's: glz::meta value = &QueryTable::query */ + template static ::core::async::Task invoke(Model& model, QueryTable& action); }; +template struct DescribeTable { + template static TableDescription invoke(Model& model, DescribeTable& action); }; +namespace detail { +struct AnswerContext {}; // Task 6 adds `ViewCache* views`, `std::string_view record`, `bool rowScoped` (index decisions 5, 48) +[[nodiscard]] std::expected answerQuery(ServedTable const& served, TableQuery const& query, + AnswerContext const& context = {}); // served.source is pinned +[[nodiscard]] ServedTable pinned(ServedTable served); // on the owner's thread: source → PinnedSource of one snapshot +template +[[nodiscard]] ServedTable serve(Model& model, TableContext const& context); // the one way to a table's ServedTable +} +// include/morph/table/runtime.hpp +struct TableRuntime { exec::IExecutor* work = nullptr; }; // Task 6 adds `ViewCache* views` +[[nodiscard]] MORPH_API TableRuntime const* currentTableRuntime() noexcept; // null outside a RemoteServer dispatch +class TableRuntimeScope { // installs `runtime` for the scope, restores the previous one +public: explicit TableRuntimeScope(TableRuntime const& runtime) noexcept; ~TableRuntimeScope(); + TableRuntimeScope(TableRuntimeScope const&) = delete; TableRuntimeScope& operator=(TableRuntimeScope const&) = delete; }; +} +namespace bench { inline constexpr std::string_view kWideModelType = "WideTableModel"; } // tests/table/wide_table_model.hpp +namespace morph::effects { +template using updatesTable = updates<::morph::table::TableOf>; +template using changesTable = changes<::morph::table::TableOf>; +} +namespace morph::model::detail { +template decltype(auto) invokeExecute(Model& model, Action& action); +// `Action::invoke(model, action)` when the action declares one, `model.execute(action)` otherwise. +} +// ServerConfig: std::shared_ptr<::morph::exec::IExecutor> tableWork; // null: the server's worker pool +// effects::ActionRecord: bool opaque = false; // held at no path; `paths` is empty +// record::RecordInfo: bool table = false; // registered by BRIDGE_REGISTER_TABLE +``` + +`BRIDGE_REGISTER_TABLE(M, ID, FN, ...)`, `ID` a string literal, `FN` a member function pointer or a `table::typed(…)` expression, options `table::rowScoped` and `table::derivedFrom<…>`. It requires `BRIDGE_REGISTER_MODEL(M, …)` before it and `` in the translation unit, and emits: +1. `template <> struct morph::table::TableTraits { using model = M; using row = R; static constexpr bool registered = true; static constexpr std::string_view id = ID; static constexpr auto serve = FN; }`, where `KEY` is the member function pointer: `FN` itself, or `FN.function` for `typed(&M::fn)`, and `R` is `Row` for a typed table and `void` otherwise (`table::detail::tableKey(FN)` and `table::detail::TableRow` compute them). Every type below is keyed on `KEY`, so `TableOf<&M::fn>`, `ChangedRows<&M::fn>` and `updatesTable<&M::fn>` name a typed table as they name a generic one; `QueryTable::invoke` reads `TableTraits::serve` to call the function; +2. `ActionTraits` and registrars for `QueryTable` under `"Table." ID` (result `GenericPage`) and `DescribeTable` under `"Table." ID ".describe"` (result `TableDescription`), as `BRIDGE_DETAIL_ACTION_TRAITS_BODY` does for an action with an explicit result, both with `::morph::model::Loggable::No`: they read, and a page fetch is not written to an action log (the default of `BRIDGE_REGISTER_ACTION` is `Loggable::Yes`, `registry.hpp:2122`; the tree's read actions pass `No`, `ui/preferences.hpp:316`); +3. `registerTableRecordOnce, Options…>(ModelTraits::typeId() + "." ID)`: a `RecordInfo` with `keyField = "key"`, `table = true`, `privateKeys` from `rowScoped`, `derivedFrom` from `derivedFrom<…>`; +4. one more `ResultSlot{typeid(TableOf), "", .opaque = true}` on `"Table." ID`'s result slots (`ResultSlot` gains `bool opaque = false`), which `resolve` turns into `ActionRecord{.record, .keyField, .paths = {}, .opaque = true}` so the table's action holds its record for watch admission (`remote.hpp:1794`) and names no path. + +**Pinned behaviour.** +- **A table id is unique in the process, not only in its model.** The action id is `"Table." ID` with no model in it, and the effects registries are keyed by action id: a second action type under an id is listed in `actionResultConflicts()` (`registerActionResultOnce`, `registry.hpp:1626-1648`) and `effects::resolve` refuses it (`effects.hpp:522`), which fails every effects lookup of the process. Two models that each register a table `"rows"` are therefore refused when the registries resolve, with "action `Table.rows` is registered by two action types; give each its own id". table.md states the same rule ("A table id is unique in the process", under "A model's tables"), so the spec is not edited here; check with `grep -n "unique in the process" docs/spec/table/table.md`. The macro's Doxygen and `registry.md` state the process-wide rule, and a test below pins the refusal. +- The walk (`result_walker::visit`): a type `T` with `T::heldRecord` and `T::heldMember()` adds `ResultSlot{typeid(typename T::heldRecord), path.empty() ? heldMember() : path + "." + heldMember()}` beside its own slot. +- `resolve` does not report "derived from other records but has a key" for a record with `table == true`: a source's change reaches it as a whole-record change, as `addDerivedChanges` already sends. +- `QueryTable::invoke`: on the strand, build `TableContext` from `session::current()` (a static empty `Context` when null) and call `detail::serve(model, context)`; read `currentTableRuntime()` before the first suspension and build `AnswerContext{}` from it; then, still on the strand, replace `served.source` with a `detail::PinnedSource` (the one `snapshot()` taken now and a copy of `columns()`), because a `DataSource` is owner-affine and only its snapshot may cross threads (`data_source.hpp:728`; table.md "the framework takes the source's snapshot, and then on the server's table executor…"); then run `answerQuery(pinnedServed, action.query, context)` as one work item posted to `runtime->work` and resume with its result through an awaiter built like `DelayAwaiter`, so the coroutine's own steps stay on the strand and the sort does not. With no runtime installed or a null `work` (`LocalBackend`), `answerQuery` runs inline. A `TableError` becomes `model::ActionRefusal{"table." + , {{"column", error.column}}, error.message}`. +- `answerQuery`: `validate(query, columnInfos(served.description), served.limits, served.mayRead)`; the page's columns are that validated query's `columns` (in the description's order, each once, by Task 1's `validate`), kept from this first validation, since `apply` validates again against the source's columns, whose order may differ; `served.source` is a `detail::PinnedSource` (a `DataSource` holding one snapshot and a copy of the columns, whose `snapshot()` returns that snapshot and whose `subscribe` does nothing); `answerQuery` never takes a snapshot of a live source, and both `apply` (with `ApplyOptions{limits, services, mayRead}`) and `writeGenericPage` read the pinned one; a caller that passes a live source (the tests) gets it pinned by `detail::pinned(ServedTable)`, called on the caller's thread; with `query.columns` absent, the page's columns are the description's minus those `served.mayRead` refuses (invariant 14); `page.revision = served.description.revision`. A description column the source lacks is `TableError{UnknownColumn, column, "the table's source has no column "}`. +- `DescribeTable::invoke` returns `describe(served.description)` (so a model never fills `revision`); it runs on the strand and touches neither the source nor a snapshot. The function result is described once per call; a model whose description does not vary returns the same object each time. +- `detail::serve(model, context)` is the only path from a model to its `ServedTable`; `QueryTable::invoke` and `DescribeTable::invoke` call it on the strand, and Task 17a's `resolve` will too. For a plain table it calls `(model.*Function)(context)`; for a typed table (`TableTraits::row` not `void`) it calls the typed function and builds the description and the `RowsSource` as the next bullet says. +- `typed(fn)`: `fn` is `std::shared_ptr const> (Model::*)(TableContext const&)`. The served description's columns are `detail::reflectedColumns()` in member order, labels `findFieldMeta(id)->label` or `inferTitle(id)`, key the `keyField` of the record registered for `Row`; the source is `RowsSource` keyed by that member. +- `scoped(source, keys)`: a `DataSource` whose snapshot maps its rows, in the shared source's order, onto the shared source's rows whose key is in `keys` (keys the source lacks are skipped); it copies no cell; when the shared source's snapshot pointer changes, the next `snapshot()` rebuilds the row map under a mutex. +- `bench::WideTableModel` (registered `"WideTableModel"`), process-wide state set by `static void configure(WideTableOptions wide, WideTableOptions small)` (defaults `{100'000, 300, 1}` and `{1'000, 30, 1}`). `configure` may be called at any time, from any test case: it replaces both options under the state's mutex and drops both sources; each source is built lazily on the first table call that needs it after that. A request already holding a source keeps it. + - `wide(TableContext const&)`, `small(…)`: the description is Task 1's `bench::wideDescription("wide", 300)` and `("small", 30)` (so `levels` is empty in this part; Part B's Task 5 sets it when the slow level lands), key `id`, one shared `WideTableSource` each, `Services{}`. + - `scoped(…)`: `small`'s source; the description is `small`'s without `d000`…`d005` for every principal except `"extended"` (all 30) and `"restricted"` (also without `t000`…`t006`); `mayRead` is membership in the caller's description. + - Actions: `EditWideRow{std::int64_t row; std::string column; std::int64_t value;}` sets the cell in `wide`, and in `small` when the row and column are there, and returns `EditWideRowResult{ChangedRows<&WideTableModel::wide> wide; ChangedRows<&WideTableModel::small> small;}` with the changed row's key in each it changed; effects `updatesTable` on `wide` and `small`. `ReplaceWideRows{std::uint64_t seed;}` regenerates both; effects `changesTable` on both. + +- [ ] **Step 1: Write the failing local tests** in `tests/table/test_table_description.cpp` + +```cpp +TEST_CASE("table registration: a model with no row type serves a table", "[table][registration]") { + // Spec row "A table from a description", server half. WideTableModel::configure({2'000, 300, 7}, {1'000, 30, 7}). + // served = WideTableModel{}.small(ctx); answerQuery(served, {sort {i001 asc}, filter t001 contains "a", page {0, 10}}): + // 10 keys, equal to the keys of apply over a fresh WideTableSource{1'000, 30, 7} with the same query; + // columns == the 30 ids in layout order; revision == describe(served.description).revision. + // Mutation: answerQuery ignoring query.sort. +} + +TEST_CASE("table registration: two tables of one model are two records and two actions", "[table][registration]") { + // effects::recordNamed("WideTableModel.wide")->keyField == "key" and ->table; same for ".small" and ".scoped". + // effects::recordsOf("Table.wide") == {ActionRecord{.record = "WideTableModel.wide", .keyField = "key", .paths = {}, .opaque = true}}. + // effects::actionsHolding("WideTableModel.wide") == {"EditWideRow", "Table.wide"}; ("…small") == {"EditWideRow", "Table.small"}. + // effects::effectsOf("EditWideRow") == {{Updates, "WideTableModel.wide"}, {Updates, "WideTableModel.small"}}. + // effects::effectsOf("ReplaceWideRows") == {{Changes, "WideTableModel.wide"}, {Changes, "WideTableModel.small"}}. + // Mutation: one record for the model (the record keyed on M instead of FN): the second registration conflicts. +} + +TEST_CASE("changed rows: the walk reports the table at its rows member", "[table][registration]") { + // walkResult() contains {typeid(TableOf<&WideTableModel::wide>), "wide.rows"} and + // {typeid(TableOf<&WideTableModel::small>), "small.rows"}. + // effects::deriveChanges("EditWideRow", R"({"wide":{"rows":[{"key":5}]},"small":{"rows":[{"key":5}]}})", ranOn) + // names record "WideTableModel.wide" with keys [5] and "WideTableModel.small" with keys [5]. + // Mutation: the walker without the heldRecord rule (the registry then refuses EditWideRow's updates). +} + +TEST_CASE("changed rows: updatesTable without its ChangedRows is refused when the registries resolve", "[table][registration]") { + // resolveForTesting(records = {the "WideTableModel.wide" RecordInfo}, slots = {"Bad": walkResult()}, + // declared = {"Bad": {updates>}}) throws EffectsRegistrationError whose problems + // contain "action `Bad` declares updates on record `WideTableModel.wide`, but its result holds no `WideTableModel.wide`". + // NoTableResult is a test struct {std::vector ids;}. + // The same call with slots = {"Bad": walkResult()} resolves, and its actionRecords for + // "Bad" name "WideTableModel.wide" at path "wide.rows". + // Mutation: the walker without the heldRecord rule (the second call throws the same problem). +} + +TEST_CASE("table registration: one table id in two models is refused when the registries resolve", "[table][registration]") { + // Test models UqA and UqB each have a function `rows`. Neither is registered with the macro: a real second + // "Table.rows" would make the process registry of this executable invalid for every other case. + // static_assert(!std::is_same_v, QueryTable<&UqB::rows>>): the two tables' query actions + // are two action types, which under the one id "Table.rows" is what registerActionResultOnce lists as a conflict. + // resolveForTesting(records = {}, slots = {"Table.rows": ActionResult{typeid(QueryTable<&UqA::rows>), {}}}, + // declared = {}, slotConflicts = {"Table.rows"}) throws EffectsRegistrationError whose problems contain + // "action `Table.rows` is registered by two action types; give each its own id". + // The process registry holds no conflict: model::detail::actionResultConflicts() is empty, with WideTableModel's + // three tables and this file's test models registered (their ids are all different). + // Mutation: QueryTable keyed on the table's id text instead of its function (the static_assert fails: two models' + // tables would share one action type and a second table "rows" would silently answer with the first's rows). +} + +TEST_CASE("table registration: rowScoped and derivedFrom are the record's", "[table][registration]") { + // Test model RtModel registers table "mine" with table::rowScoped and "theirs" with table::derivedFrom + // (RtSource a registered record; RtTouch an action declaring changes). + // recordNamed("RtModel.mine")->privateKeys; recordNamed("RtModel.theirs")->derivedFrom == {typeid(RtSource)} and + // keyField == "key"; deriveChanges("RtTouch", "{}", ranOn) names "RtModel.theirs" with no keys. + // Mutation: keeping "a derived record is keyless" for tables (the process registry fails to resolve). +} + +TEST_CASE("columns by session: two principals get two descriptions", "[table][registration]") { + // Spec row "Columns by session", server half. describe(scoped(ctx "alice")) has 24 columns, "extended" 30, + // "restricted" 17; their three revisions differ. answerQuery for "restricted" with columns absent names its 17; + // with columns {"d000"} it is UnknownColumn "d000"; for "alice" a page's revision is alice's description's. + // A ServedTable whose description lists i001 but whose mayRead refuses it: with columns absent, the page's columns + // lack i001 and no row holds its cell. Mutation: answerQuery not filtering the absent-columns list by mayRead. + // Mutation: answerQuery validating against the source's columns instead of the description's. +} + +TEST_CASE("typed: a typed table writes the page the generic source writes", "[table][registration]") { + // Spec row "The generic page", typed half. TypedRow{std::int64_t id; std::string name; Rational price;}, registered + // as a record keyed `id`; TypedModel::rows returns 3 rows; table "typedRows" registered with typed(&TypedModel::rows). + // The served description: columns id (Integer), name (Text), price (Decimal), labels "Id", "Name", "Price", key "id". + // glz::write_json of answerQuery(typed served, q) == of answerQuery(a ServedTable over a VectorSource of the same + // rows and the same description, q), for q = {sort {price desc}, page {0, 2}}. + // detail::serve<&TypedModel::rows>(model, ctx).description, through describe(), equals what DescribeTable<&TypedModel::rows> + // returns through the bridge. Mutation: DescribeTable building the typed description its own way and dropping the labels. + // Mutation: the typed layer reading cells in glaze's key order while the description lists reflected order differently. +} + +TEST_CASE("scoped: a scope's source reads the shared rows of its keys", "[table][registration]") { + // base VectorSource keys 1..5; scoped(base, {4, 2, 9}): rowCount 2, rowId(0) == 2, rowId(1) == 4, cell(1, c) == base's + // row of key 4; after base->updateRow(index of 4, new cells), scoped->snapshot()->cell(1, c) is the new value. + // Mutation: scoped copying the rows when built (the update is not seen). +} + +TEST_CASE("table action: a failing table function is an error reply and the model stays usable", "[table][registration]") { // Review Focus 5 + // FlakyModel's table "flaky" throws std::runtime_error on its first call and on the second returns a description + // naming column "ghost" its source lacks; the third call is well formed. + // Through Bridge + LocalBackend (as tests/test_coroutine_model.cpp:513 drives a Task handler): the first + // QueryTable<&FlakyModel::flaky> fails with the thrown message; the second fails with ActionRefusal code + // "table.unknownColumn" and arg column "ghost"; the third succeeds with its rows. + // Mutation: answerQuery writing the page column by column without checking the source first (a partial page). +} +``` + +- [ ] **Step 2: Write the failing socket tests** in `tests/net/test_push_tables.cpp`, built on the server-and-two-clients harness of `tests/net/test_push_two_clients.cpp`, with a test model `PtModel` serving tables `first` and `second` over small `VectorSource`s, actions `EditFirst` (→ `ChangedRows<&PtModel::first>`, `updatesTable` first), `EditSecond` (→ `ChangedRows<&PtModel::second>`, `updatesTable` second) and `EditBoth` (→ `{ChangedRows<&PtModel::first> first; ChangedRows<&PtModel::second> second;}`, `updatesTable` on both), and an authoriser that refuses principal `bob` `Table.second`, `EditSecond` and `EditBoth`. A watch of a record is admitted when the principal may run any action holding it (`remote.hpp:1794-1800`), and `EditSecond` and `EditBoth` hold `PtModel.second`, so refusing `Table.second` alone would still admit bob: + +```cpp +TEST_CASE("tables: a principal allowed one table's action is refused the other", "[net][tables]") { + // bob (refused Table.second, EditSecond and EditBoth, the only actions holding PtModel.second): watch {PtModel.first} admitted, + // watch {PtModel.second} in refusedRecords; executing Table.second is refused. + // alice: both admitted. Mutation: one record for the model (bob is admitted to both or neither). +} +TEST_CASE("tables: updatesTable on one table marks only its watchers", "[net][tables]") { + // c1 watches PtModel.first, c2 PtModel.second. EditFirst changing key 3: c1 receives a change of PtModel.first + // with keys [3]; c2 receives nothing within 3 × coalesceWindow. Then EditSecond changing key 4: c2 receives + // PtModel.second with keys [4]; c1 receives nothing. + // Mutation: ChangedRows::heldRecord naming the model's first registered table whatever F is (the registries + // refuse EditSecond's updatesTable, or c1 is told of key 4). +} +TEST_CASE("tables: an action changing two tables sends each table its keys", "[net][tables]") { + // EditBoth changing first key 1, second key 2: c1 gets PtModel.first [1]; c2 gets PtModel.second [2]. + // Mutation: the walk reporting a holder's record at the holder's own path instead of at its `rows` member (no key + // is found at "first" or "second", so each watcher gets a change without keys). +} +TEST_CASE("tables: a page's columns are the caller's", "[net][tables]") { + // Spec row "Columns by session" over the socket: WideTableModel's Table.scoped.describe for alice and restricted + // differ; each one's Table.scoped page lists its own columns and carries its own description's revision. + // Mutation: QueryTable::invoke building TableContext from an empty session instead of session::current() (both + // principals get the same 24 columns). +} +TEST_CASE("tables: a table's reply is built on tableWork", "[net][tables]") { + // ServerConfig::tableWork = a ThreadPoolExecutor{2} wrapped to record its threads' ids. PtModel.first's source is a + // recording source whose snapshot records the thread of every readColumn call. A Table.first query with a sort: + // every recorded read is on a tableWork thread, none on the thread that ran PtModel::first. + // Mutation: RemoteServer not installing the TableRuntimeScope (answerQuery runs inline on the strand). +} +``` + +- [ ] **Step 3: Run them to see them fail** + +Run: `cmake --build --preset cl-debug --target morph_table_tests` +Expected: compile failure, `ServedTable` undeclared. +Socket tests (POSIX only; on Windows in WSL or the Linux CI leg): `cmake --preset linux-everything && cmake --build --preset linux-everything --target morph_net_tests` +Expected: compile failure, `BRIDGE_REGISTER_TABLE` undefined. + +- [ ] **Step 4: Implement** every symbol of Produces and the pinned behaviour, in the files listed; register `bench::WideTableModel` with its three tables and two actions in `wide_table_model.hpp`, below the class, and define its members in `wide_table_model.cpp`. The registrations go in the header because a translation unit that names `TableOf<&WideTableModel::wide>` (the walk over `EditWideRowResult` in the tests does) must see `TableTraits`' specialisation, or `TableOf`'s `static_assert` fires there. Every public symbol gets complete Doxygen. + +- [ ] **Step 5: Run them to see them pass** + +Run: `ctest --test-dir build/cl-debug -R "table registration|changed rows|columns by session|typed:|scoped:|table action" --output-on-failure` +Expected: 10 tests pass. Then the suites the dispatcher change touches: `cmake --build --preset cl-debug --target morph_tests morph_table_tests && ctest --test-dir build/cl-debug --output-on-failure -j 8`, all pass. +Run: `ctest --test-dir build/linux-everything -L net -R "tables:" --output-on-failure` +Expected: 5 tests pass; `ctest --test-dir build/linux-everything -L net` all pass. + +- [ ] **Step 6: Record W1 and W2 over the bridge** + +Extend `"table benchmark: the generic page"` with the `Table.wide` reply of 200 rows × 40 named columns through `LocalBackend` (W1's `ok` envelope bytes, W2's encode on the server side); first `REQUIRE` the reply's 200 keys. Add the rows to "Recorded baselines". + +- [ ] **Step 7: Neighbouring specs, mutations, docs build, commit** + +Write `registry.md`'s `BRIDGE_REGISTER_TABLE` section (what the macro emits, its options, the record's name and key, `TableOf`, the walk's rule for a holder's `heldRecord`, the opaque holding, that a table id is unique in the process and what happens when it is not, that both table actions are `Loggable::No`, and the admission rule: a principal may watch a table's record when it may run any action holding it, the table's own `Table.` or an action whose result holds its `ChangedRows`, so refusing a table means refusing all of them) and the `invoke` paragraph; `backend.md`'s `tableWork` row and Fan-out bullet. Nothing about `openMembers`, `partialMember` or `announce` (steps 2c, 2d). Apply each mutation; paste the failing lines into the commit body; run the docs build. + +```bash +git add include/morph/table/description.hpp include/morph/table/runtime.hpp include/morph/core src/ui/process_state.cpp CMakeLists.txt \ + tests/table tests/net docs/spec/core/registry.md docs/spec/core/backend.md docs/spec/table/table.md +git commit -m "feat(core): register tables of a model" +``` + +--- + +## Self-review + +**Spec coverage.** "The fixture", "The data", "How figures are taken" → Task 0 (layout, generator, guards, Release medians). Step 0's records S1, S2, S7, S8, B1, B2, B5, U1–U5, W7, F2–F5 and gate S3 → Task 0 Steps 6–7 and the S3 test. "The table tests are built for WebAssembly and run under Node" → Task 0 Step 5. Step 0a and "Paging in the database", "Rows in a database are a source too", the step-0a Neighbouring-specs row (`engine.md`, `database_pages.md`) → Task 0a. "A table is a description" (the four structs, `revision`), "Rows on the wire" (every encoding, `columns`, `keys`, `revision`), `TableQuery::columns`, W1, W5, W6's codec, W7 → Task 1. "A model's tables" (`TableContext`, `ServedTable`, strand then `tableWork`, services, scope, `scoped`, the action table, the table's record, `TableOf`, options, `ChangedRows`, `updatesTable`/`changesTable`, two members for two tables, the opaque holding), "Typed rows are a convenience", "A table on the server" (one `DataSource` per table and scope, `mayRead` narrowing), invariant 14's `mayRead` half and invariant 15, the fixture as a registered model with three tables and no slow level, W2, the step-1 Neighbouring-specs rows (`registry.md`, `backend.md`) → Task 2. Left to other parts by design: `levels` meaning and level-cache sharing ("A table on the server", second bullet) → Task 5; `announce` → Task 6; the client's refetch on a new `revision` → Task 9; `ChangedRow::from`, `FailedRow` → Task 17c; `Table..resolve` → Task 17a; unloaded and measure cells in the generic page → Tasks 4 and 8c. + +**Step scan.** Each test step names its cases and their assertions with the spec's values; the bodies written as comments state exact inputs and expected values. Code steps give signatures and the rules the tests do not determine (the cell codec, the generator, the hop to `tableWork`). The pinned digest is the one value computed during implementation, and the step says how. + +**Type consistency.** `GenericPage`, `writeGenericPage`, `readGenericPage`, `TableColumn`, `TableDescription`, `ServedTable`, `ChangedRows`, `TableOf` match the roadmap's Interfaces; `TableQuery::columns` and `QueryLimits::maxColumns` land in Task 1, and `ServerConfig::tableWork`, `answerQuery(…, AnswerContext const& = {})` and `TableRuntime`/`currentTableRuntime`/`TableRuntimeScope` are as the index's "Cross-part decisions" 1, 2, 5 and 6 name them. + +**Proportion.** About as long as the spec sections it implements; the code blocks are signatures, layouts and test assertions. diff --git a/docs/superpowers/plans/2026-11-17-one-table-b-slow-columns.md b/docs/superpowers/plans/2026-11-17-one-table-b-slow-columns.md new file mode 100644 index 000000000..22828561c --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-one-table-b-slow-columns.md @@ -0,0 +1,888 @@ +# Slow Columns: Unloaded Cells, Partial Pages, the Level and View Caches, the Window Under Changes — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A table served over `apply` and read through a `PageWindow` shows a first page before a slow level loads, shows its cells as unloaded, loads a level only when a named, sorted or filtered column needs it, and updates exactly the rows that arrived, with no polling. + +**Architecture:** The engine learns a fourth cell state (`Unloaded`), a three-valued filter and an undecided set (Task 3). Pages and the generic page carry which cells are unloaded and answer keyed queries (Task 4). The server gains a shared, immutable-snapshot level cache that loads each value once (Task 5), an `announce`/`attach` path and a view cache so a sort runs once for every watcher (Task 6). The client's `PageWindow` holds columns per page and turns change events into keyed fetches with probes or page refetches, and the session reads and watches without cache entries (Task 7). + +**Tech Stack:** C++23, header-only morph, glaze, Catch2, CMake/Ninja (MSVC preset `cl-debug`; timings on `cl-release`). + +**Spec:** `docs/spec/table/table.md` — "The unloaded cell", "Semantics of an unloaded cell" (all), "Data levels", "Partial pages", "Keyed queries", "Arrival", "The window under changes" (all), "Caching layers" through "Which client cache a screen uses", and their rows of "Tests", "Invariants", "Failure modes", "Performance" (S1–S9, L1–L8, C1–C3, W3, W4, K1–K7, E1–E4), "Neighbouring specs" (steps 2a–2d) and "Delivery order" (steps 2a–2d). Roadmap: `docs/superpowers/plans/2026-11-17-one-table.md`, Tasks 3–7. +Part B of 7; index: 2026-11-17-one-table.md + +## Global Constraints + +Every line of the roadmap's Global Constraints applies; the ones this part touches most: + +- Comments state what the code does now and why; no history, no issue numbers (AGENTS.md). +- Every public symbol has complete Doxygen `@param`/`@tparam`/`@return`; docs build: `cmake -S . -B build/doc -G Ninja -DMORPH_BUILD_DOCUMENTATION=ON -DMORPH_BUILD_TESTS=OFF -DMORPH_BUILD_EXAMPLES=OFF && cmake --build build/doc --target doc` exits 0. +- No company, product or customer names; examples use `lims`. +- Commits authored `yaraslau `, ending with the session's attribution lines. +- No GUI application is launched. +- Every test carries a `// Mutation: …` comment naming the change it was seen to fail on; the task applies that mutation once and pastes the failing line into the commit body. +- Limits verbatim: `QueryLimits::maxKeys = 1000` (`maxColumns = 512` is Task 1's); `PageWindow(pageSize = 200, maxPages = 8, maxKeys = 1000, maxColumns = 96)`; `LevelCacheOptions{maxBytes = 256U << 20U, expectedBytes = 0 (64 bytes a column), batch = 64, orderLease = 60 s, retryAfter = 30 s, retryMax = 600 s}`; `ViewCacheOptions::maxBytes = 64U << 20U`; `effects::kMaxChangeKeys = 4096` (existing); level cache shards: 256. +- Timings are never CI gates. Counts and bytes are, and run as ordinary test cases. Timings run by tag `"[.benchmark]"` on `cl-release` and are written into table.md's Performance tables; each benchmark first `REQUIRE`s that its feature was active. +- A spec that describes code takes its part in the task that builds it: `docs/spec/forms/views.md` (Task 3), `docs/spec/core/backend.md` "Fan-out" (Task 6), `docs/spec/core/registry.md` and `docs/spec/ui/interpreter.md` "Queries and the cache" (Task 7). + +**Commands** (``, `` per step): + +```bash +cmake --preset cl-debug +cmake --build --preset cl-debug --target +ctest --test-dir build/cl-debug -R "" --output-on-failure +# timings +cmake --preset cl-release && cmake --build --preset cl-release --target +build/cl-release/bin/.exe "" +``` + +Targets: `morph_table_tests` (tests/table/*), `morph_tests` (tests/test_*.cpp at the top level), `morph_net_tests` (tests/net/*). Catch2 test names are the ctest names, so `-R` takes a regex over them. `morph_net_tests` is POSIX-only (index decision 18): its cases build and run on Linux with `cmake --preset linux-everything && cmake --build --preset linux-everything --target morph_net_tests && ctest --test-dir build/linux-everything -R "" --output-on-failure`; on Windows only the `cl-debug` targets above run. + +## Interfaces from other parts + +These follow the index's "Cross-part decisions" and Part A (`2026-11-17-one-table-a-foundation.md`). + +- **A1. The answer path** (decision 5) is `table::detail::answerQuery(ServedTable const& served, TableQuery const& query, AnswerContext const& context = {}) -> std::expected` in `description.hpp`. Task 2 defines it with an empty `struct AnswerContext {}`. `QueryTable::invoke` gets the `ServedTable` through `table::detail::serve(model, context)` (decision 23), replaces `served.source` on the strand with a `detail::PinnedSource` of one snapshot, and runs `answerQuery` on the table executor, so `answerQuery` never snapshots a live source (tests that pass a live source get it pinned by `detail::pinned(served)`). Tasks 4 and 5 change its body; Task 6 adds `AnswerContext::{views, record, rowScoped}` (decision 48). +- **A2. Where table work runs** (decisions 1, 6). `ServerConfig::tableWork` (Task 2); `table::TableRuntime{exec::IExecutor* work = nullptr;}`, `table::currentTableRuntime()` and `table::TableRuntimeScope`, installed by `RemoteServer` around a dispatch (Task 2). Task 6 adds `ViewCache* views` to `TableRuntime` and `ServerConfig::views`; `QueryTable::invoke` builds `AnswerContext{.views = runtime->views}` from it. +- **A3. The fixture** (Tasks 0, 2). `WideTableSource` is internally synchronised and `WideTableModel::configure(wide, small)` may be called at any time (it drops both sources; the next table call rebuilds them). The key column is `id`, Integer, value `row + 1`, so row `r`'s key is `r + 1` and a table of n rows has keys 1…n. The model type id is `"WideTableModel"`, so the records are `"WideTableModel.wide"`, `"WideTableModel.small"`, `"WideTableModel.scoped"`. The `recipe` level's columns are named by Part A's layout (`bench::WideColumn::level`): `d000`…`d009` (Decimal) and `t001`…`t010` (Text) in `wide`; `small` (`wideColumns(30)`) has only `d000`…`d005` and `t001`…`t006` of them. Part A cannot set `ColumnInfo::level` (the member is Task 3's) and serves `TableDescription::levels` empty; Task 3a sets both (its Step 5). `scoped` serves `small`'s rows to every principal and varies its columns: every principal lacks `d000`…`d005` except `"extended"` (all 30), and `"restricted"` also lacks `t000`…`t006`. No fixture table scopes rows. +- **A4. The record walk** (Task 2). `ResultSlot` gains `bool opaque = false` and `effects::ActionRecord` gains `bool opaque = false`; `Table.`'s registration adds an opaque slot, so `recordsOf("Table.small") == {ActionRecord{.record = "WideTableModel.small", .keyField = "key", .paths = {}, .opaque = true}}`. A holder type with `heldRecord`/`heldMember()` reports its record at that member. Task 7b adds `open` and `partial` beside `opaque`, and copies all three to `ActionRecordInfo`. +- **A5.** Task 1's `GenericPage`, `writeGenericPage`, `readGenericPage`, `TableQuery::columns` and `QueryLimits::maxColumns` (decision 2), with `validate`'s `columns` rules; the writer writes `Unloaded` as `null` once Task 3 adds it (Task 3a gives `detail::appendCellJson` that branch). +- **A6. Equality** (decision 38). `QuantityCell::operator==` is Task 0's, so `Cell == Cell` compiles; `tabletest::sameCell(Cell const&, Cell const&)` (Task 0, `tests/table/table_fixtures.hpp`) compares places too. `GenericPage` has no `operator==`: a test that says a page "reads back equal" compares its members, cells by `sameCell`. +- **A7. Groups** (decision 43). Task 8b makes `detail::PinnedSource`, `LeveledSource` and the scoped source forward `DataSource::groups()`; nothing here overrides or hides it. + +--- + +### Task 3: Unloaded cells in the engine (table.md step 2a) + +Two commits, each its own reviewer gate: **3a** the cell, its order, the filter and the undecided set; **3b** data levels on columns, rows and pages. + +**Spec:** "The unloaded cell", "Semantics of an unloaded cell", "Data levels"; Tests rows (a) engine half, (b) ×3, (c) `levelsNeeded` table, (d) engine half; invariants 1, 2, 3 (without retain), 4, 5, 6 (first and third clause), 7; Failure modes "A level never arrives", "A `Unloaded` cell in a base-level column", "A `columnLevels()` entry naming no column", "An edit of an unloaded cell". + +**Files (3a):** +- Modify: `include/morph/table/data_source.hpp` (`Unloaded`, `Cell`, `ColumnInfo::level`, `TableErrorCode::SourceContract` and its glaze name, `displayText`) +- Modify: `include/morph/table/sort.hpp` (`CellState`, `KeyColumn::read`, `compareKeys`) +- Modify: `include/morph/table/filter.hpp` (`Match`, `evaluate`, `evaluateGroup`, `evaluateRow`, `FilterRun`) +- Modify: `include/morph/table/engine.hpp` (`detail::JobInput`, `detail::JobResult`, `detail::ViewJob`, `Engine`) +- Modify: `include/morph/table/query.hpp` (`apply`: undecided, `totalKind`; `PageRows::{totalKind, undecided, awaiting, failed}`) +- Modify: `include/morph/table/edits.hpp` (`CellEdits::commit`) +- Modify: `include/morph/table/description.hpp` (`detail::appendCellJson` writes `Unloaded` as `null`, so the header compiles with the new alternative; Task 4 tests it) +- Modify: `tests/table/table_fixtures.hpp` (`levelCol`, `slowColumn`) +- Modify: `tests/table/wide_table_model.{hpp,cpp}` (`WideTableSource::columns()` sets `ColumnInfo::level` from `WideColumn::level`; the model's three descriptions set `levels = {"recipe"}`) +- Create: `tests/table/test_table_unloaded_cells.cpp` (add to `morph_table_tests` in `tests/CMakeLists.txt`) +- Test: `tests/table/test_table_sort.cpp`, `tests/table/test_table_filter.cpp`, `tests/table/test_table_changes.cpp` + +**Files (3b):** +- Modify: `include/morph/table/query.hpp` (`ColumnLevel`, `LevelLoaded`, `RowsSnapshot`, `RowsSource`, typed `apply`, `LevelsNeeded`, `levelsNeeded`, `UnloadedRow`, `Page::{unloadedRows, undecided, awaiting, failed}`) +- Modify: `include/morph/forms/forms.hpp` (`detail::mergeSchemaExtras` writes `x-level`), `include/morph/forms/views.hpp` (`buildColumnEntry` copies `x-level`), `include/morph/forms/engine/collection.hpp` (`CollectionColumn::level`) +- Modify: `tests/table/wide_table_model.{hpp,cpp}` (`bench::UnloadedSource`, `bench::withUnloaded`), `tests/table/bench_table.cpp` (S1, S2, S4–S6) +- Test: `tests/table/test_table_unloaded_cells.cpp`, `tests/table/test_table_query.cpp`, `tests/test_views.cpp` +- Docs: `docs/spec/forms/views.md` (`x-level` on a schema property; `deriveColumns` copies it) + +**Interfaces:** +- Consumes: `bench::WideTableOptions`, `bench::WideTableSource` (Task 0). +- Produces (3a): + - `EngineStats::filterRuns` (`std::size_t`): incremented by the `Engine` when it applies a job result whose `detail::JobResult::filtered` is set; `ViewJob::plan()` sets `filtered` when it constructs a `FilterRun` (a repair never does) + - `struct Unloaded { friend constexpr bool operator==(Unloaded, Unloaded) noexcept = default; };` + - `using Cell = std::variant;` (Task 8c appends `Measure` after it) + - `ColumnInfo::level` (`std::string`, after `format`; part of `operator==`). It lands in 3a because the base-level rule needs it: a cell may be `Unloaded` only in a column with a level. + - `TableErrorCode::SourceContract` (JSON `"sourceContract"`, appended last) + - `CellState::Unloaded` (appended after `Invalid`) + - `enum class Match : std::uint8_t { No, Yes, Unknown };` in `filter.hpp` + - `static Match CompiledFilter::evaluate(Column const& filter, KeyColumn const& keys, std::uint32_t row);` `static bool passes(...)` returns `evaluate(...) == Match::Yes` + - `static Match CompiledFilter::evaluateGroup(Group const& group, std::span keys, std::uint32_t row);` (keys by column index) + - `Match CompiledFilter::evaluateRow(std::span keys, std::uint32_t row) const;` + - `std::vector FilterRun::take() &&` (the `Yes` rows), `std::vector FilterRun::takeUndecided() &&` (the `Unknown` rows); both keep candidate order; each may be called once, in either order + - `detail::JobInput::previousUndecided`, `detail::JobResult::undecided` (`std::vector`, source rows ascending) + - `std::optional const& detail::ViewJob::failure() const noexcept` (replaces the `std::optional`) + - `std::size_t Engine::undecidedRowCount() const noexcept;` `std::span Engine::undecidedRows() const noexcept;` `void Engine::onUndecidedChange(std::function handler);` + - `PageRows::{TotalKind totalKind; std::int64_t undecided; std::vector awaiting; std::vector failed;}` +- Produces (3b): + - `struct ColumnLevel { std::string_view column; std::string_view level; };` + - `template using LevelLoaded = std::function;` + - `RowsSource(rows, key, kinds = {}, comparators = {}, LevelLoaded loaded = {})`; typed `apply(rows, key, query, options = {}, kinds = {}, comparators = {}, LevelLoaded loaded = {})` + - `struct LevelsNeeded { std::vector order; std::vector display; };` + - `[[nodiscard]] LevelsNeeded levelsNeeded(TableQuery const& query, std::span columns, std::function const& mayRead = {}, Services const& services = {});` + - `struct UnloadedRow { std::int64_t index = 0; std::vector levels; std::vector failed; [[nodiscard]] bool operator==(UnloadedRow const&) const = default; };` (decision 38) + - `Page::{std::vector unloadedRows; std::int64_t undecided = 0; std::vector awaiting; std::vector failed;}` + - `CollectionColumn::level` (`std::string`) + - Test helpers (3a): `tabletest::levelCol(std::string id, ColumnKind kind, std::string level) -> ColumnInfo`; `tabletest::slowColumn(ColumnKind kind, std::vector cells) -> std::shared_ptr` (one column `c` at level `"slow"`, keys 0…n−1). (3b): `class bench::UnloadedSource final : public DataSource` and `bench::withUnloaded(std::shared_ptr source, std::vector columns, std::string level, double loadedFraction, std::uint64_t seed) -> std::shared_ptr` (a wrapping source: the named columns get `level`, and a deterministic `1 - loadedFraction` of rows, chosen by `(seed, row)`, read `Unloaded` there). `void UnloadedSource::load(std::span rows)` marks those source rows loaded, publishes a new snapshot and notifies its own listeners `RowChange{Updated, rows}`: this is how a test makes rows arrive. `std::vector UnloadedSource::unloadedRows() const` lists the rows still unloaded, ascending. It subscribes to the wrapped source and forwards its changes + +#### 3a — the cell, its order, the filter and the undecided set + +- [ ] **Step 1: Write the failing order tests** in `tests/table/test_table_sort.cpp` + +```cpp +// Mutation: compareKeys tying unloaded with empty (rank Empty, Invalid and Unloaded alike). +TEST_CASE("table: unloaded cells are the tail after the empties in both directions", "[table][sort][unloaded]") { + using morph::table::Unloaded; + auto source = tabletest::slowColumn(ColumnKind::Integer, + {Cell{std::int64_t{3}}, Cell{Unloaded{}}, Cell{}, Cell{std::int64_t{1}}, + Cell{Unloaded{}}, Cell{std::string{"x"}}}); + for (auto const dir : {SortDirection::Ascending, SortDirection::Descending}) { + Engine engine{source}; + REQUIRE(engine.setSort({SortKey{.column = "c", .dir = dir}})); + auto const keys = tabletest::viewKeys(engine); + auto const valid = dir == SortDirection::Ascending ? std::vector{3, 0} : std::vector{0, 3}; + CHECK(std::vector(keys.begin(), keys.begin() + 2) == valid); + CHECK(std::vector(keys.begin() + 2, keys.begin() + 4) == std::vector{2, 5}); // empty, invalid + CHECK(std::vector(keys.begin() + 4, keys.end()) == std::vector{1, 4}); // unloaded + } +} +``` + +Every column that holds an `Unloaded` cell in this plan's tests is declared with a level (`levelCol`, `slowColumn`); a base-level one is the `SourceContract` case. + +Add `"table: rows with no unloaded sort cell keep their order under any completion"` (invariant 2): 200 random tables of 40 rows × 2 `Integer` columns at level `"slow"` from `std::mt19937{seed}` with 20% `Unloaded`; for each, 20 random completions replacing every `Unloaded` with an integer; for every pair of rows with no unloaded cell in the sort columns, their relative order under `setSort({a asc, b desc})` is the same before and after. Mutation: `compareKeys` answering 0 whenever either cell is `Unloaded` (an unloaded cell tying with every cell, which breaks transitivity, so the sort may order two loaded rows by where the unloaded rows sit). Ranking `Unloaded` as `Valid` with key 0 is not a usable mutation: the relative order of two loaded rows depends on their own keys under any consistent comparator, so the property holds and the case passes. + +- [ ] **Step 2: Write the failing filter tests** in `tests/table/test_table_filter.cpp` + +```cpp +// Mutation: evaluate returning passes (two-valued), which rejects the unloaded row. +TEST_CASE("table: an unloaded cell is unknown to every operator", "[table][filter][unloaded]") { + using morph::table::Unloaded; + struct Case { ColumnKind kind; FilterEntry entry; }; + std::vector const cases{ + {ColumnKind::Integer, {.eq = "1"}}, {ColumnKind::Integer, {.ne = "1"}}, {ColumnKind::Integer, {.lt = "1"}}, + {ColumnKind::Integer, {.le = "1"}}, {ColumnKind::Integer, {.gt = "1"}}, {ColumnKind::Integer, {.ge = "1"}}, + {ColumnKind::Decimal, {.between = std::array{"1", "2"}}}, + {ColumnKind::Text, {.contains = "a"}}, {ColumnKind::Text, {.startsWith = "a"}}, + {ColumnKind::Text, {.endsWith = "a"}}, {ColumnKind::Date, {.eq = "2026-01-01"}}, + {ColumnKind::Bool, {.eq = "true"}}, {ColumnKind::Text, {.isEmpty = true}}, + {ColumnKind::Text, {.notEmpty = true}}}; + for (auto const& [kind, entry] : cases) { + for (bool const exclude : {false, true}) { + for (auto const combine : {Combine::Any, Combine::All}) { + auto source = tabletest::slowColumn(kind, {Cell{Unloaded{}}}); + ColumnFilter filter{.combine = combine}; + (exclude ? filter.exclude : filter.include).push_back(entry); + auto page = apply(*source, TableQuery{.filters = FilterSpec{.columns = {{"c", filter}}}}); + REQUIRE(page.has_value()); + CHECK(page->rows.empty()); + CHECK(page->undecided == 1); + CHECK(page->total == 0); + CHECK(page->totalKind == TotalKind::AtLeast); + } + } + } +} +``` + +Add: +- `"table: a group admits on one loaded match and is unknown otherwise"`: columns `a`, `b` Text at level `"slow"`; group `{columns {a,b}, include {contains "x"}}`; rows `{x, Unloaded}` → view; `{Unloaded, y}` → undecided; `{y, z}` → rejected; `{Unloaded, Unloaded}` → undecided. Mutation: a group evaluated as `all` of its columns. +- `"table: a row unknown at one stage and rejected at a later one is rejected"`: filters `a eq "1"` (row's `a` unloaded) and `b eq "2"` (row's `b` = `"3"`): `rows` empty, `undecided == 0`, `totalKind == Exact`. Mutation: `FilterRun` dropping the undecided mark when a later stage answers `No` (keeping the row undecided). +- `"table: the filter is sound under every completion"` (invariant 1): 200 random tables of 30 rows × 3 columns (`Integer`, `Text`, `Bool`, level `"slow"`) with 25% `Unloaded`, random filters of 1–3 column entries and 0–1 group from `{eq, ne, lt, gt, contains, isEmpty, notEmpty}` in include and exclude; 20 completions each: every row of the view is in the completed view, every rejected row is rejected there. Mutation: `evaluate` answering `No` for `ne` on an unloaded cell. + +- [ ] **Step 3: Write the failing engine tests** — `tests/table/test_table_unloaded_cells.cpp` (header: what the file covers; each case its `// Mutation:`) + +- `"table: a base-level unloaded cell is a source contract error"`: `apply` over a source whose column `c` (`tabletest::col`, level `""`) holds `Unloaded` in row 1 returns `TableErrorCode::SourceContract` with `.column == "c"` when sorting by `c`. A synchronous `Engine engine{source}` returns a failed job from the call that asked for it, so `engine.setSort({SortKey{.column = "c"}})` returns the same error (not through `onError`), `engine.sort()` is empty and `viewKeys` is as before. `onError` is for a job no call could return: over a fully loaded copy of the table already sorted by `c`, with an `onError` handler set, `source->updateRow(1, {Cell{Unloaded{}}})` calls the handler once with `SourceContract` and `.column == "c"`, and `viewKeys` is as before the update. The same table with `c` at level `"slow"` sorts with row 1 last. Mutation: key building without the base-level check (both halves: `setSort` succeeds, the handler is not called). +- `"table: cellAt returns the unloaded cell"`: `engine.cellAt(0, 0)` holds `Unloaded` and `displayText(engine.cellAt(0, 0)) == ""`. Mutation: `displayText` returning `"…"`. +- `"table: an edit of an unloaded cell is refused on the cell"`: a `VectorSource` with columns `c` (level `"slow"`, row 0 `Unloaded`) and `d` (base, row 0 `"x"`); `CellEdits edits{*source, commit, &engine}`; `edits.commit({.row = 0, .column = "c", .value = Cell{std::int64_t{5}}})`: the commit function is not called and `edits.error(0, "c") == "not loaded yet"`; an edit of loaded column `d` of the same row is committed. Mutation: `commit` not looking at the cell. +- `"table: selectAll does not select undecided rows"` and `"table: a selected row that becomes undecided is pruned"` (`SelectionOptions{.pruneOnFilter = true}`; row 1 selected, its filtered cell updated to `Unloaded` via `updateRow`: `selection.contains(1)` is false). Mutations: `selectAll` over `view ∪ undecided` (the first case); `Selection::viewChanged` keeping a selected row that is in the undecided set (the second, which the first mutation does not reach). + +Engine half of (d) in `tests/table/test_table_changes.cpp`: + +```cpp +// Mutation: a repair that ignores previousUndecided (an arrived row stays undecided). +TEST_CASE("table: an undecided row that arrives is one insert and one count change", "[table][changes][unloaded]") { + using morph::table::Unloaded; + auto source = tabletest::makeSource({tabletest::levelCol("a", ColumnKind::Integer, "slow")}, + {{Cell{std::int64_t{1}}}, {Cell{Unloaded{}}}, {Cell{std::int64_t{3}}}}); + Engine engine{source}; + REQUIRE(engine.setSort({SortKey{.column = "a"}})); + REQUIRE(engine.setFilter(FilterSpec{.columns = {{"a", ColumnFilter{.include = {FilterEntry{.gt = "0"}}}}}})); + CHECK(engine.undecidedRowCount() == 1); + std::vector counts; + std::vector order; + ViewChange last; // the engine has one view handler: record here rather than through FollowingModel + engine.onViewChange([&](ViewChange const& change) { last = change; order.emplace_back("view"); }); + engine.onUndecidedChange([&](std::size_t count) { counts.push_back(count); order.emplace_back("undecided"); }); + source->updateRow(1, {Cell{std::int64_t{2}}}); + CHECK(tabletest::viewKeys(engine) == std::vector{0, 1, 2}); + REQUIRE(last.ops.size() == 1); + CHECK(last.ops[0].kind == ViewOp::Kind::Inserted); + CHECK(last.ops[0].first == 1); + CHECK(last.ops[0].count == 1); + CHECK(counts == std::vector{0}); + CHECK(order == std::vector{"view", "undecided"}); +} +``` + +Add: +- `"table: an undecided row rejected on arrival is no view operation"`: same table, `updateRow(1, {Cell{std::int64_t{-5}}})`: `onViewChange` not called, `counts == {0}`. Mutation: `onUndecidedChange` called only with a view change. +- `"table: a displayed row whose level arrives is changed in place"` for `ReorderPolicy::Immediate` and `Deferred`: sorted by `a`, filtered on nothing, row 1's non-sort column `b` goes from `Unloaded` to `"x"`: one `Changed` op at view row 1, no `Moved`. Mutation: a repair appending the dirty rows after the clean ones rather than merging them, which reports the arrived row as `Moved`. +- `"table: a cell dropped back to unloaded moves to the tail or leaves the view"` (Review Focus 2): sorted ascending by `a`, unfiltered, row 0's `a` updated from `1` to `Unloaded`: row 0 is last; with `a gt 0` filtered, the same update makes it undecided (`viewKeys` lacks 0, `undecidedRowCount() == 1`). Mutation: `KeyColumn::set` keeping the old key for a cell that became `Unloaded`. +- `"table: under deferred reorder an undecided row takes its true place at once"` (Review Focus 5): `EngineOptions{.reorder = ReorderPolicy::Deferred}`, view `{0: 1, 2: 3}`, undecided row 1 arrives with `2`: `viewKeys == {0, 1, 2}` before `settleNow()`, and `heldRows()` does not contain 1. Mutation: the repair holding entering rows like updated ones. + +- [ ] **Step 4: Run the new cases to verify they fail** + +Run: `cmake --build --preset cl-debug --target morph_table_tests` +Expected: compile errors naming `Unloaded`, `undecided`, `onUndecidedChange`, `totalKind` on `PageRows`. + +- [ ] **Step 5: Implement the cell, `ColumnInfo::level`, `displayText` and `SourceContract`** in `data_source.hpp` + +`ColumnInfo::level` carries the spec's Doxygen ("The data level the column's cells need. Empty is the base level, which every row has when it exists."); `tabletest::col` keeps its signature (level empty). `displayText` gets an `Unloaded` branch returning `{}`, and `detail::appendCellJson` (`description.hpp`) one writing `null`. The glaze enumeration of `TableErrorCode` adds `"sourceContract", SourceContract`. + +The fixture takes its levels here, because nothing before this commit could: `WideTableSource::columns()` sets each column's `level` from `WideColumn::level` (`"recipe"` on `d000`…`d009` and `t001`…`t010`), so the description columns `WideTableModel` builds from them carry it, and `wide`, `small` and `scoped` set `description.levels = {"recipe"}` (a description that lacks every recipe column sets none). Until Task 5 gives the level a cache, the cells of those columns are read from the source and are loaded. A Part A case that pins `levels` empty, or a description revision computed without levels, is updated in this commit. + +- [ ] **Step 6: Implement the order** in `sort.hpp` + +`KeyColumn::read` first maps `Unloaded` to `CellState::Unloaded` (before the empty check and the kind switch) and stores no key. `compareKeys` compares a rank before keys, ignoring `dir`: + +```cpp +// Valid 0; Empty and Invalid 1 (they tie); Unloaded 2 (they tie). Ranks never flip with the direction. +int const rankA = rank(keys.states[left]); +int const rankB = rank(keys.states[right]); +if (rankA != rankB) { return rankA < rankB ? -1 : 1; } +if (rankA != 0) { return 0; } +``` + +`RowOrder` already breaks ties by source row. + +- [ ] **Step 7: Implement the three-valued filter** in `filter.hpp` + +- `evaluate`: a cell whose state is `Unloaded` is `Unknown` whatever the entries (`isEmpty`, `notEmpty` and `exclude` included); otherwise `Yes`/`No` exactly as the current `passes` body. +- `evaluateGroup` (plain group; Task 8b adds quantifiers): `Yes` if any column is `Yes`; else `Unknown` if any is `Unknown`; else `No`. +- `evaluateRow`: `No` if any column filter or group is `No`; else `Unknown` if any is `Unknown`; else `Yes`. +- `FilterRun` keeps a mark per candidate (`std::vector`, compacted with `_rows`): a stage answering `No` drops the row, `Unknown` keeps it marked, `Yes` keeps it as it was. `take()` returns the unmarked survivors, `takeUndecided()` the marked ones. + +- [ ] **Step 8: Implement the undecided set** in `engine.hpp` + +- `ViewJob::step` maps an exception to `TableError{ServiceFailed, {}, "a service failed: " + what}`; the three call sites (`Engine` ×2, `apply`) use `failure()` as the error directly. +- Key building: after a needed column's keys are built, and after each dirty row is patched, a column with `level.empty()` holding a `CellState::Unloaded` fails the job with `TableError{SourceContract, , "an unloaded cell in a base-level column"}`. +- `order()`: after the filter run, `_result.undecided = std::move(run).takeUndecided()` sorted ascending. +- `repair()`: each dirty row is evaluated with `evaluateRow`: `Yes` joins `passing`, `Unknown` joins the new undecided rows, `No` neither; `_result.undecided` = (`previousUndecided` minus `dirty`, both ascending: a set difference, no filter run) ∪ the new undecided, ascending. +- `Engine` keeps `_undecided` with `_view` and passes it as `previousUndecided`; on applying a result it sets `_undecided`, then calls `onViewChange` if the view changed, then `onUndecidedChange(count)` if the count differs from the one before the job. +- A row entering the view from the undecided set is not in `previousView`, so under `Deferred` the diff inserts it at its true place; displayed rows keep their held places. + +- [ ] **Step 9: Implement totals and the edit refusal** + +- `apply` fills `PageRows::undecided` from the job's `undecided.size()` and `totalKind = undecided > 0 ? AtLeast : Exact`; `total` stays absent above `totalCap`. +- `CellEdits::commit`: when `_engine` is set and `_engine->viewRowOfKey(request.row)` finds a row whose `cellAt(viewRow, column)` holds `Unloaded` (column found by id in `_engine->columns()`), it records the error `"not loaded yet"` for the cell and returns without queueing; the cell's other edits are unaffected. + +- [ ] **Step 10: Run the target** + +Run: `cmake --build --preset cl-debug --target morph_table_tests && ctest --test-dir build/cl-debug -R "^table" --output-on-failure` +Expected: all pass, the new cases included. + +- [ ] **Step 11: Apply each named mutation, see its test fail, revert. Commit** + +```bash +git add include/morph/table tests/table tests/CMakeLists.txt +git commit -m "feat(table): unloaded cells, their order and the undecided set" +``` + +#### 3b — data levels on columns, typed rows and pages + +- [ ] **Step 12: Write the failing level tests** in `tests/table/test_table_query.cpp` + +```cpp +// Mutation: levelsNeeded returning every level of the columns. +TEST_CASE("table: levelsNeeded names the levels a query sorts, filters and shows", "[table][query][levels]") { + using tabletest::levelCol; + std::vector const columns{tabletest::col("id", ColumnKind::Integer), + levelCol("r1", ColumnKind::Decimal, "recipe"), + levelCol("r2", ColumnKind::Text, "recipe"), + levelCol("s1", ColumnKind::Text, "stock"), + levelCol("p1", ColumnKind::Integer, "price")}; + auto const needed = [&](TableQuery const& query) { return levelsNeeded(query, columns); }; + using V = std::vector; + TableQuery named{.columns = V{"id", "r2"}}; + CHECK(needed(named).order.empty()); + CHECK(needed(named).display == V{"recipe"}); + TableQuery sorted{.sort = {SortKey{.column = "s1"}}, .columns = V{"id"}}; + CHECK(needed(sorted).order == V{"stock"}); + CHECK(needed(sorted).display.empty()); + TableQuery filtered{.filters = FilterSpec{.columns = {{"p1", ColumnFilter{.include = {{.gt = "1"}}}}}}, + .columns = V{"p1"}}; + CHECK(needed(filtered).order == V{"price"}); + CHECK(needed(filtered).display == V{"price"}); + TableQuery grouped{ + .filters = FilterSpec{.groups = {GroupFilter{.columns = {"r2", "s1"}, .include = {{.contains = "a"}}}}}, + .columns = V{}}; + CHECK(needed(grouped).order == V{"recipe", "stock"}); + TableQuery emptyGroup{.filters = FilterSpec{.groups = {GroupFilter{.columns = {"r1", "s1"}}}}, .columns = V{}}; + CHECK(needed(emptyGroup).order.empty()); // a group with no entry reads no column + CHECK(needed(TableQuery{.columns = V{"id"}}).display.empty()); + CHECK(needed(TableQuery{}).display == V{"price", "recipe", "stock"}); // columns absent: every column + CHECK(levelsNeeded(TableQuery{}, columns, [](std::string_view c) { return c != "p1"; }).display == + V{"recipe", "stock"}); // only what the caller may read + CHECK(needed(TableQuery{.columns = V{}}).display.empty()); // columns empty: keys alone +} +``` + +(`TableQuery::columns` is Task 1's, decision 2.) + +In `tests/table/test_table_unloaded_cells.cpp`: + +- `"table: apply reads only the sorted and filtered columns"` (row (a), gate S3 with levels): a recording `DataSource` wrapping `bench::withUnloaded(WideTableSource{{.rows = 1000, .columns = 300, .seed = 7}}, `d000`…`d009`, `t001`…`t010`, "recipe", 0.7, 7)` logs the column of every `cell` and `readColumn` call; `apply` sorted on one recipe decimal and filtered `contains "a"` on one recipe text returns a page; the logged columns are exactly those two. Mutation: `apply` building keys for every column. +- `"table: a typed page names exactly its unloaded rows and levels"` (row (b)): rows `struct LevelRow { std::int64_t id; std::string name; std::int64_t qty; static constexpr std::array columnLevels() noexcept { return {{{"qty", "stock"}}}; } };` ids 0–9, `LevelLoaded` refusing `stock` for odd ids; typed `apply` with `columns` absent: `unloadedRows` is `{{1,{"stock"},{}}, {3,…}, {5,…}, {7,…}, {9,…}}` in index order; with `columns = {"id","name"}` and no sort/filter on `qty`, `unloadedRows` is empty (the level is not needed). Mutation: the typed `apply` dropping `unloadedRows`. +- `"typed: a row's column levels reach the description"` (in `tests/table/test_table_description.cpp`): `detail::serve<&LevelModel::rows>(model, ctx).description` for a typed table of `LevelRow` has column `qty` with `info.level == "stock"` and `levels == {"stock"}`. Mutation: `columnLevels()` applied in `RowsSource` only, not in `reflectedColumns`. +- `"table: a column level naming no column is refused where columns are reflected"`: a row whose `columnLevels()` names `"nope"`: `RowsSource` construction throws `std::invalid_argument` whose message contains `nope`. Mutation: the entry ignored. +- `"table: a typed table without levels is whole"` (invariant 7): typed `apply` with no `LevelLoaded` and no `columnLevels()` yields `unloadedRows`, `awaiting`, `failed` empty, `undecided == 0`, `totalKind == Exact`, and the same `rows`, `total` as before this change; and the same for `LevelRow` (which has `columnLevels()`) with no `LevelLoaded`, since empty means every level is loaded. Mutation: `awaiting` filled with every level of the columns when `loaded` is empty (only the `LevelRow` half can fail on it: a row with no `columnLevels()` has no level to fill `awaiting` with). + +In `tests/test_views.cpp`: `"views: deriveColumns copies x-level"` — for `LevelRow`, `forms::schemaJson()` has `"x-level":"stock"` on `qty`, and `deriveColumns` gives that column `level == "stock"` (and `CollectionColumn::level` reads it). Mutation: `buildColumnEntry` not copying `x-level`. + +- [ ] **Step 13: Run the new cases to verify they fail** — `cmake --build --preset cl-debug --target morph_table_tests morph_tests`; expected: compile errors naming `level`, `levelsNeeded`, `unloadedRows`, `ColumnLevel`. + +- [ ] **Step 14: Implement levels on typed rows, pages and schemas** + +- `detail::reflectedColumns()` (in `query.hpp`, which Task 2's `typed` also reads) applies `Row::columnLevels()` when the member function exists: each entry sets that column's `level`; an entry naming no column throws `std::invalid_argument{"columnLevels() names no column: "}`. So `RowsSource` and Task 2's `typed` description both carry the levels, and 3b changes `typed`'s description builder (`detail::serve`'s typed branch) to set `description.levels` to the sorted, unique non-empty levels of its columns. `RowsSnapshot` holds the `LevelLoaded` and a per-column level; `cell` and `readColumn` return `Unloaded{}` for a column whose level the predicate refuses, without calling the member's reader. +- `levelsNeeded`: `order` = levels of exactly the columns `apply` builds keys for: every sort key's column, and `compileFilterGuarded(query.filters, columns, services)->columnsUsed()` (so a column filter with an entry; a group's column only when the group has an `include` entry and one of them compiles on it; nothing from a filter that does not compile) (Task 8a adds the distinct request's column or group); `display` = levels of `query.columns`, or of every column `mayRead` allows when absent; both sorted, unique, without `""`. No rows read. The typed `apply` passes `options.services.forTask()`. A second case, `"table: levelsNeeded leaves out a group's column on which no entry compiles"`: group `{r1 Decimal, s1 Text}` with `contains "a"` → `order == {"stock"}`, with `gt "5"` → `{"recipe"}`. Mutations: a group with no `include` entry adding its columns (first case); a group's column on which no entry compiles added (second case). +- Typed `apply`: copies `undecided`, `totalKind`, `awaiting`, `failed` from `PageRows`; builds `unloadedRows` for the page's rows from `LevelLoaded` over the needed levels (`order ∪ display`), each row's `levels` sorted; `failed` per row stays empty (a predicate cannot say a load failed). `awaiting` = the `order` levels the predicate refuses for at least one row of the view or the undecided set. Without a predicate all three stay empty. +- `forms::detail::mergeSchemaExtras` writes `"x-level": ` on each property `columnLevels()` names; `views::buildColumnEntry` adds `"x-level"` to the keys it copies; `CollectionColumn::level` reads it. +- `bench::UnloadedSource` and `bench::withUnloaded` as the Interfaces block state; its snapshot hands runs through `readColumn`, and `load(rows)` is one new snapshot and one `Updated` notification for all of `rows`. + +- [ ] **Step 15: Add the benchmarks** in `tests/table/bench_table.cpp`, tag `"[.benchmark][table][unloaded]"`, each first `REQUIRE`-ing unloaded cells present: +- S1: `apply`, sort one recipe decimal, page 200, 100,000 × 300 via `withUnloaded(…, 0.7, 7)`, against the same with `loadedFraction = 1.0`. S2: text `contains` on a recipe text column. +- S4: `levelsNeeded` over 300 columns, 8 sort keys, 32 filtered columns. +- S5: an `Engine` over a `bench::UnloadedSource` (`withUnloaded(…, 0.7, 7)`) sorted on a recipe decimal, 100,000 rows; `source->load(rows)` of the first 200 and then the next 1,000 of `unloadedRows()`. Gates as ordinary cases (`"table: an arrival is one repair"`): each `load` raises `EngineStats::repairs` by one and `fullSorts` by none, and the arrived rows sit at the view rows a fresh `apply` over the same snapshot gives (the oracle). Mutation: `load` notifying `Reset` (a full sort instead of a repair). +- S6: 50,000 undecided rows (filter on a recipe column with 50% loaded), 1,000 of them decided by one `load`: gate case `"table: deciding rows runs no filter over all rows"`: one repair, `EngineStats::filterRuns` unchanged by the arrival, and each decided row is in the view or rejected as the oracle has it. Mutation: a repair that constructs a `FilterRun` over `previousUndecided`. + +- [ ] **Step 16: Run the targets** — `ctest --test-dir build/cl-debug -R "^(table|views)" --output-on-failure`: all pass. Record S1, S2, S4–S6 on `cl-release` into table.md's "Benchmarks: server" table (median, p10–p90, load average). + +- [ ] **Step 17: Update `docs/spec/forms/views.md`** (`x-level` on a schema property; `deriveColumns` copies it to the column as it copies `x-comparator`). Docs build green. + +- [ ] **Step 18: Mutations, then commit** + +```bash +git add include/morph/table include/morph/forms tests docs/spec +git commit -m "feat(table): data levels on columns, typed rows and pages" +``` + +--- + +### Task 4: Partial pages and keyed queries on the wire (table.md step 2b) + +**Spec:** "Partial pages", "Keyed queries", "Data levels" (the `columns` rules of `validate`); Tests rows "`TableQuery` on the wire", "The generic page" (unloaded); Failure modes "A keyed query to a model that does not translate keys", "A query's `columns` names a column the table lacks…". + +**Files:** +- Modify: `include/morph/table/query.hpp` (`TableQuery::keys`, `TableQuery::retry`; `QueryLimits::maxKeys`; `validate`'s keyed rules; `PageRows::indices`; `Page::indices`; `UnloadedLevels`; `detail::ComputedView`, `detail::computeView`, `detail::pageRows`; keyed `apply`) +- Modify: `include/morph/table/description.hpp` (`GenericPage::{unloadedRows, undecided, awaiting, failed, indices}`; the writer and reader; `detail::answerQuery`, A1) +- Test: `tests/table/test_table_query.cpp`, `tests/table/test_table_description.cpp`; benchmarks in `tests/table/bench_table.cpp` + +**Interfaces:** +- Consumes: Task 3's `PageRows`, `UnloadedRow`, `Page`; Task 1's `GenericPage`, `writeGenericPage(PageRows const&, DataSource const&, std::span columns)`, `readGenericPage(std::string_view, TableDescription const&)`; `TableQuery::columns`, `QueryLimits::maxColumns` and their `validate` rules (Task 1, A5). +- Produces: + - `TableQuery::keys` (`std::optional>`, after `columns`) and `TableQuery::retry` (`bool retry = false`, after `keys`; Task 8a puts `distinct` before it, as the spec's block orders them) — decision 25 + - `QueryLimits::maxKeys = 1000` + - `PageRows::indices`, `Page::indices` (`std::vector`, after `failed`) + - `struct UnloadedLevels { std::span levels; std::span failed; };` + - `struct detail::ComputedView { std::vector rows; std::vector undecided; };` + - `[[nodiscard]] std::expected detail::computeView(DataSource const& source, TableQuery const& validated, ApplyOptions const& options);` + - `using detail::SourceRowOf = std::function(RowId const&)>;` + - `[[nodiscard]] PageRows detail::pageRows(detail::ComputedView const& view, RowSnapshot const& snapshot, TableQuery const& validated, QueryLimits const& limits, std::span viewRowOf = {}, detail::SourceRowOf const& sourceRowOf = {});` (`viewRowOf`: view row by source row, `UINT32_MAX` for absent; built on demand when empty. `sourceRowOf`: a key's source row; when empty, a keyed query scans the snapshot's row ids once. Task 6 passes the view cache entry's two lookups, so a keyed query over a cached view reads no row id it was not asked for) + - `GenericPage::{std::vector unloadedRows; std::int64_t undecided = 0; std::vector awaiting; std::vector failed; std::vector indices;}` + +- [ ] **Step 1: Write the failing wire tests** in `tests/table/test_table_query.cpp` + +```cpp +// Mutation: TableQuery's JSON leaving out `keys` (a glz::meta naming every member but `keys`). +TEST_CASE("table: columns and keys round-trip through glaze", "[table][query][keyed]") { + TableQuery query; + query.columns = std::vector{"id", "name"}; + query.keys = std::vector{RowId{std::int64_t{7}}, RowId{std::string{"A-1"}}}; + query.retry = true; + std::string json; + REQUIRE_FALSE(glz::write_json(query, json)); + TableQuery back; + REQUIRE_FALSE(glz::read_json(back, json)); + CHECK(back.columns == query.columns); + CHECK(back.keys == query.keys); + CHECK(back.retry); + TableQuery bare; + REQUIRE_FALSE(glz::read_json(bare, R"({"sort":[],"filters":{},"page":{"offset":0,"limit":200}})")); + CHECK_FALSE(bare.columns.has_value()); + CHECK_FALSE(bare.keys.has_value()); + CHECK_FALSE(bare.retry); +} +``` + +Add: +- `"table: validate refuses a keyed query out of bounds"`: `keys` with `page.offset = 10` → `InvalidSpec`; 1,001 keys → `LimitExceeded`; a text key of 257 bytes → `LimitExceeded`. Mutation: the keyed checks skipped. +- `"table: a keyed query to a table without keyed queries is unavailable"` (`test_table_description.cpp`): `detail::answerQuery` over a description with `capabilities.keys = false` answers a query with `keys` set `TableErrorCode::Unavailable`; the same table answers a page. Every other table answers keyed queries through `answerQuery`, so this is the one server-side form of the spec's "a model that does not translate keys"; the client's fallback to `invalidate` is `WindowRows`'s (Task 9). Mutation: `answerQuery` ignoring `capabilities.keys`. +- `"table: an empty columns list gives a page of keys"` (generic, `test_table_description.cpp`; skip if Task 1 already pins it): `detail::answerQuery` over a 3-row table with `columns = {}` returns `columns.empty()`, `keys == {0,1,2}`, every row an empty `GenericRow`. Mutation: an empty list read as absent. +- `"table: a keyed reply carries the view's totals and each row's view row"`: + +```cpp +// Mutation: indices filled with positions in the reply instead of view rows. +TEST_CASE("table: a keyed reply carries the view's totals and each row's view row", "[table][query][keyed]") { + using morph::table::Unloaded; + auto source = tabletest::makeSource({tabletest::levelCol("a", ColumnKind::Integer, "slow")}, + {{Cell{std::int64_t{40}}}, {Cell{std::int64_t{10}}}, {Cell{Unloaded{}}}, + {Cell{std::int64_t{30}}}, {Cell{std::int64_t{-1}}}, {Cell{std::int64_t{20}}}}); + TableQuery query{.sort = {SortKey{.column = "a"}}, + .filters = FilterSpec{.columns = {{"a", ColumnFilter{.include = {{.gt = "0"}}}}}}}; + query.keys = std::vector{RowId{std::int64_t{3}}, RowId{std::int64_t{1}}, RowId{std::int64_t{2}}, + RowId{std::int64_t{4}}, RowId{std::int64_t{99}}}; + auto page = apply(*source, query); + REQUIRE(page.has_value()); + CHECK(page->rows == std::vector{1, 3}); // view order; 2 undecided, 4 rejected, 99 absent + CHECK(page->indices == std::vector{0, 2}); + CHECK(page->total == 4); + CHECK(page->undecided == 1); + CHECK(page->totalKind == TotalKind::AtLeast); +} +``` + +- `"generic page: unloaded rows, undecided and indices round-trip"` (`test_table_description.cpp`): a `GenericPage` with `unloadedRows {{1, {"recipe"}, {"recipe"}}}`, `undecided 40`, `awaiting {"stock"}`, `failed {"recipe"}`, `indices {5, 9}` writes and reads back with each of the five members equal (`GenericPage` has no `operator==`; `unloadedRows` compares by `UnloadedRow`'s, A6); JSON lacking all five reads as a fully loaded page (members empty, `undecided == 0`). Mutation: the reader requiring `unloadedRows`. +- `"generic page: an unloaded cell is null and named per level"`: `writeGenericPage` over a 2-row source whose row 1 has `Unloaded` in recipe column `r` and named `columns {"id","r"}` writes `rows[1][1]` as `null` and `unloadedRows == {{1, {"recipe"}, {}}}`; a level whose columns are not named is not listed. Mutation: the writer emitting a sentinel string for `Unloaded`. + +- [ ] **Step 2: Run to verify failure** — `cmake --build --preset cl-debug --target morph_table_tests`: compile errors naming `keys`, `indices`, `maxKeys`. + +- [ ] **Step 3: Implement `validate`'s keyed rules** in `query.hpp` + +(`columns` is validated by Task 1.) `keys`: `page.offset != 0` → `InvalidSpec` ("a keyed query has no page"); more than `maxKeys` → `LimitExceeded`; a text key longer than `maxTextLength` → `LimitExceeded`. (Task 8a adds "keys with `distinct`" → `InvalidSpec`.) + +- [ ] **Step 4: Split `apply` and answer keyed queries** + +`apply` = `validate` → `computeView` → `pageRows`. `pageRows` fills `total` (absent above `totalCap`), `totalKind`, `undecided`; for a non-keyed query `offset` and the page's rows as before; for a keyed one, `rows` = the source rows whose key is in `keys` and whose view row exists, ascending by view row, `indices` = those view rows, `offset = 0`. Keys are matched through `sourceRowOf` when it is given (one lookup a key); otherwise by scanning the snapshot's `rowId`s once against an `std::unordered_set` of the requested keys, which is what `apply` does. The typed `apply` copies `indices`. + +Add to Step 1 `"table: a keyed page uses the lookup it is given"` (`test_table_query.cpp`): `detail::pageRows` over the view of the case above, with a `sourceRowOf` built from an `std::unordered_map` and a snapshot wrapper that counts `rowId` calls, returns the same `rows` and `indices` as without it and makes no `rowId` call. Mutation: `pageRows` ignoring `sourceRowOf`. + +- [ ] **Step 5: Implement the generic page members and the keys capability** + +`detail::answerQuery` refuses a query with `keys` set as `TableError{Unavailable, {}, "this table answers no keyed query"}` when `served.description.capabilities.keys` is false. + +`writeGenericPage` copies `totalKind`, `undecided`, `awaiting`, `failed`, `indices` from `PageRows`, and lists row `i` in `unloadedRows` with the sorted levels of the named columns whose cell it wrote as `Unloaded` (Task 5's answer path replaces this with the level snapshots' states). The reader accepts every new member as optional. + +- [ ] **Step 6: Run the target** — `ctest --test-dir build/cl-debug -R "^(table|generic page|description)" --output-on-failure`: all pass. + +- [ ] **Step 7: Benchmarks** in `bench_table.cpp` (`"[.benchmark][table][wire]"`): W3 — bytes of the W1 page (200 rows, 40 named columns from the 1,000 × 300 fixture W1 is recorded on; positions 100 to 139 hold the recipe decimals `d000` to `d009`) with all 200 rows naming one unloaded level, minus the same page with `unloadedRows` cleared, as a share of W1; W4 — a keyed reply of 20 keys and 40 columns: bytes, encode, decode. Record into table.md's "Benchmarks: wire". + +- [ ] **Step 8: Mutations, then commit** + +```bash +git add include/morph/table tests/table +git commit -m "feat(table): partial pages and keyed queries" +``` + +--- + +### Task 5: The level cache (table.md step 2c, first half) + +**Spec:** "The server level cache" (all thirteen rules and the layout, size and use paragraphs), "A table on the server" (level caches by record); Tests rows "A value is loaded once" (cache half), "Concurrent queries share a load", "Reloaded once after invalidation" (cache half), "A load in flight at invalidation", "Visible before told", "Eviction", "A level's layout is the cache's" (cache half), "A cache's size is deep", "A reader blocks no one", "Order uses are leased", "A failed load" (cache half); invariants 11, 12, 13, 14 (layout clause); gates L1–L8. + +**Files:** +- Create: `include/morph/table/level_cache.hpp`; `tests/table/test_table_level_cache.cpp` (in `morph_table_tests`) +- Modify: `include/morph/core/change_types.hpp` (`effects::AnnounceSink`, `effects::IChangeObserver`: the cache derives from it, so it lands here rather than in Task 6) +- Modify: `include/morph/table/description.hpp` (`detail::answerQuery`, A1: level snapshots, `LeveledSource`, `want`, `unloadedRows`/`awaiting`/`failed` from snapshots) +- Modify: `tests/table/wide_table_model.{hpp,cpp}` (the slow level `recipe`), `tests/table/bench_table.cpp` (L1–L3, L6) + +**Interfaces:** +- Consumes: Task 3's `Unloaded`, `levelsNeeded`; Task 4's `computeView`, `pageRows`, `GenericPage` members; Task 2's `ServedTable::levels` (`std::vector>`). +- Produces (in `morph::table`, `level_cache.hpp`): the spec's block verbatim — `LevelRead`, `LevelUse`, `LevelSnapshot`, `LevelSource`, `LevelCacheOptions`, `LevelCacheStats`, `LevelCache` with `Loader`, `SizeOf`, `Cells`, both constructors, `invalidate`, `invalidateAll`, `onLoadFailed`, `stats`, and `using CellLevelCache = LevelCache>;` — plus: + - `[[nodiscard]] std::size_t cellBytes(Cell const& cell) noexcept;` (in `data_source.hpp`: `sizeof(Cell)` plus a string's heap capacity when it is not in the small buffer) + - `struct LevelInput { std::shared_ptr source; std::shared_ptr snapshot; };` + - `class LeveledSource final : public DataSource` — `LeveledSource(std::shared_ptr base, std::vector columns, std::vector levels);` `columns()` the given columns; `snapshot()` reads a base-level column from `base` by id and a level column from its level's snapshot at the column's place in `LevelSource::columns()` (by id), `Unloaded` unless `read` answers `Loaded`; `subscribe`/`unsubscribe` do nothing (it is one request's immutable view); `[[nodiscard]] LevelRead state(std::size_t row, std::string_view level) const;` +- Produces (in `morph::effects`, `change_types.hpp`): + - `using AnnounceSink = std::function> keys)>;` + - `class IChangeObserver { public: virtual ~IChangeObserver() = default; virtual void changed(Changes const& changes) = 0; virtual void bind(AnnounceSink sink) = 0; };` (special members as the file's other interfaces declare them) +- Fixture: `WideTableOptions::recipePreloaded` (`double`, default `1.0`), `WideTableOptions::recipeBatch` (`std::size_t`, default `64`), `WideTableOptions::recipeFails` (`bool`, default `false`: the loader returns no value for any key, so every key it is given fails), `bench::WideTableModel::recipeGate()` returning a `bench::LoadGate&` with `hold()`, `release()` (every call from now on passes) and `release(std::size_t calls)` (that many loader calls pass, then it holds again), `loaderCalls() -> std::vector>`, and `recipeCache() -> std::shared_ptr` (what a test `attach`es and reads `stats()` from). The fixture has no record besides its tables', so the cache's `invalidatedBy` is its `records`; a change of another record in `invalidatedBy` is tested on the cache alone (Step 1, "the observer invalidates by record"). The recipe level's columns are `d000`…`d009` and `t001`…`t010` (A3); the cache's `columns` list them in that order. + +- [ ] **Step 1: Write the failing cache tests** in `tests/table/test_table_level_cache.cpp` + +Shared helpers in the file's anonymous namespace, gathered in `struct Rig`: `tabletest::ManualExecutor loads;` (`ManualExecutor::runAll` runs only what was queued when it was called, and a batch's completion posts the next, so a test that means "until every load has run" calls `rig.drain()`, which is `tabletest::drain(loads)`); `rig.loggedKeys()` (every key the loader was given, sorted); a `CellLevelCache` over options `{.records = {"T.rows"}, .level = "recipe", .columns = {levelCol("r", Text, "recipe")}, .loads = &loads, .clock = [&] { return now; }}` and a loader that logs its keys and returns `{key, {Cell{"v" + text(key)}}}` per key; `keys(n)` gives `RowId{0}`…`RowId{n-1}`; `readCell(snapshot, key)`; an `AnnounceSink` that records `(record, keys)` and, when `readOnAnnounce` is set, reads the cache's snapshot for each key at call time. + +```cpp +// Mutation: want not checking the cache (loads held keys again): loadedKeys 400. +TEST_CASE("level cache: a value is loaded once", "[table][levels]") { + Rig rig; + REQUIRE(rig.cache.want(keys(200), LevelUse::Display)); + rig.drain(); // all four batches + REQUIRE(rig.cache.want(keys(200), LevelUse::Display)); + rig.drain(); + CHECK(rig.cache.stats().loadedKeys == 200); + CHECK(rig.loggedKeys() == keys(200)); // each once, in any order: compared sorted + CHECK(readCell(*rig.cache.snapshot(), RowId{std::int64_t{5}}) == Cell{std::string{"v5"}}); +} +``` + +Add, each with the spec's mutation: +- `"level cache: a key wanted while it is queued is loaded once"`: `want(keys(200), Display)`, then `rig.loads.runAll()` once (one batch of 64 stored, the next posted), then `want(keys(200), Display)` again, then `rig.drain()`: `loadedKeys == 200` and `loggedKeys() == keys(200)`. Mutation: `want` queueing a key that is already queued (272 keys loaded). +- `"level cache: concurrent wants share one load"`: this case's `loads` is a one-thread pool, not the manual executor, so the loader can block on a latch off the test thread; 8 `std::thread`s call `want(keys(60), Display)`; after the latch is released and the pool is idle, `loaderCalls == 1`. Mutation: no in-flight set. +- `"level cache: invalidated keys are absent and load once more"`: 200 loaded; `invalidate(keys 0..9)`: those read `Unloaded`, the rest `Loaded`; two `want(keys(200))` load exactly keys 0–9, once; `invalidatedKeys == 10`. Mutation: `invalidate` leaving the values. +- `"level cache: the observer invalidates by record"`: `changed(Changes{.records = {{"T.rows", keys {"3"}}}})` makes key 3 absent and announces nothing; `{{"T.rows", nullopt}}` empties the level; `{{"Recipe", nullopt}}` with `invalidatedBy {"T.rows","Recipe"}` empties it and announces `("T.rows", nullopt)`; a record in neither list changes nothing. Mutation: `changed` ignoring the record. +- `"level cache: a load in flight at invalidation does not land"`: hold the loader on key 1; `invalidate({1})`; release returning the old value: key 1 reads `Unloaded`, `droppedLoads == 1`; the next `want({1})` calls the loader. Mutation: storing without the generation check. +- `"level cache: a want after an invalidation does not wait for the stale load"` (Review Focus 1): hold the loader on key 1; `invalidate({1})`; `want({1})` again before releasing: after release and drain the loader was called twice for key 1, the second call's value is stored, `droppedLoads == 1`. Mutation: "in flight" ignoring the generation, which leaves key 1 unloaded after the stale load is dropped. +- `"level cache: values are stored before they are announced"`: `readOnAnnounce`: every announced key reads `Loaded` at announce time; after `invalidateAll()` through `changed` with another record, the announce sink reads every key `Unloaded`. Mutation: announcing before storing. +- `"level cache: eviction drops the least recently used"`: `maxBytes` fitting 100 values; load 100, read keys 50–99 by `want`, load 50 more: keys 0–49 read `Unloaded`, 50–149 `Loaded`, `evictedKeys == 50`, the announce sink got only the loads' keys (no event for an eviction); `want(keys 0..9)` loads them again. Mutation: evicting the most recently used. +- `"level cache: a value's layout is the cache's"`: cache columns `{r1, r2, r3}`; `LeveledSource` A with description columns `{id, r3, r1}`, B with `{id, r2}`: A's row 0 reads `r3`'s value under `r3` and `r1`'s under `r1`; B reads `r2` under `r2`; one loader call served both. Mutation: reading the value by the caller's column order. +- `"level cache: size is deep"`: values of twenty text cells of 40 characters; `maxBytes = 100 * `; after loading 150 rows, `stats().bytes <= maxBytes` and `evictedKeys == 50`. Mutation: `SizeOf` as `sizeof(Value)`. +- `"level cache: a held snapshot blocks no store"`: hold `snapshot()`; on another thread `want` + drain, `invalidate`, `changed(...)` each complete within 1 s (`std::future::wait_for`); the held snapshot still reads its old values and its `generation()` differs from a new snapshot's. Mutation: a snapshot holding a shared lock. +- `"level cache: order uses are leased and the second is refused"`: `maxBytes` fitting 150 values, `expectedBytes` = one value's size; `want(keys 0..99, Order)` loads 100; `want(keys 100..199, Order)` returns `TableErrorCode::Unavailable`, `refusedOrders == 1`, loader calls unchanged; a `Display` load of 100 other keys evicts none of 0–99; advance the clock past `orderLease`: a further `Display` load evicts from 0–99. Mutation: no lease (the loader's call count grows without end over ten alternating rounds: assert `loaderCalls` after ten rounds equals that after one). +- `"level cache: leased values outgrowing the bound stop the order load"`: `expectedBytes` one tenth of the true size; `want(keys(100), Order)` is accepted; while loading, leased bytes exceed `maxBytes`: the remaining order batches are not loaded, the lease is dropped, `("T.rows", nullopt)` is announced, and the next `want(keys(100), Order)` is `Unavailable`. Mutation: the over-bound check skipped. +- `"level cache: a failed load is remembered"`: the loader returns no value for keys 0–9 of 20: those read `Failed`; `failedLoads == 10`; `onLoadFailed` got keys 0–9 once; the sink announced keys 0–9 once; `want(keys 0..9)` loads nothing until `retryAfter` (30 s) on the clock, then once; a second failure waits 60 s; `want(…, Display, true)` loads at once; `invalidate({3})` clears key 3's failure. A key the loader returns with an empty value reads `Loaded` with empty cells. Mutation: a failed key wanted again by every request. A loader that throws fails every key of the call. +- `"level cache: a level no cache serves is unloaded and awaited"` (in `tests/table/test_table_description.cpp`; spec failure mode "A filter on a level no cache serves"): a `ServedTable` whose description has column `r` at level `"recipe"` and whose `levels` holds one recording `LevelSource`, for the level `"stock"` and nothing for `"recipe"`, filtered `r contains "a"`: `answerQuery` returns no rows, `undecided` = every row, `awaiting == {"recipe"}`, and the recording source saw no `want`. Mutation: a level without a source read from the base source. +- `"table: change keys round-trip awkward keys"` (in `tests/table/test_table_query.cpp`; Review Focus 3): `changeKeys` then `rowIdOf` gives back `RowId{std::string{"a\"b\\c é"}}` and `RowId{std::int64_t{9'007'199'254'740'993}}` exactly; `rowIdOf` of `true`, `1.5` and `{}` is `nullopt`; `changeKeys` of `RowId{7}` and `RowId{"x"}` writes `7` and `"x"`. Mutation: writing an integer key through `double`. + +- [ ] **Step 2: Run to verify failure** — `cmake --build --preset cl-debug --target morph_table_tests`: `level_cache.hpp` not found. + +- [ ] **Step 3: Implement `level_cache.hpp`** (the classes as the Interfaces block; the spec's Doxygen on each member) + +The decisions the rules and tests leave open: + +- **Storage.** 256 shards by `std::hash`; each `std::shared_ptr`, a `Shard` being an immutable `std::unordered_map>`. A `Slot` holds the `Value` (or the failure: count and time), its deep bytes, and `mutable std::atomic lastUse` (a cache-wide use counter) and `mutable std::atomic leaseUntil` (clock ticks; 0 none). `snapshot()` copies the 256 pointers and a generation under the mutex; the mutex is held only to copy pointers or swap in changed shards. Every store, removal and observer call copies only the shards it touches and bumps the generation. +- **Generations.** A key's generation lives in `std::unordered_map` beside the shards (under the same mutex); `invalidate` bumps each key's, `invalidateAll` bumps a level epoch. A load records `(epoch, key generation)` per key when it starts; the store keeps a key only when both are unchanged; others are dropped and counted in `droppedLoads`. A key is "in flight" only while a load holding its current generation runs, so a `want` after an invalidation starts a new load. +- **Queue and batches.** Two LIFO stacks of wanted keys, `Display` and `Order`: each `want` pushes its keys as one block, in the order given, on top of its stack, and a batch takes keys from the top block in that order (the newest want first, each want in its own order). One loader call runs at a time per cache: when none runs, the next batch (up to `batch` keys, `Display` stack first) is posted to `loads`; its completion stores, announces, and posts the next. Keys held, in flight, already queued, or failed inside their delay are not queued again: a queued key wanted again moves to the top block of its stack (an `Order` key wanted for `Display` moves to the `Display` stack), so a key is in at most one block and is handed to the loader once. +- **Order fit.** `want(keys, Order)` computes `keys.size() × mean` (mean = stored bytes / stored values; `expectedBytes` while none; 64 × columns when that is 0) plus the bytes of slots leased by other keys; over `maxBytes` it returns `Unavailable` and changes nothing. Otherwise every key's lease becomes `now + orderLease` (a key still loading receives it when stored). +- **Eviction.** After a store, while `bytes > maxBytes`, evict the slots with the smallest `lastUse` whose lease is past; a `Display` value stored with nothing evictable is stored with `lastUse = 0` so it goes first. While leased bytes exceed `maxBytes`, clear the `Order` stack, set every lease to 0, and announce each of `records` without keys. +- **Failure delay.** `retryAfter × 2^(failures − 1)`, capped at `retryMax`, read from `clock` when `want` sees the key. +- **Announce.** After a store, the stored keys (written with `changeKeys` — this task adds `[[nodiscard]] std::vector changeKeys(std::span keys);` and `[[nodiscard]] std::optional rowIdOf(glz::raw_json const& key);` to `query.hpp`: an integer key is a JSON number, a text key a JSON string, anything else `nullopt`) go to the sink once per record of `records`; failed keys likewise, once. +- **Observer.** `changed` runs on the server strand and only removes: for each change whose record is in `invalidatedBy` — a record of `records` with keys invalidates those keys (unreadable keys invalidate the level), without keys the level; any other record invalidates the level and announces each of `records` without keys. +- `stats()` reads atomics; `bytes` is the deep total. + +- [ ] **Step 4: Implement `detail::answerQuery` with levels** (A1) in `description.hpp` + +For a validated query: `levelsNeeded`; one snapshot per needed level (`ServedTable::levels` by `level()`); a `LeveledSource` over Task 2's `detail::PinnedSource` (the one source snapshot the reply reads), the description's columns and those snapshots; `computeView` and `pageRows` over it; the writer over the reply's rows and named columns; `unloadedRows[i].levels` = the needed levels whose `state(row, level)` is not `Loaded`, `failed` = those `Failed`; `PageRows::awaiting` = the `order` levels with an `Unloaded` state for some row of the view or the undecided set, `failed` = those with a `Failed` one. Then `want`, every call with `retry = query.retry` (decision 25): each `display` level with the reply's keys (`Display`), each `order` level with the keys of the view and the undecided rows (`Order`); a needed level no entry of `served.levels` serves reads `Unloaded` for every row, counts as `awaiting` when it is an `order` level, and is wanted from no one; an `Unavailable` from an `Order` want refuses the query with `TableError{Unavailable, , …}` — the want happens before the reply is returned, so a refused order use returns no page. + +- [ ] **Step 5: Add the fixture's slow level** in `wide_table_model.{hpp,cpp}`: one `CellLevelCache` shared by `wide` and `small` (`records` both; `columns` = `d000`…`d009`, `t001`…`t010` from `wideColumns(300)`; `batch` = `WideTableOptions::recipeBatch`), loader over the generator's recipe cells, sleeping `loadDelay` per key or waiting on `recipeGate()`, and returning no value at all when `recipeFails`; `recipePreloaded` of the rows stored when the cache is built (rows chosen by `(seed, row)`, so the same seed preloads the same rows); `invalidatedBy` left at its default, `records`. Each of the three table functions (`scoped` included, whose record is not in `records`: its arrivals are not announced, and no test watches it) returns `ServedTable::levels = {the cache}`; the columns' `info.level` and the descriptions' `levels = {"recipe"}` are Task 3a's (A3). `configure` rebuilds the cache with the sources. The default `recipePreloaded = 1.0` keeps every Part A page test (which reads recipe values) unchanged; the level tests and benchmarks set `0` or `0.7` explicitly. + +- [ ] **Step 6: Run the target** — `ctest --test-dir build/cl-debug -R "^(level cache|table|generic page)" --output-on-failure`: all pass. + +- [ ] **Step 7: Benchmarks** (`"[.benchmark][levels]"`, loader sleeping a fixed time per key): L1 (snapshot + 200 reads; 100,000 reads), L2 (bytes per row at twenty columns, and for 100,000 rows), L3 (`invalidate` of 1,000 keys; the observer call for a 4,096-key change; both while another thread holds a snapshot 40 ms — gate case `"level cache: invalidation does not wait for a reader"` asserts each returns before the reader releases), L6 (loader return to announce per batch of 64 at 100,000 held rows; gate case asserts shards copied ≤ keys stored, through a test-only counter `LevelCacheStats` does not expose — read it with a `detail::` accessor). L4, L5, L7, L8 are the gate cases of Step 1 ("concurrent wants", "a value is loaded once", "order uses", "a failed load"); L8's ten page requests inside `retryAfter` are asserted in Task 6's bridge case. Record into table.md's "Benchmarks: server level cache". + +- [ ] **Step 8: Mutations, then commit** + +```bash +git add include/morph/table include/morph/core/change_types.hpp tests/table tests/CMakeLists.txt +git commit -m "feat(table): the level cache" +``` + +--- + +### Task 6: Announce, attach and the view cache (table.md step 2c, second half) + +**Spec:** "Arrival" steps 1–3, "The view cache", "A model's tables" (row scope), "The server level cache" (how the server learns of a cache); Tests rows "`announce`", "A cached view is the view", "One sort for many watchers", "No value crosses a scope", "A row-scoped table", "A value is loaded once" (two clients), "Reloaded once after invalidation" (through the server), "A level's layout is the cache's" (bridge), "A failed load" (bridge), (a) bridge, (c) bridge; invariants 13, 14, 29; gates S7, S9, C1–C3. + +**Files:** +- Create: `include/morph/table/view_cache.hpp`; `tests/table/test_table_view_cache.cpp` (in `morph_table_tests`); `tests/net/test_push_unloaded_rows.cpp` (in `morph_net_tests`, which links `morph_wide_table_model`) +- Modify: `include/morph/core/remote.hpp` (`RemoteServer::announce`, `attach`, `viewStats`, the observer call in `fanOut`, `ServerConfig::views`, the server's `ViewCache` installed in its `TableRuntime`). It still includes no table header but `table/runtime.hpp` (Part A's rule) +- Modify: `include/morph/table/runtime.hpp` (`ViewCacheOptions`, `ViewCacheStats`, the forward declaration `class ViewCache;`, `TableRuntime::views`, `makeViewCache`, `viewCacheStats`), `src/ui/process_state.cpp` (the two functions' definitions, beside `currentTableRuntime()`; it includes `view_cache.hpp`) +- Modify: `include/morph/table/data_source.hpp` (`RowSnapshot::identity()`), `include/morph/table/query.hpp` (`RowsSnapshot::identity()`) +- Modify: `include/morph/table/description.hpp` (`AnswerContext::{views, record, rowScoped}`; `detail::answerQuery` through the view cache; `rowScoped` with an empty `scope`; `QueryTable::invoke` filling all three) +- Test: `tests/net/test_push_tables.cpp` +- Docs: `docs/spec/core/backend.md` "Fan-out" (`tableWork`, `announce`, `attach`, `IChangeObserver`, the view cache) + +**Interfaces:** +- Consumes: Task 5's `LevelCache`, `LeveledSource`, `IChangeObserver`, `AnnounceSink`, `changeKeys`, `rowIdOf`; Task 4's `computeView`, `pageRows`; A1–A4. +- Produces: + - `std::expected RemoteServer::announce(std::string_view record, std::optional> keys);` + - `void RemoteServer::attach(std::shared_ptr observer);` + - `ServerConfig::views` (`table::ViewCacheOptions`) + - `[[nodiscard]] table::ViewCacheStats RemoteServer::viewStats() const;` (the server's one view cache; callable from any thread) + - In `table/runtime.hpp`, which stays free of the other table headers (it adds ``, ``, ``): `struct ViewCacheOptions { std::size_t maxBytes = 64U << 20U; std::function onCompute; };` (`onCompute`: called on the computing thread at the start of each computation; empty by default; a test records `std::this_thread::get_id()` in it), `struct ViewCacheStats { std::size_t hits, misses, computations, waits, evictions, invalidations, bytes; };`, `class ViewCache;`, `[[nodiscard]] MORPH_API std::shared_ptr makeViewCache(ViewCacheOptions options);` and `[[nodiscard]] MORPH_API ViewCacheStats viewCacheStats(ViewCache const& cache);`. `RemoteServer` holds the `std::shared_ptr` it got from `makeViewCache(config.views)` and never needs the complete type; `view_cache.hpp` includes `runtime.hpp` and defines the class + - `[[nodiscard]] virtual void const* RowSnapshot::identity() const { return this; }` — two snapshots with one identity hold the same rows. `RowsSnapshot` without a `LevelLoaded` returns its rows vector's address, so the `RowsSource` that `detail::serve` builds on every call of a typed table has one identity while the model returns the same `std::shared_ptr const>`; with a predicate it returns `this`. A snapshot that wraps another (the scoped source's, `LeveledSource`'s) does not forward it + - `struct ViewKey { std::string record; std::string scope; std::string query; };` (`query`: the canonical JSON of the validated `sort` and `filters` only) + - `struct ViewComputation { detail::ComputedView view; std::vector awaiting; std::vector failed; };` (what `compute` returns; the cache builds the entry from it) + - `struct ViewEntry { std::shared_ptr snapshot; std::vector> levels; detail::ComputedView view; std::vector awaiting; std::vector failed; [[nodiscard]] std::span viewRowOf() const; [[nodiscard]] std::optional sourceRowOf(RowId const& key) const; [[nodiscard]] std::size_t bytes() const; };` (`viewRowOf` and the key index are built once, at the first keyed query, under a `std::once_flag`; held only by `std::shared_ptr`, never copied or moved) + - `class ViewCache { public: explicit ViewCache(ViewCacheOptions options = {}); [[nodiscard]] std::expected, TableError> find(ViewKey const& key, std::shared_ptr const& snapshot, std::span const> levels, std::function()> const& compute); [[nodiscard]] ViewCacheStats stats() const; };` + - `struct AnswerContext { ViewCache* views = nullptr; std::string_view record; bool rowScoped = false; };` (decision 48: `record` is the table's record name, `.`, the first member of the `ViewKey`; `rowScoped` is the registration's option. `QueryTable::invoke` fills them from `TableTraits` and the record's `RecordInfo::privateKeys`; a caller that passes neither, as the direct tests of Tasks 2–5 do, gets `record` empty and no row-scope check) and `TableRuntime::views` (`ViewCache*`; null computes every time) + +- [ ] **Step 1: Write the failing view cache tests** in `tests/table/test_table_view_cache.cpp` + +- `"view cache: a cached view is the view"` (invariant 29): for seeds 0–199, `std::mt19937{seed}` builds a 300-row table of 4 columns (`Integer`, `Text` base; `Decimal`, `Text` at level `"recipe"` read through a `CellLevelCache` holding 70% of rows), a sort of 1–2 random keys and a random filter of 1–2 entries; through one `ViewCache` entry the test builds page 0, a keyed reply of 10 random keys and page 1, and `CHECK`s each `PageRows` equal (`rows`, `total`, `totalKind`, `undecided`, `indices`, `offset`) to `apply`'s over the same `LeveledSource`. Its second half stores into the sorted level and builds page 0 again, which must equal `apply`'s over the new snapshot. Mutation: an entry valid whatever its order levels' generations, which serves the old order. + +Add: +- `"view cache: an arrival on an order level computes again; on a display level it does not"`: one entry sorted on recipe column `r1`; a store into the level (generation changes) → the next `find` recomputes (`computations == 2`); with the sort on a base column and only display level `r2` changing → `computations == 1`, `hits == 1`. Mutation: as the case above. +- `"view cache: a request on a newer snapshot does not join an older computation"`: request A `find`s key K with snapshot S1 and its `compute` blocks on a latch; request B `find`s K with snapshot S2 (one `updateRow` later): B computes on its own (`computations == 2`, `waits == 0`) and its entry's `view` is the one over S2; after A is released, a third `find` with S2 hits B's entry. The same holds for a different order-level generation with the same snapshot. Mutation: single flight joined on the key alone, which hands B the view over S1. +- `"view cache: fifty requests compute once"` (S7/C1 shape): 50 threads `find` the same key while `compute` waits on a latch: `computations == 1`, `waits == 49`, every result the same entry. Mutation: no single flight. +- `"view cache: the bound evicts least recently used"`: `maxBytes` fitting two entries of 10,000 rows; three keys → the first evicted, `bytes <= maxBytes`. Mutation: no bound. +- `"view cache: a keyed fetch sorts nothing"` (S9 gate): after page 0, a keyed query of 20 keys: `computations` unchanged. Mutation: a keyed query bypassing the cache. +- `"view cache: a typed table's view is cached across calls"` (`test_table_description.cpp`): a typed table whose function returns the same rows pointer each call; two `detail::answerQuery` calls, each over a fresh `detail::serve<&TypedModel::rows>(model, ctx)` (pinned), with one `ViewCache` and `record = "TypedModel.rows"` in the context: `computations == 1`, `hits == 1`; after the model replaces its rows vector, a third call computes again (`computations == 2`). Mutation: `find` comparing snapshot pointers instead of `identity()` (three computations). +- `"view cache: a row-scoped table needs a scope"` (`test_table_description.cpp`): `answerQuery` with `AnswerContext{.rowScoped = true}` over a `ServedTable` whose `scope` is empty answers `SourceContract`; with `scope = "p1"` it answers a page; with `rowScoped = false` and an empty scope it answers a page. Mutation: the check reading `served.scope` alone (the third case is refused). + +- [ ] **Step 2: Write the failing bridge tests** in `tests/net/test_push_unloaded_rows.cpp` + +The file's rig (anonymous namespace), built as `tests/net/test_push_two_clients.cpp` builds its server, socket and client sessions: a `RemoteServer` over a 4-thread pool with `ServerConfig{.tableWork = }` serving `bench::WideTableModel` (`small`: 1,000 × 30, `recipePreloaded = 0`, recipe gate held), the model's level cache `attach`ed; one or more clients, each a `ui::Session` with a watcher and a `CountingChannel` (a `ui::ModelChannel` decorator logging `(actionId, bodyJson)` of every `execute`). Records are `"WideTableModel.small"` and `"WideTableModel.wide"` (A3). The row-scope cases use a test model `UrModel` in the same file: table `rows`, registered `table::rowScoped`, whose function returns `table::scoped(, )` with `scope` = the principal, principal `p1` seeing rows 0–499 and `p2` rows 250–749, and one `CellLevelCache` for `r` shared by both scopes; a second registration `UrEmptyScope` is the same with `scope` left empty. + +```cpp +// Mutation: announce bypassing the derived-record walk. +TEST_CASE("announce: a derived record is included, many keys are whole, an unregistered record is refused", + "[net][push][levels]") { + // A record D registered derivedFrom the table record; a client watching D. + // announce(small, 3 keys) → the client's event names `small` with the 3 keys and D whole-type. + // announce(small, 4,097 keys) → `small` whole-type. + // announce("NoSuchRecord", {}) → unexpected, and no event reaches any client within 200 ms. +} +``` + +Add: +- `"table over the bridge: the first page arrives before the level"` (row (a) bridge): with the gate held forever, `Table.small` sorted on `id`, `columns` = `id`, `d000` and `t001`: the reply arrives; `unloadedRows` names indices 0–199 (keys 1–200) with `{"recipe"}`; every recipe cell is `null`. Mutation: the answer path waiting for its loader. +- `"table over the bridge: a level loads only for what a query needs"` (row (c) bridge): a query naming no recipe column → `loaderCalls()` empty; naming one → the logged keys are exactly the page's 200; sorting on one → every candidate row (1,000). Mutation: `levelsNeeded` returning every level. +- `"table over the bridge: two clients load a value once"`: two clients ask the same page naming a recipe column; release the gate; `loadedKeys == 200` and each key once in the log. Mutation: `want` not checking the cache (800). +- `"table over the bridge: an updates effect invalidates without a call"`: after the level loaded, `EditWideRow` on the row keyed 5 (declares `updatesTable` on `wide` and `small`): the next query names that row unloaded and wants it; the loader loads key 5 once. Mutation: `fanOut` not handing the change to observers. +- `"table over the bridge: no value crosses a scope"`: `UrModel`'s `rows` for `p1` and `p2`, each naming `r`: each reply holds only its scope's rows; after release the loader was called once for each of rows 250–499. Mutation: a view shared across scopes (an empty `scope` in the key). +- `"table over the bridge: a row-scoped table announces without keys"`: an arrival for `UrModel.rows` reaches `p1`'s watch with `keys` absent; no event `p1` receives names a key outside 0–499; `UrEmptyScope`'s first query answers `SourceContract`. Mutation: the record registered without `privateKeys`. +- `"table over the bridge: a level's layout is the cache's"` (`test_push_tables.cpp`): `WideTableModel.scoped` for `"extended"` (recipe columns `d000`…`d005`, `t001`…`t006`) and for a default principal such as `"alice"` (`t001`…`t006` only), each naming every recipe column it has, with `recipePreloaded = 0` and the gate released. The first reply of each has its recipe cells `null` (a reply never waits for a load) and wants the page's keys; the test waits until `recipeCache()->stats().loadedKeys` reaches the page's 200 (polling the counter with a deadline, since `scoped`'s record is not announced), then asks each page again: the second replies' recipe cells equal the generator's values under their own column ids, and each key is in `loaderCalls()` once for both principals. Mutation: reading the value by the caller's column order (alice's `t001` then holds `d000`'s value). +- `"table over the bridge: failed keys are not loaded again inside the delay"` (L8): `small` configured with `recipePreloaded = 0` and `recipeFails = true`, sorted on `d000` (so `recipe` is an order level; `Page::failed` names order levels only, spec "Partial pages"): once the 1,000 order keys have failed, ten page requests cause zero further loader calls, and each reply has `awaiting` empty, `failed == {"recipe"}`, and every `unloadedRows[i].failed == {"recipe"}`; the failed keys were announced once; then one request with `retry: true` calls the loader for each of the 1,000 keys once, in `ceil(1000 / 64) = 16` calls. Mutation: a failed key wanted again by every request. +- `"table over the bridge: one sort for many watchers"` (C1, C2, gate parts, `test_push_tables.cpp`): fifty clients watching one sorted view of `wide` refetch after one announcement: `server->viewStats().computations` rises by one; each computation ran on a `tableWork` thread: the rig's `ServerConfig::views.onCompute` records `std::this_thread::get_id()` under a mutex, and every recorded id is one of the `tableWork` pool's (which the rig collects by posting a task to each of its threads). Mutations: no single flight (fifty computations); `QueryTable::invoke` running `answerQuery` inline (the recorded id is a strand thread's). +- C3 gate case `"table over the bridge: fifty sorts stay inside the bound"`: fifty clients with fifty different sorts: `server->viewStats().bytes <= maxBytes` and `evictions > 0` with `ServerConfig::views.maxBytes` set to fit ten views of `wide`. Mutation: no bound. + +- [ ] **Step 3: Run to verify failure** — `cmake --build --preset cl-debug --target morph_table_tests` and, on Linux, `cmake --build --preset linux-everything --target morph_net_tests`: `view_cache.hpp` not found; `announce`, `attach` not members. + +- [ ] **Step 4: Implement `view_cache.hpp`** + +Wherever this step says two snapshots are the same, it means their `identity()` is equal; an entry holds its snapshot, so the address an identity names cannot be reused while the entry lives. `options.onCompute`, when set, is called first on the thread that computes. + +`find`: under a mutex, look the key up; an entry whose `snapshot` is the same as the argument and whose every `levels` generation equals the arguments is a hit (its recency bumped); a stale entry is dropped (`invalidations`). On a miss, a request joins a running computation only when that computation's key, snapshot and every level generation equal its own, and then waits on its `std::shared_future` (`waits`); otherwise it computes inline, outside the mutex, and publishes through its own `std::shared_future` (running computations are kept per `(key, snapshot, generations)`). The cache builds the `ViewEntry` from the `ViewComputation`, the snapshot and the generations, in a `std::shared_ptr`; when two computations of one key finish, the entry whose snapshot and generations a later request matches is the one it finds (an insert replaces the key's entry unless that entry's computation started later, so the computation over the older snapshot, finishing last, does not displace the newer entry). A failed computation is not cached. Over `maxBytes` after an insert, least recently used entries go. `ViewEntry::bytes()` is `4 × (view + undecided)` plus, once built, `4 × source rows` for `viewRowOf` and 12 bytes a row for the key index (a vector of `(hash, source row)` sorted by hash). The cache reads `bytes()` again on every hit, so an entry that built its lookups since it was inserted is counted at its new size and the bound is applied then. + +- [ ] **Step 5: Implement `detail::answerQuery` through the cache** (A1) + +The `ViewKey` is `{context.record, served.scope, canonical JSON of validated sort and filters}`; with `context.views` null or `context.record` empty the view is computed for the request and not cached. The snapshot passed is the pinned source's (the base rows, whose identity survives across requests), not the `LeveledSource`'s; the levels passed are the `order` levels with their snapshots' `generation()`. `compute` runs `computeView` over the `LeveledSource` and fills `awaiting`/`failed`. `pageRows` takes the entry's view and, for a keyed query, its `viewRowOf()` and its `sourceRowOf` (Task 4's two trailing parameters), so a keyed key is one lookup. `retain` is not in the key (Task 17b merges it per request). When `context.rowScoped` is set and `served.scope` is empty, `answerQuery` answers `SourceContract` ("a row-scoped table needs a scope") before it reads anything. + +- [ ] **Step 6: Implement `announce` and `attach`** in `remote.hpp` + +- `announce`: refuses (`"unregistered record: "`) when `effects::detail::resolved().recordNamed(record)` is null; otherwise builds `Changes` with `addRecordChange` and `addDerivedChanges`, applies the `kMaxChangeKeys` rule, and posts to the strand a fan-out with no caller (`fanOut(changes, 0, {})`'s path) that does not call the observers. Callable from any thread. +- `attach`: stores the observer and calls `observer->bind(sink)`, `sink` capturing `std::weak_ptr` and calling `announce` when the server is alive, nothing otherwise. +- `fanOut` (an execute's or a time fact's changes) calls each observer's `changed(changes)` first, on the strand, then queues events; an announce reaches the private fan-out step that skips observers. +- `ServerConfig::views` sizes the server's one `ViewCache`, made with `table::makeViewCache(config.views)` at construction and held by `std::shared_ptr` (the type stays incomplete in `remote.hpp`); `viewStats()` returns `table::viewCacheStats(*_views)`. The server puts the pointer in the `TableRuntime` it installs around a dispatch (A2), and `QueryTable::invoke` passes `AnswerContext{.views = runtime->views, .record = , .rowScoped = }` (`views` null when no runtime is installed, as under `LocalBackend`; `record` and `rowScoped` are filled either way). + +- [ ] **Step 7: Run the targets** — `ctest --test-dir build/cl-debug -R "^(view cache|table)" --output-on-failure` and `ctest --test-dir build/linux-everything -R "^(table over the bridge|announce|tables)" --output-on-failure`: all pass. + +- [ ] **Step 8: Benchmarks** — S7 (ten page requests of one sorted view: requests two to ten), S9 (a keyed query of 20 keys: first and next) in `bench_table.cpp`; C1–C3 timings (strand's longest task, views computed per second) in `test_push_unloaded_rows.cpp` under `"[.benchmark][net]"`. Record into table.md. + +- [ ] **Step 9: Update `docs/spec/core/backend.md` "Fan-out"** (`ServerConfig::tableWork`, `views`; `announce`; `attach` and the observer call before events). Docs build green. + +- [ ] **Step 10: Mutations, then commit** + +```bash +git add include/morph/table include/morph/core src/ui/process_state.cpp tests docs/spec/core/backend.md +git commit -m "feat(net): announce arrivals and cache views" +``` + +--- + +### Task 7: The window under changes (table.md step 2d) + +Two commits: **7a** `PageWindow`; **7b** the session's read and watch, the query cache's open, partial and opaque entries, and the bridge's end-to-end case. + +**Spec:** "The window under changes" (all), "Partial pages" (the window's members), "The client's caches", "Which client cache a screen uses", "Arrival" steps 4–6; Tests rows "An event that precedes its page reply", "An ordinary edit on the same record", "Invalidation faster than a round trip", "A reply holds the named columns only" (window half), "A row the window never held", "An open entry hears every change", "A partial entry is not merged into", "An opaque entry", "A read with no entry", (b) window, (d) window and bridge; invariants 8, 9, 10, 30; gates K1–K4, K6, K7, E1–E4. + +**Files (7a):** +- Modify: `include/morph/table/query.hpp` (`PageFetch::{columns, revision}`; `RowsFetch`; `Refresh`; `RefreshPlan`; `detail::WindowCore`; `PageWindow`; the declaration `template <> class PageWindow>;`) +- Modify: `include/morph/table/description.hpp` (the definition of `PageWindow`) +- Test: `tests/table/test_table_server.cpp`; `tests/table/bench_table.cpp` (K1–K3) + +**Files (7b):** +- Modify: `include/morph/ui/interpreter.hpp`, `src/ui/interpreter.cpp` (`CallOptions::stop`; `Session::read`, `Session::watchRecord`, `WatchHolder`; open, partial and opaque entries) +- Modify: `include/morph/ui/document.hpp` (`ActionRecordInfo::{open, partial, opaque}`), `include/morph/ui/author.hpp` (copies them), `include/morph/core/effects.hpp` (`ActionRecord::{open, partial}`; `opaque` is Task 2's, A4), `include/morph/core/detail/result_walker.hpp` (holder members), `include/morph/table/query.hpp` (`Page::openMembers`, `Page::partialMember`) +- Modify: `include/morph/ui/value.hpp` (`detail::tableValueFromJson`, decision 46) +- Modify: `tests/ui_interpreter_support.hpp` (`Harness(ui::Catalog catalog, bool recordWatches = false)`: the catalog is a member the session's options and `mount`'s `loadOrFail` both read, in place of their two calls of `corpusCatalog()`; the existing constructors pass `corpusCatalog()`) +- Create: `tests/test_ui_interpreter_cache.cpp` (in `morph_tests`) +- Test: `tests/net/test_push_unloaded_rows.cpp` +- Docs: `docs/spec/core/registry.md` (`openMembers`, `partialMember`, an opaque holder), `docs/spec/ui/interpreter.md` "Queries and the cache" (open, partial, opaque entries; `Session::read`, `watchRecord`) + +**Interfaces:** +- Consumes: Task 4's `UnloadedRow`, `UnloadedLevels`, `GenericPage`, keyed replies; Task 6's `changeKeys`/`rowIdOf` (Task 5), `announce`. +- Produces (7a), in `query.hpp` unless noted: + - `struct PageFetch { PageRequest request; std::vector columns; std::uint64_t query = 0; std::uint64_t revision = 0; bool operator==(PageFetch const&) const = default; };` + - `struct RowsFetch { std::vector keys; std::vector columns; std::uint64_t query = 0; std::uint64_t sequence = 0; };` + - `enum class Refresh : std::uint8_t { Nothing, Rows, Pages };` `struct RefreshPlan { Refresh kind = Refresh::Nothing; RowsFetch rows; };` + - `PageWindow`: `explicit PageWindow(std::int64_t pageSize = 200, std::size_t maxPages = 8, RowKey key = {}, std::size_t maxKeys = 1000, std::size_t maxColumns = 96);` `std::vector visible(std::int64_t first, std::int64_t count, std::span columns = {});` `std::vector superseded() const;` `void cancelled(PageFetch const& fetch);` `RefreshPlan refresh(std::span keys);` `RefreshPlan owed();` `void invalidate();` `bool accept(PageFetch const& fetch, Page reply);` (keeps the existing `bool`: `false` when ignored) `std::vector patch(RowsFetch const& fetch, Page reply);` `UnloadedLevels unloadedLevels(std::int64_t index) const;` `std::int64_t undecided() const noexcept;` `std::span awaiting() const noexcept;` `std::span failed() const noexcept;` `std::uint64_t revision() const noexcept;` and the existing `fail`, `reset`, `query`, `row`, `total`, `totalKind`, `error`, `pagesHeld`, `pending` + - `PageWindow` (in `description.hpp`): the same members with `GenericPage` in place of `Page` and no key function parameter (`explicit PageWindow(std::int64_t pageSize = 200, std::size_t maxPages = 8, std::size_t maxKeys = 1000, std::size_t maxColumns = 96);`), and in place of `row`: `RowId const* key(std::int64_t index) const;` `Cell const* cell(std::int64_t index, std::string_view column) const;` (null when the row or the column is not held) `bool holds(std::int64_t index, std::string_view column) const;` +- Produces (7b): + - `CallOptions::stop` (`::core::async::StopToken`; a stop sends the wire's `cancel` where the server takes one) + - `async::Completion Session::read(std::shared_ptr const& channel, std::string const& actionId, Value const& body, ::core::async::StopToken stop = {});` — resolves with the reply's JSON text, not a `Value`: a page's Number cells are JSON numbers with fractions, which `ui::valueFromJson` refuses, so the caller decodes the text itself (`table::readGenericPage`, Task 11c's `readTypedPage`). table.md declares the same signature (index decision 30). + - `class WatchHolder` (decision 47: a copyable handle over a `std::shared_ptr` to one registration; the record is counted out and the handler removed when the last copy dies. `Completion` hands its value to a handler as `const T&`, `core/completion.hpp`, so a `then` handler keeps the watch by copying the holder; a default-constructed holder holds nothing. The registration holds the session weakly, so a holder that outlives its session releases nothing) + - `Session::settleReply`'s table-aware decode for an opaque entry (decision 46), through `[[nodiscard]] std::expected ui::detail::tableValueFromJson(Json const& json);` in `value.hpp` + - `async::Completion Session::watchRecord(std::string const& record, std::function handler);` + - `effects::ActionRecord::{std::vector open; std::vector partial;}` beside Task 2's `opaque`, and `ui::ActionRecordInfo::{open, partial, opaque}` (all in `operator==`) + - `static constexpr std::array Page::openMembers() noexcept { return {"awaiting", "distinct"}; }` and `static constexpr std::string_view Page::partialMember() noexcept { return "unloadedRows"; }` (`distinct` exists once Task 8a lands; until then the walk skips a named member the holder lacks) + +#### 7a — `PageWindow` + +The rules no test alone fixes, which both specialisations share through `detail::WindowCore` (all bookkeeping that does not touch a row's content: pages, keys per row, unloaded levels per row, staleness, revisions, fetches in flight, totals, sequences): + +- **State.** `_query` (`reset` advances), `_revision` (`invalidate` advances), per held page `{keys, unloaded levels per row, stale, complete, columns held (generic) with the visible-call stamp of each}`, at most one fetch in flight per page (the window remembers it, so `accept` knows whether it was a whole-page or a column fetch), totals `{total, totalKind, undecided, awaiting, failed}` with `_totalsRevision`, `_sequence`, `_latestAsked: RowId → sequence` (held keys only; a key is forgotten when it leaves the held pages, so it never outgrows the held rows), `_latestKeyed` (the sequence of the latest `RowsFetch`), `_owed` (keys recorded while a page fetch is in flight). +- **`visible(first, count, columns)`** covers pages `first/pageSize − 1` to `(first + max(count,1) − 1)/pageSize + 1`, skipping pages past an exact total and pages with a fetch in flight. Not held, or held stale → a whole-page fetch `{offset p·size, limit size}` with `columns`, tagged `revision = _revision`. Held, current and short (a server cut it) → the rest of the page, with the columns held. Held, current, complete but lacking some of `columns` (generic only) → a column fetch of the same rows (`{p·size, rows held}`) naming only the missing columns, in the order given. Each returned fetch is recorded in flight. A typed window ignores `columns` and always fetches `{}`. +- **`accept`.** Ignored (`false`) when `fetch.query != _query` or the fetch is not the one in flight for its page; the in-flight record is removed either way when it matches. A column fetch: when the reply's `keys` equal the page's row for row, its cells are added (each row's unloaded levels become the union of held and reply levels) and over `maxColumns` the columns with the oldest visible-call stamp go; otherwise `invalidate()`. A whole-page fetch: the page's rows, keys and unloaded levels are replaced (a rest-of-page fetch appends as today) and `stale = fetch.revision != _revision`. With at most one fetch in flight per page and a reply accepted only as that fetch, a reply older than the held content cannot arrive: the spec's "a reply older than the held content is ignored" holds by construction, and the window keeps no content revision. A page reply with `fetch.revision >= _totalsRevision` sets `undecided`, `awaiting`, `failed` and `_totalsRevision`, and sets `total`/`totalKind` only when the reply carries a `total` (an absent total neither replaces a known one nor counts as a difference); when a present `total`, its `totalKind`, or `undecided` differ from the window's, every other held page is marked stale. **A view that shrank holds nothing past its end:** when the total the window now has is `Exact`, every held row at a view row at or past it is dropped (a page wholly past it is dropped, the page the total falls in is cut to it and counts as complete), and every fetch in flight for a page wholly past it is forgotten, so its late reply is ignored as any reply without a fetch in flight is and `pending()` does not wait for it. Without this a page past the total is never refetched (`visible` skips it) and never dropped, and its first key stays a probe that no reply can answer, so every later event would invalidate. Pages over `maxPages` go farthest first. +- **`superseded()`** returns the fetches in flight for pages outside the range `visible` last covered; **`cancelled`** removes a matching in-flight record. +- **`refresh(keys)`.** While any page fetch is in flight, the keys are appended to `_owed`. Then: no row held → `Nothing`; no key function (typed) or `awaiting()` not empty → `invalidate()`, `Pages`; otherwise the keys are the event's keys (deduplicated, held or not) plus, per run of consecutive held view rows (across adjacent held pages), the key of the run's first row unless already present; more than `maxKeys` → `invalidate()`, `Pages`; else `Rows` with `RowsFetch{keys, columns: the columns of the latest visible call (typed: {}), _query, ++_sequence}`, each key's `_latestAsked` set to the sequence and `_latestKeyed` to it. +- **`owed()`** builds a plan from `_owed` by the same rules as `refresh` without recording again; `Nothing` when `_owed` is empty. It then clears `_owed` when no page fetch is in flight, **and always when the plan is `Pages`**: the invalidation took a new revision, every reply still in flight is older than it and leaves its page stale, so the refetch that follows covers every recorded key. Keeping the keys there would never end: the client calls `visible` after every `accept`, so with two or more pages around the visible rows a fetch is in flight at every `accept`, and each `owed()` would invalidate again with no event behind it (invariant 10). +- **`patch(fetch, reply)`.** Ignored (empty result) when `fetch.query != _query`. A reply row whose key has `_latestAsked > fetch.sequence` is ignored, missing or not. `invalidate()` and an empty result when: a requested key the window holds (and no later fetch asked for) has no row; a reply row's key is held at another view row than `reply.indices`; a reply row's key is not held and its view row lies inside a held page; `fetch.sequence == _latestKeyed` and the reply's `total`, `totalKind` or `undecided` differ from the window's. Otherwise each held row with a reply row at its view row is replaced (its unloaded levels with the reply's); in a generic window, a column the page holds that the reply lacks is dropped from that page, so the next `visible` fetches it again rather than showing a cell older than its row. The replaced view rows are returned ascending. `patch` never adds, removes or reorders held rows, and never sets the totals. +- **`invalidate()`** advances `_revision` and marks every held page stale; rows stay shown, fetches stay in flight. + +- [ ] **Step 1: Write the failing window tests** in `tests/table/test_table_server.cpp` + +Helpers in the file: `using Win = PageWindow;` `GenericPage pageOf(std::int64_t offset, std::vector keys, std::vector columns, std::int64_t total, std::int64_t undecided = 0)` (one integer cell per column, the key's value); `GenericPage keyedOf(std::vector> keyAtIndex, columns, total, undecided = 0)`; `std::vector ids(std::initializer_list)`. + +```cpp +// Mutation: refresh not recording keys while a page fetch is in flight. +TEST_CASE("window: an event that precedes its page reply is owed", "[table][window]") { + Win window{10, 8}; + std::vector const cols{"a"}; + auto const fetches = window.visible(0, 5, cols); + REQUIRE(fetches.size() == 2); + CHECK(window.refresh(ids({3, 4})).kind == Refresh::Nothing); // nothing held yet + GenericPage reply = pageOf(0, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, cols, 20); + reply.unloadedRows = {{3, {"recipe"}, {}}, {4, {"recipe"}, {}}}; + REQUIRE(window.accept(fetches[0], std::move(reply))); + auto const plan = window.owed(); + REQUIRE(plan.kind == Refresh::Rows); + CHECK(std::ranges::is_permutation(plan.rows.keys, ids({3, 4, 0}))); // the keys and the run's probe + CHECK(window.unloadedLevels(3).levels.size() == 1); +} + +// Mutation: refresh skipping held rows with no unloaded level. +TEST_CASE("window: an ordinary edit on a held row is a keyed fetch, a move invalidates", "[table][window]") { + Win window{10, 8}; + std::vector const cols{"a"}; + for (auto const& fetch : window.visible(0, 5, cols)) { + REQUIRE(window.accept(fetch, pageOf(fetch.request.offset, fetch.request.offset == 0 + ? std::vector{0,1,2,3,4,5,6,7,8,9} : std::vector{10,11,12,13,14,15,16,17,18,19}, + cols, 20))); + } + auto const plan = window.refresh(ids({7})); + REQUIRE(plan.kind == Refresh::Rows); + CHECK(std::ranges::is_permutation(plan.rows.keys, ids({7, 0}))); // one run, rows 0–19: one probe + auto const replaced = window.patch(plan.rows, keyedOf({{0, 0}, {7, 7}}, cols, 20)); + CHECK(replaced == std::vector{0, 7}); + auto const again = window.refresh(ids({7})); + auto const before = window.revision(); + CHECK(window.patch(again.rows, keyedOf({{0, 0}, {7, 12}}, cols, 20)).empty()); + CHECK(window.revision() == before + 1); +} +``` + +Add, each a `TEST_CASE` with its mutation: +- `"window: invalidation faster than a round trip advances one reply per trip"`: hold page 0; `invalidate`; `visible` → one fetch `f1` (revision r1); `invalidate` again (r2); `visible` → nothing (page 0 in flight); `accept(f1, rows A)`: `cell(0,"a")` shows A, the page is still stale, and `visible` returns exactly one fetch tagged r2. Mutation: `accept` ignoring every older revision. +- `"window: a column scrolled in is fetched for held pages and merged by key"` (row "A reply holds the named columns only", window half; gate K7): two complete pages with `{a}`; `visible(0, 5, {a, b})` returns two column fetches naming only `{b}`, offsets 0 and 10, limits 10; accepting replies with the same keys adds `b` (`cell(3,"b")` non-null, `cell(3,"a")` unchanged); a column reply whose `keys` differ invalidates. Mutation: a column fetch naming every column. +- `"window: over maxColumns the columns farthest from view go first"`: `maxColumns = 2`; visible `{a,b}`, then `{c}`: after the column reply, page holds `{b,c}` or `{a,c}` — assert `c` held and exactly 2 held, and the one dropped is the column least recently named (`a` when the second call was `{b, c}`). Mutation: dropping the newest. +- `"window: a page reply with another total adopts it and marks other pages stale"`: page size 10, pages 0 and 1 held with total 30; `visible(15, 10, cols)` fetches page 2; its reply says total 35: `total() == 35`, and the next `visible(15, 10, cols)` returns three fetches: pages 0 and 1 whole (offsets 0 and 10, limit 10, every column), and page 3 (offset 30), which the larger total brought into range. Mutation: totals adopted without marking (page 3's fetch alone). +- `"window: a reply without a total keeps the known one"`: the existing `"table: the window keeps a known total when a reply omits it"` still passes, and a page reply with `total` absent marks no page stale. Mutation: an absent total counted as a difference. +- `"window: a patch drops the columns its reply lacks"`: page 0 holds `{a, b}`; a keyed reply naming only `{a}` for key 3 is patched: `cell(3, "a")` is the reply's, `holds(3, "b")` is false, and `visible(0, 5, {a, b})` returns a column fetch naming `{b}`. Mutation: `patch` keeping the old `b` cells. +- `"window: a row the window never held"` (four invalidating shapes and one not): held pages 0–1 of 100 rows; a keyed reply with (i) an unheld key at view row 5, (ii) the probe at view row 1, (iii) total 101 on the latest fetch, (iv) a requested held key missing — each invalidates (`revision()` +1); (v) an unheld key at view row 80 with the total unchanged, the reply also holding the run's probe (key 0 at view row 0) → no invalidation, and `patch` returns `{0}`: the probe's row and nothing else. Mutation: no probes (shape ii undetected: assert the plan's keys contain the run's first key). +- `"window: an older keyed reply never overwrites a newer one"`: fetch F1 for key 7, then F2 for key 7; patch F2's reply (value 2), then F1's reply (value 1): `cell(7,"a")` holds 2, and F1's reply with key 7 missing does not invalidate. Mutation: no per-key sequence. +- `"window: the totals of an old keyed reply are not compared"`: F1 then F2; F1's reply carries total 30 (window 20): no invalidation. Mutation: comparing totals on every keyed reply. +- `"window: an awaited order or too many keys refetches pages"`: a page reply with `awaiting {"recipe"}` → `refresh` returns `Pages` and advances the revision; `maxKeys = 3` and an event of 3 keys plus 1 probe → `Pages`. Mutation: the key count compared before adding probes. +- `"window: superseded fetches are those left behind"` (K6 at window level): `visible(0,…)` → pages 0,1; `visible(50'000, 20)` → `superseded()` returns the fetches of pages 0 and 1; after `cancelled` for each, their late replies are ignored. Mutation: `superseded` returning every fetch. +- `"window: a typed window without a key function refreshes pages"`: `PageWindow{10, 8}` holding a page: `refresh` → `Pages`. Mutation: probing without keys. +- `"window: unloaded levels agree with the page after accept"` (row (b) window): the reply's `unloadedRows {{2,{"recipe"},{"recipe"}}}` → `unloadedLevels(2).levels == {"recipe"}`, `.failed == {"recipe"}`, `unloadedLevels(1)` empty. Mutation: `accept` dropping `unloadedRows`. +- `"window: a view that empties shows no rows and asks no more"` (Review Focus 4): pages 0–1 held, total 20; a keyed reply on the latest fetch with no rows and total 0 invalidates; `visible(0, 5, cols)` returns the refetches of pages 0 and 1; the whole-page reply of page 0 with no rows and total 0 is accepted: `key(0)` and `key(10)` are null (page 1 was past the new total and is dropped), `total() == 0`, `pending()` is false although page 1's reply never came, that reply is ignored when it does (`accept` returns `false`), `visible(0, 5, cols)` returns nothing, and a later `refresh(ids({3}))` is `Nothing` (no row held, so no probe). Mutations: the total adopted without dropping what lies past it (`key(10)` stays, `pending()` stays true); the pages past it dropped but their fetches kept in flight (`pending()` stays true, the late reply is accepted). An empty reply leaving the page incomplete cannot fail this case: page 0 lies wholly past a total of 0, so it is dropped whatever its completeness. +- `"window: an owed invalidation ends"`: pages 0 and 1 held, each last reply carrying `awaiting {"recipe"}`; `invalidate()`, `visible(0, 5, cols)` → two fetches in flight; `refresh(ids({3}))` (recorded, and `Pages`); accept page 0's reply: `owed()` is `Pages` once; `visible` returns page 0's refetch; accept page 1's reply: `owed()` is `Nothing`; after the refetches `visible` asks for are accepted with no further event, `visible(0, 5, cols)` returns nothing, `pending()` is false, and `revision()` rose by exactly three since the start (the `invalidate`, the `refresh`, the one `owed`). The same holds for a `PageWindow` without a key function. Mutation: `owed()` keeping `_owed` after a `Pages` plan (the revision rises at every `accept`, without end: assert it after six rounds). +- Gate K2 `"window: a refresh of 900 keys over eight runs asks 908"`: 8 pages held in eight runs (pages 0,2,4,…,14 of 100,000 rows, each its own run), an event of 900 keys: `plan.rows.keys.size() == 908`. Mutation: probing every held row. + +Bridge-free typed regression: the existing `PageWindow`/`PageWindow` cases keep passing with the new constructor (defaults unchanged), with two changes the new rules force: in `"table: the window ignores a reply it does not await or that no longer fits"` a late reply to a page's first fetch, made while the rest-of-page fetch is in flight, is ignored (`false`) and leaves the rest awaited, since it is not the fetch in flight for its page; in `"table: the window fetches the pages around the visible rows"` the replies carry total 700 rather than 600, since an exact total of 600 now drops page 6 (offset 600) and forgets its fetch. + +- [ ] **Step 2: Run to verify failure** — `cmake --build --preset cl-debug --target morph_table_tests`: compile errors naming `refresh`, `RowsFetch`, `revision`, `PageWindow` incomplete. + +- [ ] **Step 3: Implement `detail::WindowCore`, `PageWindow` and `PageWindow`** per the rules above. `query.hpp` declares `template <> class PageWindow>;` before any use so that a translation unit without `description.hpp` cannot instantiate the primary template for generic rows (it fails as incomplete instead). The generic page stores cells per column (`std::map, std::less<>>` per page). + +- [ ] **Step 4: Run the target** — `ctest --test-dir build/cl-debug -R "^(window|table)" --output-on-failure`: all pass. + +- [ ] **Step 5: Benchmarks** (`"[.benchmark][window]"`): K1 (`accept` of a 200 × 300 generic page), K2 timing (the gate case's refresh), K3 (`patch` of 200 rows). Record into table.md's "Benchmarks: client cache and window". + +- [ ] **Step 6: Mutations, then commit** + +```bash +git add include/morph/table tests/table +git commit -m "feat(table): the page window under changes" +``` + +#### 7b — reading and watching without entries, open, partial and opaque entries, end to end + +- [ ] **Step 7: Write the failing cache tests** in `tests/test_ui_interpreter_cache.cpp` + +The catalog: `corpusCatalog()` wrapped so that `T_Page` (model `Lims_SampleModel`) has `records = {ActionRecordInfo{.record = "T_Row", .keyField = "code", .paths = {"rows"}, .open = {"awaiting"}, .partial = {"unloadedRows"}}}` and `T_TablePage` has `{.record = "T_Row", .opaque = true}`; `Harness h{catalog};` documents query them as `kList` in `tests/test_push_cache.cpp` does. + +```cpp +// Mutation: the cache ignoring `open`. +TEST_CASE("cache: an open entry is marked by a change to a key it does not hold", "[push][cache][table]") { + Harness h{tableCatalog()}; + auto screen = h.mount(kPageList); // one query of T_Page + h.reply(0, R"({"rows":[{"code":1}],"awaiting":["recipe"],"unloadedRows":[]})"); + h.session.applyChanges(changesOf("T_Row", {"99"})); + h.settle(); + CHECK(h.dispatcher.calls.size() == 2); // refetched + h.reply(1, R"({"rows":[{"code":1}],"awaiting":[],"unloadedRows":[]})"); + h.session.applyChanges(changesOf("T_Row", {"99"})); + h.settle(); + CHECK(h.dispatcher.calls.size() == 2); // not open any more: key 99 is not held +} +``` + +Add: +- `"cache: a partial entry is not merged into"`: reply with `unloadedRows [{"index":0,"levels":["recipe"]}]`; an `updates T_Row` reply of `{code:1, qty:5}` marks the entry (one more call) and leaves `rows[0].qty` as it was; with `unloadedRows []` the same reply merges (`rows[0].qty == 5`, no call). Mutation: the cache ignoring `partial`. +- `"cache: an opaque entry is marked by every change and never merged"`: a `T_TablePage` entry and a distinct-values-shaped entry of the same action are both marked by a keyed change naming key 99, and an `updates` reply marks without merging. Mutation: the cache looking for a key member. +- `"cache: a read makes no entry"`: `session.read(channel, "T_Page", body)` resolves with the reply's text, byte for byte as the channel returned it; `cacheSize()` unchanged; a stop before the reply settles the completion as cancelled and passes `CallOptions::stop` to the channel. Mutation: `read` going through `acquire`. +- `"cache: a read's text keeps a fractional number"`: the channel replies with a generic page of one row whose Number cell is `2.5` (written by `table::writeGenericPage` over a one-column description); `session.read` resolves, and `table::readGenericPage(text, description)` decodes it to a page whose cell `(0, "n")` is the number 2.5. Mutation: `read` parsing the reply through `valueFromJson` and resolving with `canonicalJson` of the result (the completion fails: a number with a fraction is refused). +- `"cache: a watch without an entry joins the watch set"`: `watchRecord("T_Row", handler)` sends one `watch` naming `T_Row` and resolves after its reply; the test's `then` handler copies the holder out of the `WatchHolder const&` it is given and the completion is then destroyed: `watchSet()` names `T_Row` while that copy or a copy of it lives, and not after the last one is destroyed (one `unwatch`, sent then and not before); a `resync` event calls the handler once with `keys` absent; a `changes` event for `T_Row` calls it with the event's keys. Mutations: holders not counted in the watch set; the registration released when the first copy dies (the `unwatch` goes out while a copy lives). +- `"cache: an opaque entry keeps a fractional number"` (decision 46): a `T_TablePage` query replied `{"revision":"r","columns":["n","big","i"],"keys":[1],"rows":[[2.5,1e300,7]],"total":1,"totalKind":"exact","offset":0}` settles with a value and no error; `rows[0][0]` is the decimal 2.5 (`num` 25, `den` 10, one place), `rows[0][1]` is the text `"1e+300"` (`std::format("{}", 1e300)`, which `table::parseDecimal` refuses), `rows[0][2]` is the integer 7. The same reply to a `T_Page` query (not opaque) fails the entry with "the reply is not a document value". Mutations: `settleReply` using `valueFromJson` for every entry (the opaque entry is in error); the table-aware decode used for every entry (the `T_Page` entry settles). + +In `tests/net/test_push_unloaded_rows.cpp`, the bridge half of (d) with gate E3: + +```cpp +// Mutations: refresh asking for every held key; refresh dropping the keys the window does not hold. +TEST_CASE("table over the bridge: exactly the arrived rows update, without polling", "[net][push][levels]") { + // WideTableModel::configure: small with recipePreloaded = 0, recipeBatch = 20; the recipe gate held. + // No refreshEvery, no clock advanced. The CountingChannel counts page requests (no `keys`) and keyed ones apart. + // 1. watchRecord("WideTableModel.small") resolves. PageWindow w{200, 8}; w.visible(0, 30, {"id","d000"}) + // returns two fetches (pages 0 and 1: no total is known yet); each is sent with Session::read, its text decoded + // with table::readGenericPage(text, *description) (the description read from the action + // Table.small.describe), and accepted. + // pageRequests == 2, keyedRequests == 0; every row's unloadedLevels names "recipe". + // 2. Settle 200 ms: still 2 and 0. + // 3. recipeGate().release(1): one loader call of 20 keys runs (the display wants keep each want's keys in + // order, newest want first, so they are the first 20 keys of one page). Let L = model.loaderCalls()[0]. + // The cache stores, then announces L; the watch handler calls w.refresh(keys). + // 4. The plan is Rows; its keys are L plus the probe of the one held run (key 1, the first held row) — CHECK + // is_permutation(plan.rows.keys, L ∪ {1}). One keyed request is sent: pageRequests == 2, keyedRequests == 1. + // 5. w.patch returns the view rows of L, plus row 0 when key 1 was a probe, ascending; for each key of L its + // row's unloadedLevels is empty and cell(row, "d000") is the generator's value; a row not in L still names + // "recipe". +} +``` + +Add `"table over the bridge: the same arrival through the query cache"` (E4): a document query on `Table.small` (a page read by a `rows` table) holds the same page; the arrival marks that one entry and it refetches once: one page request per marked entry. `small` has no `Number` column (its Rationals cross as `[n, d]`, which a `Value` holds), so this case does not exercise decision 46; `"cache: an opaque entry keeps a fractional number"` above does. Mutation: the cache looking for a key member in an opaque entry (the arrival's keys match no row, and nothing refetches). + +- [ ] **Step 8: Run to verify failure** — `cmake --build --preset cl-debug --target morph_tests` (and `morph_net_tests` on `linux-everything`): compile errors naming `read`, `watchRecord`, `open`. + +- [ ] **Step 9: Implement the catalog's members** + +- The result walk records, for each visited `Object` holder with `openMembers()` or `partialMember()`, its path and those members' paths (`ActionResult` gains `std::vector holders`, `struct HolderMembers { std::string path; std::vector open; std::string partial; };`). A named member the holder's reflection lacks is skipped. +- Resolution gives each matched `ActionRecord` the `open` and `partial` paths of every holder whose path is a prefix of (or equal to the parent of) the record's path. `Table.`'s opaque slot is Task 2's (A4). `ui::author` copies `open`, `partial` and `opaque` into `ActionRecordInfo`. + +- [ ] **Step 10: Implement the cache rules** in `src/ui/interpreter.cpp` + +A helper `bool memberSet(Value const& value, std::string_view path)`: set when the value at `path` is a non-empty array, an object, `true`, or a number other than zero. `markRecordChange` marks an entry whose held record is `opaque` or has any `open` path set, whatever the keys. `applyRecordEffect` treats `updates` as `changes` for an entry whose record is `opaque` or has any `open` or `partial` path set (the discarded-reply downgrade already marks only). + +**A page in the query cache** (decision 46). `Session::settleReply` reads every reply through `valueFromJson`, which refuses a number with a fraction and so fails the whole entry; a generic page writes a `Number` cell as such a number. For an entry that holds an `opaque` record, `settleReply` reads the reply with `detail::tableValueFromJson` instead. It is `valueFromJson` but for a JSON number that is not an integer: that becomes the decimal `Value` its shortest round-trip text in fixed notation spells, `table::parseDecimal` of `std::to_chars(…, number, std::chars_format::fixed)` (`std::format("{}")` would write `0.0001` as `1e-04`, which `parseDecimal` refuses), and when `parseDecimal` refuses the text (more than 18 places, a numerator past `int64`) the `Value` is `std::format("{}", number)`. `tableValueFromJson` is declared in `value.hpp` and defined in `src/ui`, so `value.hpp` includes no table header. Non-finite numbers are already strings on the wire. Every other entry keeps the strict rule. A `rows` table over such a page therefore sees a `Decimal` column (Task 11a's inference), with a text among its cells where a number had no decimal form. + +- [ ] **Step 11: Implement `read` and `watchRecord`** + +- `CallOptions::stop`; `BridgeDispatcher::Channel::execute` uses `RawHandler::execute(…, stop)` when `stop.stop_possible()`. +- `read` sends through `channel->execute(actionId, canonicalJson(body), CallOptions{.stop = stop})` and settles on the owner with the reply's text unparsed; no entry is made, no effects applied; a stopped call settles cancelled and its reply is dropped. It does not read the reply into a `Value`: `valueFromJson` refuses a number with a fraction, and a page's Number cells are such numbers. +- `watchRecord` counts the record in `_recordRefs` as an entry does (a count leaving zero sends a `watch` for it at once, through `flushWatches`), stores the handler under a holder id, and resolves when that watch's reply arrives (at once when the record was already watched and acknowledged, or there is no watcher). `applyChanges` calls each handler whose record a change names, after marking entries; `reconnected` (reconnect and `resync`) calls each with `RecordChange{record, nullopt}`. `WatchHolder` is a `std::shared_ptr` to the registration (decision 47): the registration's destructor, which runs when the last copy of the holder dies, removes the handler and counts the record out through the session it holds weakly. The completion's own copy is one of them, so a caller that wants the watch keeps a copy and lets the completion go. + +- [ ] **Step 12: Run the targets** — `ctest --test-dir build/cl-debug -R "^(cache|stale_mark|own_updates|changes_reply)" --output-on-failure` and `ctest --test-dir build/linux-everything -R "^table over the bridge" --output-on-failure`: all pass, the existing push-cache cases included. + +- [ ] **Step 13: Benchmarks** — K4 (a 4,096-key event against an entry of 200 rows; storing a decoded 200 × 300 page) in `tests/bench_interpreter.cpp`; E1 (first page of sorted 100,000 × 300 `wide` with `recipe` unloaded, request to accepted page, against no level) and E2 (loader return to patched rows for 20 rows, p50/p99) in `test_push_unloaded_rows.cpp` under `"[.benchmark][net]"`. Record into table.md's "Benchmarks: client cache and window" and "Benchmarks: end to end". + +- [ ] **Step 14: Docs** — `docs/spec/core/registry.md` (a holder's `openMembers()`/`partialMember()`; `ActionRecord::open`, `partial`, `opaque`; `Table.` holds its record opaquely); `docs/spec/ui/interpreter.md` "Queries and the cache" (the three entry rules; `Session::read`, which resolves with the reply's JSON text because a `Value` holds no number with a fraction or an exponent and a page's Number cells are such numbers, so the caller decodes with `table::readGenericPage`; `watchRecord` and its copyable holder; an opaque entry's reply read with fractional numbers as decimals, and as text where no decimal holds them); `Session::read`'s `@return` in `interpreter.hpp` says the same. Docs build green. + +- [ ] **Step 15: Mutations, then commit** + +```bash +git add include/morph src/ui tests docs/spec +git commit -m "feat(ui): read and watch without entries; open, partial and opaque cache entries" +``` + +--- + +## Review Focus + +Up to five input classes the spec implies and no row of its Tests table exercises; each has its test in the owning task. + +1. **An invalidation between a want and its load's return, followed by another want.** A query that follows the invalidation's event while the stale load still runs must start a fresh load, not wait on one that will be dropped; otherwise the row stays unloaded until some later request. Test: Task 5, `"level cache: a want after an invalidation does not wait for the stale load"`. +2. **A loaded cell that goes back to `Unloaded`** (a server dropping what it loaded). The row moves to the unloaded tail of its sort, or becomes undecided and leaves a filtered view, with `onUndecidedChange`. Test: Task 3a, `"table: a cell dropped back to unloaded moves to the tail or leaves the view"`. +3. **Keys that are awkward JSON.** A text key with a quote, a backslash and non-ASCII, and an integer key above 2^53, through `changeKeys`/`rowIdOf` (and so through an announcement), must come back as the same `RowId`. Test: Task 5, `"table: change keys round-trip awkward keys"`. +4. **A view that empties.** Every row leaving the view (an edit, a filter's level arriving): the window must show no rows, a total of 0, and stop fetching. Test: Task 7a, `"window: a view that empties shows no rows and asks no more"`. +5. **A row entering from the undecided set under `ReorderPolicy::Deferred`.** It takes its true place at once and is not held; displayed rows keep their indices. Test: Task 3a, `"table: under deferred reorder an undecided row takes its true place at once"`. + +## Self-review notes + +- **Where the spec now agrees:** `Session::read` resolves with text (30) and an opaque entry's reply is decoded with fractional numbers as decimals (46); table.md states both, with their reasons. **Deviations from the spec's text, each by an index decision:** `WatchHolder` is copyable (47); `AnswerContext` carries the record and the row-scope flag (48); `ViewCacheOptions` and `ViewCacheStats` live in `table/runtime.hpp` so that `core/remote.hpp` includes no other table header, and `ViewCacheOptions::onCompute`, `RemoteServer::viewStats()` and `RowSnapshot::identity()` are additions the spec's blocks do not list. +- **Rules the window adds to the spec's:** `owed()` drops its keys when it invalidates, and a page reply with an exact total drops what the window holds past it. Both close a loop the spec's rules leave open; each has its case in Task 7a. + +- **Coverage.** Spec rows (a)–(d), the cache rows, the window rows and the client-cache rows of "Tests" each map to a named case above. Gate K6's "at most three sent" and the timing rules of "When a fetch is sent" are `WindowRows`'s (Task 9); here the window's half (`superseded`) is tested. W3, W4, S1, S2, S4 timings are recorded, not gated, per "How figures are taken". L9 is not in step 2c's gate list; "A cache's size is deep" covers its behaviour. +- **Placement follows the index's Cross-part decisions:** `Page::{unloadedRows, undecided, awaiting, failed}` and `UnloadedRow` in Task 3b (decision 3); `effects::IChangeObserver`/`AnnounceSink`, `changeKeys`, `rowIdOf` in Task 5 (decision 4); `TableQuery::columns` and `maxColumns` in Task 1 (decision 2); `PageWindow`'s `key`, `cell`, `holds`, `revision` here in Task 7 (decision 8). diff --git a/docs/superpowers/plans/2026-11-17-one-table-c-engine-config.md b/docs/superpowers/plans/2026-11-17-one-table-c-engine-config.md new file mode 100644 index 000000000..be3f7e560 --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-one-table-c-engine-config.md @@ -0,0 +1,1239 @@ +# The One Table, Part C — the Engine's Configuring Additions: Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Give `morph::table` value-set filters and distinct values, column groups with quantifiers and `together`, values with units over a run-time unit registry, and a column layout with widths, pinning and one fitting rule (table.md Delivery order step 3). + +**Architecture:** Everything lands in the engine headers (`include/morph/table/{data_source,sort,filter,query,engine}.hpp`) plus one UI parser (`include/morph/ui/measure.hpp`). Filters stay compile-once / evaluate-per-cell: a `oneOf` becomes one hashed set, a group becomes per-cell entry bit masks found by one value-index lookup, `Together` is a bipartite matching by augmenting paths, and every evaluation is three-valued (`Match`) over unloaded cells. A `Measure` key is a pair (dimension place, exact base amount) built from tables indexed by `UnitId`, so key building never looks a unit up by name. + +**Tech Stack:** C++23, header-only morph, glaze, Catch2 (`morph_table_tests`), MSVC preset `cl-debug` (timings on `cl-release`). + +**Spec:** `docs/spec/table/table.md` — "Filters from the header" (value-set operator, distinct values, date buckets), "Column groups", "Values with units" (all subsections), "Columns: order, visibility, pinning, width" (the engine half), "Semantics of an unloaded cell" ("Unloaded cells in filters", "Unique values"), Invariants 1, 22–25, Tests rows "`oneOf`", "Distinct values", "Column groups", "Values with units", "Unit numbers across registries", "Column layout" (engine half), "The generic page" (measure half), Benchmarks D1–D6, G1–G7, M1–M5, Neighbouring specs row `../forms/views.md` (step 3), Delivery order step 3. Roadmap: `docs/superpowers/plans/2026-11-17-one-table.md`, Task 8. +Part C of 7; index: 2026-11-17-one-table.md + +## Global Constraints + +Every line of the roadmap's Global Constraints applies. The ones this part touches, verbatim: + +- AGENTS.md "Comments and documentation": a comment or spec states what the code does now and why; no history, no issue numbers, no commit hashes. +- Every public symbol has complete Doxygen `@param`/`@tparam`/`@return`; the docs build runs `WARN_AS_ERROR = FAIL_ON_WARNINGS` (`cmake -S . -B build/doc -G Ninja -DMORPH_BUILD_DOCUMENTATION=ON -DMORPH_BUILD_TESTS=OFF -DMORPH_BUILD_EXAMPLES=OFF && cmake --build build/doc --target doc`). +- morph is public: no company, product or customer names in code, tests, specs or commit messages; examples use the neutral `lims` domain. +- Commits are authored `yaraslau ` and end with the session's attribution lines. +- AGENTS.md "Verify rather than assert": every test names the mutation it was seen to fail on, and the task runs that mutation once and records the failing output in its commit message body. +- Limits, verbatim: `QueryLimits::maxSetValues = 10'000`, `maxQuerySetValues = 20'000`, `maxQuerySetBytes = 1 MiB` (1'048'576 bytes), `maxGroupColumns = 16`; `DistinctRequest::limit = 200`. +- Timings are never CI gates. Count gates (D3, D5, D6, G5, G7, M5) are ordinary tests; timings (D1–D4, G1–G4, G6, G7, M1–M4) are `[.benchmark]` cases in `tests/table/bench_table.cpp`, run on `cl-release`, and written into table.md's "Benchmarks: configuring", "Benchmarks: column groups" and "Benchmarks: values with units" tables in the same commit. +- No GUI application is launched. + +Commands (the roadmap's standard loop): + +```bash +cmake --preset cl-debug +cmake --build --preset cl-debug --target morph_table_tests +ctest --test-dir build/cl-debug -R "" --output-on-failure +# timings only: +cmake --preset cl-release && cmake --build --preset cl-release --target morph_table_tests +build/cl-release/tests/morph_table_tests.exe "[.benchmark][]" +``` + +## Review Focus + +1. **An empty or repeating value set.** `oneOf: []` (a menu with nothing ticked) matches no row in `include` and rejects no row in `exclude`; `["alpha", "ALPHA"]` on a folded text column is one member, matches the same rows as `["alpha"]`, and counts as two toward `maxSetValues`. Test goes to Task 8a (`"table: an empty or repeating oneOf"`). +2. **A values-list search that is not text.** On a decimal column a search `"1.5"` finds `11.5` and `1.5` (substring of the value's text), an accented search `"É"` finds `"école"` and `"Ecole"` under the collator's fold, and an `offset` past the end returns no values while `distinct` still counts them. Test goes to Task 8a (`"distinct: search on numbers and accents, and an offset past the end"`). +3. **A group naming a column twice, `exactly 0`, and `together` over too many entries.** `columns: ["a", "a"]` is `InvalidSpec` (a matching that may use a column twice is not `Together`); `exactly 0` passes exactly the rows where no column satisfies; `together` with 4 entries over 3 columns is `InvalidSpec`. Test goes to Task 8b (`"groups: duplicate columns, exactly zero and too many together entries"`). +4. **Negative and zero amounts with units.** `-300 g` sorts before `-0.2 kg`; `0 g`, `0 kg` and a plain `0` in a mass-only column: the first two tie and are one distinct value, the third is `InvalidValue` as an operand; `-0.5 %` sorts in the ratio group after every mass in both directions. Test goes to Task 8c (`"measure: negative and zero amounts"`). +5. **A stored layout that repeats itself.** An `order` naming an id twice keeps its first place; a width of `0` or `-5` is dropped; `pinned: 40` over three visible columns is 3; a group listing a column twice keeps it once. Test goes to Task 8d (`"column layout: a stored layout that repeats itself"`). + +--- + +## Decisions + +- **`x-units` is not emitted.** A typed row's schema is `forms::schemaJson()`, built from the type alone, while the units are the application's run-time registry, and a client learns units "from the table's description … and from nowhere else". 8c therefore marks a `MeasureValue` property `x-measure` only, and the units reach a client in `TableDescription::units` (filled by `DescribeTable`). table.md ("Values with units") already says this; 8c Step 13 only checks it. Reading a document row's `{num, den, unit}` in `ValueRowsSource` is Task 11a's, and dropping a stored display unit that names a removed unit is Task 12c's (the index assigns both). + +- **`Together` with no include entry compiles.** An exclude-only group ("none of the companies is X") has no include entry and must not depend on its `mode`. 8b accepts 0, or 2 to k, include entries, as table.md's "Column groups" already states; 8b Step 13 only checks it. +- **A typed table's unit registry comes from its model.** `table::typed` returns rows only, so `detail::serve` asks the model for `tableUnits(TableContext const&)` (8c Step 8), as table.md's "Typed rows are a convenience" names it. + +## Order inside Part C + +As the index's cross-part decision 17 fixes, the order is **8a → 8b → 8d**, with 8c after 8b, before or after 8d: + +- 8a needs Task 3. +- **8b needs 8a**: its pooled values list extends `distinctValues`, and its `Together` value index reuses 8a's `ValueSet`. +- **8d needs 8b**: `ColumnLayoutValue::groups` is a `std::vector`, and 8b moves `ColumnGroupInfo` into `data_source.hpp`, which `engine.hpp` already includes. 8d never includes `description.hpp` from `engine.hpp`: `description.hpp` reaches `engine.hpp` through `query.hpp`, so that include would be a cycle. With 8b landed first, none remains. +- **8c needs Tasks 1, 2 and 5** (the generic page, the describe reply, the level cache) and 8b. + +8a, 8b and 8c all touch `filter.hpp`, `query.hpp` and `description.hpp` (the answer path); 8b and 8d both touch `engine.hpp`. They merge one at a time, each rebased on the last. + +**Headers.** `query.hpp` includes `engine.hpp`, never the reverse. A member of `Engine` whose signature or body needs a type of `query.hpp` (8a's `Engine::distinctValues`) is declared in `engine.hpp` over forward declarations and defined `inline` in `query.hpp`. + +**The server answer path** (index decisions 5 and 43). By the time Part C runs, `detail::answerQuery` validates the query itself and computes over a `LeveledSource` over a `detail::PinnedSource` (Tasks 2, 5, 6). Whatever a task of this part adds to `apply` it also adds to `answerQuery`, with a test that calls `answerQuery`: a test through `apply` alone does not show that a `Table.` request is served. + +## Interfaces consumed from other parts + +These are the names this part relies on. Where the roadmap does not pin a detail, the assumption is stated; the implementer checks it against the landed code first and adapts only the call, never the name another task produced. + +- **Task 3 (Part B):** `struct Unloaded {}` (a `Cell` alternative after `QuantityCell`); `CellState::Unloaded`; `enum class Match : std::uint8_t { No, Yes, Unknown }`; `static Match CompiledFilter::evaluate(Column const&, KeyColumn const&, std::uint32_t)`; `passes == (evaluate == Yes)`; `static Match CompiledFilter::evaluateGroup(Group const&, std::span keys, std::uint32_t row)` (keys by column index; the plain-group rule, which 8b replaces with quantifiers); `Match CompiledFilter::evaluateRow(std::span, std::uint32_t) const`; `FilterRun::take() &&` and `FilterRun::takeUndecided() &&`, whose group stage calls `evaluateGroup`; `PageRows::{TotalKind totalKind; std::int64_t undecided; …}`; `Engine::undecidedRowCount()`; `TableErrorCode::SourceContract` (appended last); `ColumnInfo::level` (a member after `format`). +- **Task 1 (Part A):** `TableDescription{…, groups, levels, units, …}`, `ColumnGroupInfo{id, label, columns}` with `operator== = default`, `GenericPage`, `writeGenericPage(PageRows const&, DataSource const&, std::span)`, `readGenericPage(std::string_view, TableDescription const&)`. Task 1 leaves `TableDescription::units` out; **8c adds it after `levels`**. `UnitInfo` does not exist before 8c. +- **Task 2 (Part A):** `ServedTable{description, source, levels, mayRead, scope, services, limits}`; `DescribeTable::invoke` returning `describe(served.description)`; `table::detail::answerQuery(ServedTable const&, TableQuery const&, AnswerContext const& = {})` (index decision 5). +- **Task 4 (Part B):** `TableQuery::keys` (`std::optional>`, after `columns`); `apply` = `validate` -> `detail::computeView` -> `detail::pageRows`. +- **Task 5 (Part B):** the spec's block verbatim: `CellLevelCache`, `LevelCacheOptions` (no `units` member; 8c adds it), `LevelCacheStats::{loaderCalls, invalidatedKeys}`, `LevelSource::snapshot()`, `LevelSnapshot::read`, `invalidateAll()`; `cellBytes(Cell const&)` in `data_source.hpp` (`sizeof(Cell)` for a `Measure`, which owns no heap). +- **Task 7 (Part B):** `Page::openMembers()` already returns `{"awaiting", "distinct"}`; 8a only adds the `distinct` member it names. +- **Task 0 (Part A):** `bench::WideTableSource`, `bench::WideTableOptions{rows, columns, seed, loadDelay}` in `tests/table/wide_table_model.{hpp,cpp}`. `bench::WideColumn{info, role, sparse, level, group}` from `WideTableSource::layout()`: `m000`...`m009` have role `Measure` and `ColumnKind::Decimal` until 8c; `t004`...`t006` carry `group = "g3"`, `t011`...`t026` `group = "g16"`. + +--- + +### Task 8a: `oneOf` and distinct values + +**Spec:** "Filters from the header" (the value-set operator; "Distinct values" with every bullet); "Unique values"; invariants 22, 23; Tests rows "`oneOf`", "Distinct values"; gates D3, D5, D6; timings D1–D4. + +**Files:** +- Modify: `include/morph/table/filter.hpp` (`FilterEntry::oneOf`, `CompiledFilter::Op::OneOf`, `ValueSet`, `FilterCounters`, `detail::readEntry`, `compileEntry`, `CompiledFilter::matches`) +- Modify: `include/morph/table/query.hpp` (`QueryLimits::{maxSetValues, maxQuerySetValues, maxQuerySetBytes}`, `DateBucket`, `DistinctRequest`, `DistinctValue`, `DistinctValues`, `detail::DistinctInput`, `detail::distinctOver`, `distinctValues`, the definition of `Engine::distinctValues`, `TableQuery::distinct`, `PageRows::distinct`, `Page::distinct`, `validate`, `apply`, `detail::entryTooLong`) +- Modify: `include/morph/table/engine.hpp` (forward declarations of `DistinctRequest` and `DistinctValues`; the declaration of `Engine::distinctValues`, no body) +- Modify: `include/morph/table/description.hpp` (`GenericPage::distinct`, its writer and reader; `detail::answerQuery`'s distinct branch) +- Create: `tests/table/test_table_distinct.cpp`; modify `tests/table/test_table_filter.cpp`, `tests/table/test_table_query.cpp`, `tests/table/bench_table.cpp`, `tests/CMakeLists.txt` (add `table/test_table_distinct.cpp` to `morph_table_tests`) + +**Interfaces:** +- Consumes: Task 3's `Match`, `CellState::Unloaded`, `CompiledFilter::evaluate`, `PageRows::undecided`; Task 1's `GenericPage`. +- Produces: + ```cpp + // filter.hpp + struct FilterEntry { /* existing members, then: */ std::optional> oneOf; }; + enum class CompiledFilter::Op : std::uint8_t { Eq, …, NotEmpty, OneOf }; // OneOf appended last + struct FilterCounters { std::uint64_t setLookups = 0; std::uint64_t cellReads = 0; std::uint64_t augmentations = 0; }; + class ValueSet; // the members of one oneOf, parsed for one column; one lookup per cell + // CompiledFilter::Entry gains: std::shared_ptr set; (set for OneOf only) + static Match CompiledFilter::evaluate(Column const&, KeyColumn const&, std::uint32_t row, FilterCounters* counters); + // query.hpp + enum class DateBucket : std::uint8_t { Value, Year, Month, Day }; // JSON "value", "year", "month", "day" + struct DistinctRequest { std::string column; std::string group; std::string search; + DateBucket bucket = DateBucket::Value; std::int64_t offset = 0; std::int64_t limit = 200; }; + struct DistinctValue { std::string text; std::string operand; std::int64_t count = 0; }; + struct DistinctValues { std::vector values; std::int64_t distinct = 0; + TotalKind distinctKind = TotalKind::Exact; std::int64_t blanks = 0; + std::int64_t invalid = 0; bool partial = false; }; + [[nodiscard]] std::expected + distinctValues(DataSource const& source, TableQuery const& query, DistinctRequest const& request, + ApplyOptions const& options = {}); + // TableQuery::distinct, PageRows::distinct, Page::distinct, GenericPage::distinct: + std::optional distinct; // on TableQuery + std::optional distinct; // on PageRows, Page, GenericPage + // query.hpp — the one core; the free function, the engine and answerQuery all call it + namespace detail { + struct DistinctInput { + std::shared_ptr snapshot; + std::span columns; + std::span const> keys; // by column index; null where not built + FilterSpec filters; // the request's own column entry already erased + Services services; // already forTask() + QueryLimits limits; + }; + // Builds the key columns `keys` lacks (the filter's and the request's), on the calling thread, into locals. + [[nodiscard]] std::expected distinctOver(DistinctInput const& input, + DistinctRequest const& validated); + } + // engine.hpp — declared over `struct DistinctRequest; struct DistinctValues;` forward declarations at + // namespace scope; a return type may be incomplete in a declaration. Defined `inline` in query.hpp, after + // distinctOver: engine.hpp cannot include query.hpp, which includes it. + [[nodiscard]] std::expected Engine::distinctValues(DistinctRequest const& request) const; + ``` + +- [ ] **Step 1: Write the failing `oneOf` tests** in `tests/table/test_table_filter.cpp`. Add helpers `oneOf(std::vector)` beside `eq(…)`, and, to the header comment's mutation list, "`ValueSet` matching nothing: `oneOf matches what its eq entries match` fails". + +```cpp +FilterEntry oneOf(std::vector v) { return FilterEntry{.oneOf = std::move(v)}; } + +TEST_CASE("table: oneOf matches what its eq entries match", "[table][filter]") { + Filtered const text{.source = tabletest::column(ColumnKind::Text, + {std::string{"Alpha"}, std::string{"beta"}, std::string{"Gamma"}, Cell{}, + std::string{"alpha"}}), + .services = {}}; + CHECK(text.by(on("c", {oneOf({"alpha", "BETA"})})) == Rows{0, 1, 4}); + CHECK(*text.by(on("c", {oneOf({"alpha", "BETA"})})) == *text.by(on("c", {eq("alpha"), eq("BETA")}))); + CHECK(text.by(on("c", {}, Combine::Any, {oneOf({"alpha", "BETA"})})) == Rows{2, 3}); + CHECK(text.by(on("c", {oneOf({"alpha", "BETA"}), isEmpty()})) == Rows{0, 1, 3, 4}); + FilterEntry exact = oneOf({"alpha"}); + exact.caseSensitive = true; + CHECK(text.by(on("c", {exact})) == Rows{4}); + + Filtered const ints{.source = tabletest::column(ColumnKind::Integer, + {std::int64_t{1}, std::int64_t{2}, std::int64_t{3}, std::string{"x"}}), + .services = {}}; + CHECK(ints.by(on("c", {oneOf({"2", "1.5"})})) == Rows{1}); + CHECK(ints.by(on("c", {oneOf({"2", "zz"})})).error().code == TableErrorCode::InvalidValue); +} + +TEST_CASE("table: oneOf is unknown on an unloaded cell", "[table][filter]") { + // slowColumn, not column: an unloaded cell in a filtered base-level column is SourceContract. + auto const source = tabletest::slowColumn(ColumnKind::Text, {std::string{"Alpha"}, Cell{Unloaded{}}, std::string{"b"}}); + auto const page = apply(*source, TableQuery{.sort = {}, .filters = on("c", {oneOf({"alpha"})}), .page = {}}); + REQUIRE(page); + CHECK(page->rows == std::vector{0}); + CHECK(page->undecided == 1); + CHECK(page->totalKind == TotalKind::AtLeast); +} + +TEST_CASE("table: an empty or repeating oneOf", "[table][filter]") { // Review Focus 1 + Filtered const text{.source = tabletest::column(ColumnKind::Text, + {std::string{"Alpha"}, std::string{"beta"}, Cell{}}), .services = {}}; + CHECK(text.by(on("c", {oneOf({})})) == Rows{}); + CHECK(text.by(on("c", {}, Combine::Any, {oneOf({})})) == Rows{0, 1, 2}); + CHECK(*text.by(on("c", {oneOf({"alpha", "ALPHA"})})) == *text.by(on("c", {oneOf({"alpha"})}))); +} + +TEST_CASE("table: a oneOf of any size is one lookup a cell", "[table][filter]") { // gate D5 + // 100,000 rows of "v"; a oneOf of the 10,000 texts "v0".."v9999". + // For every row r: CompiledFilter::evaluate(compiled.columns()[0], keys, r, &counters). + CHECK(counters.setLookups == 100'000); + CHECK(passed == 50'000); +} + +TEST_CASE("table: oneOf is the OR of its eq entries over random tables", "[table][filter]") { // invariant 23 + // std::mt19937 seed 23; 200 tables of 50 rows over kinds Text, Integer, Decimal, Date, Bool; + // cells drawn from 8 values plus empty and one invalid text; a oneOf of 1..6 drawn values. + CHECK(*f.by(on("c", {oneOf(values)})) == *f.by(on("c", eqEntries(values)))); // include, combine any + CHECK(*f.by(on("c", {}, Combine::Any, {oneOf(values)})) == + *f.by(on("c", {}, Combine::Any, eqEntries(values)))); // exclude +} +``` + +(`Filtered`, `on`, `eq`, `isEmpty` are the file's existing helpers; the D5 case builds key columns as `Filtered::by` does and keeps the pointers to call `evaluate` itself. `Filtered::by` returns `std::expected` and `TableError` has no `operator==`, so two results are compared as `*a == *b`; a result against a `Rows` literal compares directly. Every case below follows that rule.) + +- [ ] **Step 2: Write the failing limit tests** in `tests/table/test_table_query.cpp`: + +```cpp +TEST_CASE("table query: value sets are bounded per entry and per query", "[table][query]") { + // texts(n, bytes): n distinct strings of exactly `bytes` bytes. + auto const columns = std::vector{tabletest::col("a", ColumnKind::Text), tabletest::col("b", ColumnKind::Text), + tabletest::col("c", ColumnKind::Text)}; + auto query = [](std::vector>> sets) { /* one oneOf include per column */ }; + CHECK(validate(query({{"a", texts(10'000, 16)}}), columns)); + CHECK(validate(query({{"a", texts(10'001, 16)}}), columns).error().code == TableErrorCode::LimitExceeded); + CHECK(validate(query({{"a", texts(10'001, 16)}}), columns).error().column == "a"); + CHECK(validate(query({{"a", texts(10'000, 16)}, {"b", texts(10'000, 16)}}), columns)); + CHECK(validate(query({{"a", texts(10'000, 16)}, {"b", texts(10'000, 16)}, {"c", texts(1, 16)}}), columns) + .error().code == TableErrorCode::LimitExceeded); + CHECK(validate(query({{"a", texts(9'000, 120)}}), columns).error().code == TableErrorCode::LimitExceeded); // 1,080,000 B + CHECK(validate(query({{"a", texts(1, 257)}}), columns).error().code == TableErrorCode::LimitExceeded); // maxTextLength +} + +TEST_CASE("table query: a 10,000-value set fits the wire bound", "[table][query]") { // gate D6 + auto const q = /* one oneOf of 10,000 distinct 16-byte texts on column "a" */; + std::string json; + REQUIRE_FALSE(glz::write_json(q, json)); + CHECK(json.size() <= 250'000); + CHECK(json.size() < QueryLimits{}.maxQuerySetBytes); + CHECK(validate(q, columns)); +} +``` + +- [ ] **Step 3: Write the failing distinct-value tests** in `tests/table/test_table_distinct.cpp`. Header comment lists the mutations: "counting over the view (the column's own filter kept): `counts are those of the rows the other filters leave` fails"; "grouping text by raw text instead of its fold: `values are grouped by the key` fails". The shared source: + +```cpp +// status (Text), city (Text), qty (Integer); keys 0..5 +// 0: "open", "Berlin", 1 +// 1: "Open", "Paris", 2 +// 2: "closed", "Berlin", 3 +// 3: empty, "Berlin", 4 +// 4: "open", "Paris", "x" (invalid integer) +// 5: "hold", "Rome", 5 + +TEST_CASE("distinct: counts are those of the rows the other filters leave", "[table][distinct]") { + TableQuery q; + q.filters.columns["city"] = ColumnFilter{.combine = Combine::Any, .include = {oneOf({"Berlin", "Paris"})}, .exclude = {}}; + q.filters.columns["status"] = ColumnFilter{.combine = Combine::Any, .include = {eq("closed")}, .exclude = {}}; + auto const d = distinctValues(*source, q, DistinctRequest{.column = "status"}); + REQUIRE(d); + REQUIRE(d->values.size() == 2); + CHECK(d->values[0].text == "closed"); CHECK(d->values[0].operand == "closed"); CHECK(d->values[0].count == 1); + CHECK(d->values[1].text == "open"); CHECK(d->values[1].operand == "open"); CHECK(d->values[1].count == 3); + CHECK(d->distinct == 2); CHECK(d->distinctKind == TotalKind::Exact); + CHECK(d->blanks == 1); CHECK(d->invalid == 0); CHECK_FALSE(d->partial); + // invariant 22: the sum is the row count of the other filters + CHECK(1 + 3 + d->blanks + d->invalid == 5); +} + +TEST_CASE("distinct: invalid cells are counted and listed under no value", "[table][distinct]") { + TableQuery q; + q.filters.columns["city"] = ColumnFilter{.combine = Combine::Any, .include = {eq("Paris")}, .exclude = {}}; + auto const d = distinctValues(*source, q, DistinctRequest{.column = "qty"}); + REQUIRE(d); + REQUIRE(d->values.size() == 1); + CHECK(d->values[0].text == "2"); CHECK(d->values[0].operand == "2"); CHECK(d->values[0].count == 1); + CHECK(d->invalid == 1); +} + +TEST_CASE("distinct: an unloaded cell or an undecided row sets partial", "[table][distinct]") { + // Both under the first case's query `q` (city oneOf Berlin, Paris; status eq closed), which drops row 5, so + // the values are closed, open. The same source with row 0's status Unloaded{}, then (second source) row 1's + // city Unloaded{}. + // Mutation: distinctOver counting an Unknown row as a candidate — the second count is 3 and partial is false. + CHECK(withUnloadedStatus->partial); CHECK(withUnloadedStatus->values[1].count == 2); // "open": rows 1, 4 + CHECK(withUndecidedRow->partial); CHECK(withUndecidedRow->values[1].count == 2); // row 1 undecided by city +} + +TEST_CASE("distinct: search, paging and the cap", "[table][distinct]") { + CHECK(names(distinctValues(*source, {}, {.column = "status", .search = "OP"})) == std::vector{"open"}); + auto const page = distinctValues(*source, {}, {.column = "status", .offset = 1, .limit = 1}); + CHECK(names(page) == std::vector{"hold"}); // ascending: closed, hold, open + CHECK(page->distinct == 3); + ApplyOptions capped; + capped.limits.totalCap = 2; + auto const atCap = distinctValues(*source, {}, {.column = "status"}, capped); + CHECK(atCap->distinct == 2); CHECK(atCap->distinctKind == TotalKind::AtLeast); CHECK(atCap->values.size() == 3); + ApplyOptions small; + small.limits.maxLimit = 2; + CHECK(distinctValues(*source, {}, {.column = "status", .limit = 500}, small)->values.size() == 2); +} + +TEST_CASE("distinct: search on numbers and accents, and an offset past the end", "[table][distinct]") { // Review Focus 2 + // decimal column [11.5, 1.5, 2]; text column ["école", "Ecole", "x"] with tabletest's accent-folding collator + CHECK(names(distinctValues(*decimals, {}, {.column = "c", .search = "1.5"})) == std::vector{"1.5", "11.5"}); + CHECK(names(distinctValues(*texts, {}, {.column = "c", .search = "É"}, foldingOptions)).size() == 1); // one folded value + auto const past = distinctValues(*decimals, {}, {.column = "c", .offset = 10}); + CHECK(past->values.empty()); CHECK(past->distinct == 3); +} + +TEST_CASE("distinct: dates by year, month and day", "[table][distinct]") { + // Date column (days) for 2025-12-31, 2026-01-15, 2026-01-20, 2026-02-01 + auto const years = distinctValues(*dates, {}, {.column = "d", .bucket = DateBucket::Year}); + CHECK(years->values[0].text == "2025"); CHECK(years->values[0].operand == "2025-01-01..2025-12-31"); CHECK(years->values[0].count == 1); + CHECK(years->values[1].text == "2026"); CHECK(years->values[1].operand == "2026-01-01..2026-12-31"); CHECK(years->values[1].count == 3); + auto const months = distinctValues(*dates, {}, {.column = "d", .bucket = DateBucket::Month}); + CHECK(names(months) == std::vector{"2025-12", "2026-01", "2026-02"}); + CHECK(months->values[1].operand == "2026-01-01..2026-01-31"); CHECK(months->values[1].count == 2); + auto const days = distinctValues(*dates, {}, {.column = "d", .bucket = DateBucket::Day}); + CHECK(days->values[1].text == "2026-01-15"); CHECK(days->values[1].operand == "2026-01-15..2026-01-15"); + // A DateTime column: Day bucket of 2026-01-15T10:00:00Z has operand "2026-01-15T00:00:00Z..2026-01-15T23:59:59Z". + CHECK(distinctValues(*source, {}, {.column = "status", .bucket = DateBucket::Year}).error().code == TableErrorCode::InvalidSpec); +} + +TEST_CASE("distinct: requests are validated as queries are", "[table][distinct]") { + CHECK(distinctValues(*source, {}, {.column = "status", .group = "g"}).error().code == TableErrorCode::InvalidSpec); + CHECK(distinctValues(*source, {}, {}).error().code == TableErrorCode::InvalidSpec); + CHECK(distinctValues(*source, {}, {.column = "nope"}).error().code == TableErrorCode::UnknownColumn); + ApplyOptions hidden; + hidden.mayRead = [](std::string_view id) { return id != "status"; }; + CHECK(distinctValues(*source, {}, {.column = "status"}, hidden).error().code == TableErrorCode::ColumnNotReadable); + CHECK(distinctValues(*source, {}, {.column = "status", .search = std::string(257, 'a')}).error().code == TableErrorCode::LimitExceeded); + CHECK(distinctValues(*source, {}, {.column = "status", .offset = 10'000'001}).error().code == TableErrorCode::LimitExceeded); + CHECK(distinctValues(*source, {}, {.column = "status", .offset = -1}).error().code == TableErrorCode::LimitExceeded); + TableQuery keyed; + keyed.keys = std::vector{std::int64_t{1}}; + keyed.distinct = DistinctRequest{.column = "status"}; + CHECK(validate(keyed, source->columns()).error().code == TableErrorCode::InvalidSpec); +} + +TEST_CASE("distinct: the column's level is an order level of the request", "[table][distinct]") { + // the shared source with status declared at level "slow" (tabletest::col then .level = "slow") + TableQuery q; + q.distinct = DistinctRequest{.column = "status"}; + q.columns = std::vector{"city"}; + auto const needed = levelsNeeded(q, source->columns(), {}); + CHECK(needed.order == std::vector{"slow"}); // Mutation: levelsNeeded ignoring query.distinct +} + +TEST_CASE("distinct: server mode answers through apply, client mode through the engine", "[table][distinct]") { + TableQuery q; // the city filter of the first case + q.distinct = DistinctRequest{.column = "status"}; + auto const page = apply(*source, q); + REQUIRE(page); + CHECK(page->rows.empty()); + REQUIRE(page->distinct); + CHECK(*page->distinct == *distinctValues(*source, q, *q.distinct)); // DistinctValues and DistinctValue are ==-comparable + Engine engine{source}; + REQUIRE(engine.setFilter(q.filters)); + CHECK(*engine.distinctValues(*q.distinct) == *distinctValues(*source, q, *q.distinct)); +} + +TEST_CASE("distinct: invariant 22 over random tables", "[table][distinct]") { + // std::mt19937 seed 22; 100 tables of 300 rows, columns c0 (Text), c1 (Integer), c2 (Text); + // random filters on all three; for column c0 with partial == false: + CHECK(sumOfCounts + d->blanks + d->invalid == *apply(*source, queryWithoutC0Filter)->total); +} +``` + +Also in `test_table_description.cpp`: `"generic page: a distinct reply round-trips"` — a `GenericPage` with no rows and `distinct` holding the first case's values reads back equal. Mutation: the writer leaving `distinct` out. + +And, in the same file, the answer path (a `ServedTable` over the shared source above, built as that file's other `answerQuery` cases build theirs): + +```cpp +TEST_CASE("answer query: a distinct request answers values and no rows", "[table][description][distinct]") { + // served: description of status, city, qty; source the shared source; q = the first distinct case's query + // with q.distinct = DistinctRequest{.column = "status"}. + auto const page = detail::answerQuery(served, q); + REQUIRE(page); + CHECK(page->rows.empty()); + CHECK(page->keys.empty()); + REQUIRE(page->distinct); + CHECK(*page->distinct == *distinctValues(*source, q, *q.distinct)); + // Mutation: answerQuery ignoring query.distinct — `apply` answers the distinct request, but `writeGenericPage` + // does not copy `distinct` (a distinct reply is built by answerQuery), so `distinct` is absent. + + auto refusing = served; + refusing.description.capabilities.distinct = false; + CHECK(detail::answerQuery(refusing, q).error().code == TableErrorCode::Unavailable); + // Mutation: the branch not reading capabilities.distinct. +} + +TEST_CASE("answer query: a distinct request reads a slow column through its level", "[table][description][distinct]") { + // status declared at level "slow", served by a CellLevelCache (built as Task 5's answerQuery cases build theirs) + // holding nothing: the reply is partial, lists no value, and the cache was asked for every row's key as an + // Order use. After the load is run, the same request equals distinctValues over the plain source. + CHECK(first->distinct->partial); + CHECK(first->distinct->values.empty()); + CHECK(wantedKeys == allSixKeys); // LevelUse::Order + CHECK(*second->distinct == *distinctValues(*plainSource, q, *q.distinct)); + // Mutation: the branch running distinctValues over served.source instead of the LeveledSource — the + // second reply is still partial and empty. +} +``` + +- [ ] **Step 4: Run the new cases; they fail to compile** (`oneOf`, `distinctValues`, `DistinctRequest` undeclared). + +Run: `cmake --build --preset cl-debug --target morph_table_tests` +Expected: compile errors naming `oneOf` and `distinctValues`. + +- [ ] **Step 5: Implement the value-set operator** in `filter.hpp`: + - `FilterEntry::oneOf` per the Interfaces block, Doxygen as the spec's block ("Matches a cell whose value equals any of these. Each is parsed for the column's kind, as `eq`'s operand is."). + - `readEntry` counts `oneOf` as one operator (`Op::OneOf`); `operatorDefined(kind, OneOf)` is `operatorDefined(kind, Eq)`. + - `class ValueSet` holds the parsed members for one column kind: `std::unordered_set` (Date, DateTime, Bool), `std::unordered_set` (Integer, Key, Decimal, Quantity; hash of the canonical `numerator`/`denominator`), `std::unordered_set` (Number), and a transparent-hash `std::unordered_set` of folded texts, or raw texts when `caseSensitive` (Text). Public: `[[nodiscard]] bool contains(KeyColumn const& keys, std::uint32_t row, FilterCounters* counters) const` (one probe; increments `counters->setLookups` when non-null) and `[[nodiscard]] std::size_t size() const noexcept`. Members are parsed by the existing `parseOperand`; one that does not parse is `InvalidValue` naming the column, as `eq` is. An Integer/Key column drops a member that is not a whole number at compile time (it can never match, as `eq "1.5"` cannot). + - `matches` for `OneOf`: `Unloaded` → handled by Task 3's `evaluate` (`Unknown`); `Empty`/`Invalid` → `false`; `Valid` → `entry.set->contains(…)`. + - The existing `evaluate(Column const&, KeyColumn const&, std::uint32_t)` gains a trailing `FilterCounters* counters = nullptr`, passed down to `matches`. + +- [ ] **Step 6: Implement the limits** in `query.hpp`: `QueryLimits::maxSetValues = 10'000`, `maxQuerySetValues = 20'000`, `maxQuerySetBytes = std::size_t{1} << 20U`. `detail::entryTooLong` checks every `oneOf` member against `maxTextLength`. `detail::checkFilters` sums, over every `oneOf` of `include` and `exclude` of every column and group, the member count and the members' byte sizes; one entry over `maxSetValues` is `LimitExceeded` naming its column (a group's: empty), the sums over `maxQuerySetValues` or `maxQuerySetBytes` are `LimitExceeded` with an empty column. + +- [ ] **Step 7: Implement distinct values** in `query.hpp` (`DateBucket` and its `glz::meta` "value", "year", "month", "day"; the three structs with `operator== = default`; `TableQuery::distinct`, `PageRows::distinct`, `Page::distinct`). `distinctValues` follows the spec's bullets; the choices they leave open: + - **Validation** (also run by `validate` on `query.distinct`): exactly one of `column`, `group` is non-empty, else `InvalidSpec`; `group` non-empty is `Unavailable` ("pooled values need column groups") until Task 8b; the column passes `detail::checkColumn`; `search.size() > maxTextLength`, `offset < 0`, `offset > maxOffset`, `limit < 0` are `LimitExceeded`; `limit` is clamped to `maxLimit`; a `bucket` other than `Value` on a kind other than `Date`/`DateTime` is `InvalidSpec`; a `Custom` column is `UnsupportedOperator` (it has no values to tick); `query.keys` and `query.distinct` both set is `InvalidSpec`. + - **Rows:** compile `query.filters` with `filters.columns[request.column]` erased; run it as `apply` does (a `FilterRun` over every source row). `Yes` rows are candidates; any `Unknown` row sets `partial`. + - **Grouping key:** the column's `KeyColumn` (built for the column alone): Text by `folded`, the exact/int/real key otherwise; a bucket groups `Date` days or `DateTime` seconds (UTC) by the bucket's start. `Empty` → `blanks`, `Invalid` → `invalid`, `Unloaded` → `partial`, not counted. + - **A value's `text` and `operand`:** from its first candidate row in source order. Text: the raw text (both). Integer/Key/Decimal/Quantity: `units::detail::formatRationalDecimal` of the key (both). Number: `std::format("{}", key)` (both). Bool: `"true"`/`"false"`. Date `Value`: the cell's own string when the source gave text, else ISO `YYYY-MM-DD` (both). DateTime `Value`: the cell's own string, else `YYYY-MM-DDTHH:MM:SSZ`. Buckets: `text` is `YYYY`, `YYYY-MM` or `YYYY-MM-DD`; `operand` is the bucket's first and last instant joined by `..` (`2026-01-01..2026-01-31`; DateTime ends `T00:00:00Z` and `T23:59:59Z`), which the menu splits into a `between`. + - **Search:** `collator.fold(search)` is a substring of the value's folded `text`, folded once per distinct value, never per row. + - **Order and paging:** values sort by `compareKeys` (ascending) on their first rows, ties by first row; `distinct` is the count after search, reported as `min(count, totalCap)` with `AtLeast` when `count > totalCap`; then `offset`/`limit` slice `values`. + - `levelsNeeded` (Task 3) adds, when `query.distinct` names a `column`, that column's level to `order`: the values list reads it for every candidate row. + - **One core.** `detail::distinctOver(input, validated)` does the rows, grouping, text, search, order and paging above over a snapshot and the key columns it is handed, building the ones it lacks into locals. `distinctValues(source, query, request, options)` validates, erases the column's own entry, and calls it with `source.snapshot()`, no keys, and `options.services.forTask()`. + - `apply` with `query.distinct` set returns `PageRows{.rows = {}, .distinct = distinctValues(…)}` (same options). The typed `apply` copies `distinct` into `Page`. `Page::openMembers()` already names `"distinct"` (Task 7). + - **`detail::answerQuery`** (Tasks 2, 5, 6) branches on `query.distinct` right after its own `validate`, before the view cache is asked (a distinct reply is not a view and is not cached there): + 1. `served.description.capabilities.distinct == false` → `TableError{Unavailable, {}, "this table answers no distinct request"}`, as Task 4 refuses a keyed query; + 2. `levelsNeeded` (which now holds the column's level in `order`), one snapshot per needed level, and the `LeveledSource` over the pinned source, exactly as the page path builds them; + 3. `distinctValues` over that `LeveledSource` with `ApplyOptions{served.limits, served.services, served.mayRead}`; + 4. `want` for each `order` level with every source row's key as `LevelUse::Order` and `retry = query.retry` (the values list reads the column for every candidate); an `Unavailable` from that want refuses the request as it refuses a page; + 5. the reply is a `GenericPage` with `revision` set, `columns`, `keys` and `rows` empty, and `distinct` set. + - `GenericPage::distinct` is written and read as the JSON member `"distinct"` with glaze's default shape of `DistinctValues`. + +- [ ] **Step 8: Implement `Engine::distinctValues(request) const`.** In `engine.hpp`: `struct DistinctRequest; struct DistinctValues;` before `class Engine`, and the member's declaration with its Doxygen, no body. In `query.hpp`, after `detail::distinctOver`: `inline std::expected Engine::distinctValues(DistinctRequest const& request) const`, which validates the request as above with default `QueryLimits` and no `mayRead`, and calls `distinctOver` with `_snapshot`, `_columns`, the engine's `filter()` spec with the column's entry erased, `_options.services.forTask()`, and `_keys` when `_keysSnapshot == _snapshot` (an empty span otherwise). A key column the engine does not hold is built by `distinctOver` on the calling thread and not stored. Test, in `test_table_distinct.cpp`: `"distinct: the engine reuses the keys it holds"` — an engine sorted by `status` (`stats().keyBuilds == 1`), then `distinctValues({.column = "status"})`: the result equals the free function's and `stats().keyBuilds` is still 1. Mutation: the member passing an empty key span — the result is the same, so the case also counts `KeyColumn` builds through a counting `TextCollator` (`fold` calls unchanged by the second call). + +- [ ] **Step 9: Run the new cases and the target** + +Run: `ctest --test-dir build/cl-debug -R "oneOf|distinct|value sets|wire bound" --output-on-failure`, then `ctest --test-dir build/cl-debug -R "table" --output-on-failure` +Expected: all pass. + +- [ ] **Step 10: Mutations.** (a) `ValueSet::contains` returning `false`: `"table: oneOf matches what its eq entries match"` fails. (b) `distinctValues` keeping the column's own filter: `"distinct: counts are those of the rows the other filters leave"` fails (`closed` missing). (c) grouping text by `raw` instead of `folded`: the same case fails (`open` count 2, an `Open` value appears). (d) `answerQuery` ignoring `query.distinct`: `"answer query: a distinct request answers values and no rows"` fails. (e) its branch reading `served.source` instead of the `LeveledSource`: `"answer query: a distinct request reads a slow column through its level"` fails. (f) `Engine::distinctValues` passing no keys: `"distinct: the engine reuses the keys it holds"` fails on the fold count. Paste each failing line into the commit body; revert. + +- [ ] **Step 11: Timings D1–D4.** Add `TEST_CASE("table benchmark: distinct values and value sets", "[.benchmark][table][distinct]")` to `bench_table.cpp`, generated with `std::mt19937{7}`: 100,000 rows, a text column of 50,000 distinct values; D1 first 200 with keys built; D2 with search `"abc"`; D3 with filters on two other columns, one of them `Unloaded` in 30% of rows — the case asserts `partial` before printing; D4 compile a 10,000-value `oneOf` and filter the 100,000 rows. Run on `cl-release` (command in Global Constraints) and write the medians and spreads into table.md "Benchmarks: configuring" rows D1–D4 (replacing "(P)" budgets by the recorded baseline plus its spread, as the Performance section says). + +- [ ] **Step 12: Docs build** (new public symbols) — command in Global Constraints; expected: exits 0. + +- [ ] **Step 13: Commit** `feat(table): value sets and distinct values` (body: the six mutations' failing lines). + +--- + +### Task 8b: Column groups with quantifiers + +**Spec:** "Column groups" (declaring, the filter, the truth tables, deciding `Together`, unloaded cells, the menu's pooled values list); "Unloaded cells in filters" (group rule); invariant 24 and invariant 1 for groups; Tests row "Column groups"; Tests row "Distinct values" (a group's "(Blanks)"); gates G5, G7; timings G1–G4, G6, G7; Neighbouring specs row `../forms/views.md` (`x-column-group`, step 3). + +**Files:** +- Modify: `include/morph/table/data_source.hpp` (`ColumnGroupInfo` moved here, `DataSource::groups()`, `VectorSource::setGroups`, `detail::checkGroups`) +- Modify: `include/morph/table/filter.hpp` (`GroupMode`, `ColumnCount`, `GroupFilter::{group, mode, match, exclude}`, `CompiledFilter::Group`, `compileGroup`, `compileFilter`'s groups parameter, `CompiledFilter::evaluateGroup` with quantifiers and counters, glaze metas) +- Modify: `include/morph/table/query.hpp` (`checkFilters` for groups, `validate`'s `groups` parameter, `computeView` and `apply` passing `source.groups()`, pooled `distinctValues`, `RowsSource::groups()` from `Row::columnGroups()`) +- Modify: `include/morph/table/engine.hpp` (`compile` passing `_source->groups()`; `fitToColumns` keeping a declared group's filter) +- Modify: `include/morph/table/description.hpp` (remove `ColumnGroupInfo`'s definition; it now comes from `data_source.hpp`; `detail::PinnedSource::groups()` and the scoped source's `groups()`; `detail::answerQuery` passing groups; `typed` copying the source's groups into the description) +- Modify: `include/morph/table/level_cache.hpp` (`LeveledSource::groups()` forwarding its base's) +- Docs: `docs/spec/table/table.md` ("Column groups": the `Together` sentence is already there; Step 13 checks it) +- Modify: `include/morph/forms/forms.hpp` (`mergeSchemaExtras` writes `x-column-group`), `include/morph/forms/views.hpp` (`deriveColumns` copies `x-column-group`) +- Modify: `tests/table/wide_table_model.{hpp,cpp}` (declared groups `g3`, `g16`) +- Test: `tests/table/test_table_filter.cpp`, `tests/table/test_table_distinct.cpp`, `tests/table/test_table_columns.cpp`, `tests/table/bench_table.cpp` +- Docs: `docs/spec/forms/views.md` (`x-column-group` on a schema property, copied into the `v-columns` entry) + +**Interfaces:** +- Consumes: 8a's `ValueSet`, `FilterCounters`, `distinctValues`; Task 3's `Match`, `evaluate(Column const&, …)`. +- Produces: + ```cpp + // data_source.hpp (ColumnGroupInfo as Task 1 defined it: id, label, columns) + [[nodiscard]] virtual std::span DataSource::groups() const { return {}; } + void VectorSource::setGroups(std::vector groups); + [[nodiscard]] std::span VectorSource::groups() const override; // what setGroups stored + // filter.hpp + enum class GroupMode : std::uint8_t { Columns, Together }; // JSON "columns", "together" + struct ColumnCount { enum class Kind : std::uint8_t { Any, All, AtLeast, Exactly } kind = Kind::Any; std::int64_t n = 1; }; + struct GroupFilter { std::string group; std::vector columns; GroupMode mode = GroupMode::Columns; + ColumnCount match; Combine combine = Combine::Any; + std::vector include; std::vector exclude; }; + [[nodiscard]] std::expected + compileFilter(FilterSpec const& spec, std::span columns, Services const& services, + std::span groups = {}); // and compileFilterGuarded likewise + static Match CompiledFilter::evaluateGroup(Group const& group, std::span keys, + std::uint32_t row, FilterCounters* counters = nullptr); // Task 3's, extended + ``` + `ColumnCount` JSON is `"any"`, `"all"`, `{"atLeast": n}` or `{"exactly": n}` (custom glaze read/write). + + Index decision 38: `FilterEntry`, `ColumnFilter`, `GroupFilter` and `ColumnCount` each declare `[[nodiscard]] bool operator==(T const&) const = default;` in this task (`FilterSpec` too, so a held filter compares). Test `"filters compare by value"` in `test_table_filter.cpp`: two `FilterSpec`s built alike are equal, and differ after one changes a `oneOf` member, a `match.n`, or a `mode`; mutation: `ColumnCount::operator==` comparing `kind` only. + + Index decision 43, the groups of a table on the server: + ```cpp + // query.hpp — a typed row's declared groups; the label is the id here (query.hpp does not include forms.hpp), + // and table::typed writes forms' inferTitle(id) into the description's copy, as it labels a column + [[nodiscard]] std::span RowsSource::groups() const override; // {} when Row has no columnGroups() + [[nodiscard]] std::expected + validate(TableQuery query, std::span columns, QueryLimits const& limits = {}, + std::function const& mayRead = {}, std::span groups = {}); + // description.hpp, level_cache.hpp — each forwards the source it wraps + [[nodiscard]] std::span detail::PinnedSource::groups() const override; // a copy taken when pinned + [[nodiscard]] std::span LeveledSource::groups() const override; // _base->groups() + // the source table::scoped returns: the shared source's groups() + ``` + A table's groups are its `DataSource::groups()`. A model that serves a description over a `VectorSource` calls `setGroups` with the description's `groups`; `table::typed` fills `description.groups` from its `RowsSource::groups()`, with each label replaced by `inferTitle(id)`. The server evaluates the source's groups and never the description's: the description's `groups` is what a client draws, and a model that writes it by hand builds it from `source->groups()` (as Step 9 has `bench::WideTableModel` do), so the two name the same groups and columns. + +- [ ] **Step 1: Write the failing truth-table test** in `test_table_filter.cpp`. + - Change the existing helper `Filtered::by` to compile with the source's declared groups: `compileFilter(spec, source->columns(), services, source->groups())`. Without it every `.group = "company"` case below is `UnknownColumn`, because the group is resolved only through the span `compileFilter` is given. The existing cases name no declared group and are unchanged by it. + - The truth-table source (`Filtered f`, its `VectorSource` with `setGroups` declaring `company`) and `by(GroupFilter) -> std::expected` (`f.by` of a spec holding that one group) are file-scope helpers, used by every `[groups]` case below. + - Helper `Match groupMatch(VectorSource const&, GroupFilter, std::uint32_t row)` compiles `FilterSpec{.groups = {g}}` with `source.groups()`, builds the key columns as `Filtered::by` does, and returns `CompiledFilter::evaluateGroup(compiled->groups()[0], pointers, row)`. + - Header mutation lines: "`Together` evaluated as `atLeast` with n = entries: the truth-table case fails on row F, F, X"; "`Filtered::by` compiling without `source->groups()`: every declared-group case fails with `UnknownColumn`". + +```cpp +// companyA, companyB, companyC (Text), declared group {"company", "Company", {companyA, companyB, companyC}} +// 0: F, S, X 1: F, F, X 2: S, F, F 3: F, X, Y 4: X, Y, Z +TEST_CASE("groups: the spec's truth table", "[table][filter][groups]") { + CHECK(by({.group = "company", .include = {eq("F")}}) == Rows{0, 1, 2, 3}); + CHECK(by({.group = "company", .mode = GroupMode::Together, .include = {eq("F"), eq("S")}}) == Rows{0, 2}); + CHECK(by({.group = "company", .include = {oneOf({"F", "S", "T"})}}) == Rows{0, 1, 2, 3}); + CHECK(by({.group = "company", .match = {.kind = ColumnCount::Kind::AtLeast, .n = 2}, .include = {oneOf({"F", "S"})}}) == Rows{0, 1, 2}); + CHECK(by({.group = "company", .match = {.kind = ColumnCount::Kind::Exactly, .n = 1}, .include = {eq("F")}}) == Rows{0, 3}); + CHECK(by({.group = "company", .match = {.kind = ColumnCount::Kind::All, .n = 1}, .include = {oneOf({"F", "S"})}}) == Rows{2}); + CHECK(*by({.columns = {"companyA", "companyB", "companyC"}, .include = {eq("F")}}) == + *by({.group = "company", .include = {eq("F")}})); // the plain group is `any` + CHECK(by({.group = "company", .include = {}, .exclude = {eq("X")}}) == Rows{2}); // "none of the companies is X" + std::vector seventeen; // only the 17th entry can match + for (int i = 1; i <= 16; ++i) seventeen.push_back(eq("A" + std::to_string(i))); + seventeen.push_back(eq("F")); + CHECK(by({.group = "company", .include = seventeen}) == Rows{0, 1, 2, 3}); // Mutation: a 16-bit entry mask + // dates: "two of the three are after 2026-05-01" over three Date columns is atLeast 2 with a gt entry +} + +TEST_CASE("groups: three-valued over unloaded cells", "[table][filter][groups]") { + // Rows of three Text cells, U = Cell{Unloaded{}}; each CHECK is groupMatch(source, filter, row) == expected. + struct Case { GroupFilter filter; std::array cells; Match expected; }; + // AtLeast 2, eq F: {F,F,U} Yes {X,X,U} No {F,X,U} Unknown + // Any, eq F: {F,U,U} Yes {X,X,U} Unknown {X,X,X} No + // All, eq F: {F,F,U} Unknown {F,X,U} No + // Exactly 1, eq F: {F,F,U} No {F,X,U} Unknown {X,X,U} Unknown {F,X,X} Yes {X,X,X} No + // Together F,S: {F,S,U} Yes {F,F,U} Unknown {U,U,X} Unknown {X,X,U} No + // include {}, exclude eq X: {F,X,U} No {F,S,U} Unknown {F,S,F} Yes + // isEmpty, Any: {X,X,U} Unknown (an unloaded cell is not empty) +} + +TEST_CASE("groups: duplicate columns, exactly zero and too many together entries", "[table][filter][groups]") { // Review Focus 3 + CHECK(f.by(FilterSpec{.columns = {}, .groups = {{.columns = {"companyA", "companyA"}, .include = {eq("F")}}}}) + .error().code == TableErrorCode::InvalidSpec); + CHECK(by({.group = "company", .match = {.kind = ColumnCount::Kind::Exactly, .n = 0}, .include = {eq("F")}}) == Rows{4}); + CHECK(f.by(FilterSpec{.columns = {}, .groups = {{.group = "company", .mode = GroupMode::Together, + .include = {eq("A"), eq("B"), eq("C"), eq("D")}}}}) + .error().code == TableErrorCode::InvalidSpec); + CHECK(f.by(FilterSpec{.columns = {}, .groups = {{.group = "company", .mode = GroupMode::Together, .include = {eq("A")}}}}) + .error().code == TableErrorCode::InvalidSpec); // one entry: neither 0 nor 2..k + // Together takes 0, or 2 to k, include entries: an exclude-only group compiles in either mode. + // Mutation: compileGroup requiring 2..k include entries in Together mode with no exception for 0. + CHECK(by({.group = "company", .mode = GroupMode::Together, .include = {}, .exclude = {eq("X")}}) == Rows{2}); + CHECK(*by({.group = "company", .mode = GroupMode::Together, .include = {}, .exclude = {eq("X")}}) == + *by({.group = "company", .include = {}, .exclude = {eq("X")}})); + CHECK(by({.group = "company", .mode = GroupMode::Together, .include = {}, .exclude = {}}) == Rows{0, 1, 2, 3, 4}); + CHECK(f.by(FilterSpec{.columns = {}, .groups = {{.group = "company", .match = {.kind = ColumnCount::Kind::AtLeast, .n = 4}, + .include = {eq("F")}}}}).error().code == TableErrorCode::InvalidSpec); + CHECK(f.by(FilterSpec{.columns = {}, .groups = {{.group = "company", .columns = {"companyA", "companyB"}, + .include = {eq("F")}}}}).error().code == TableErrorCode::InvalidSpec); + CHECK(f.by(FilterSpec{.columns = {}, .groups = {{.group = "nope", .include = {eq("F")}}}}).error().code == + TableErrorCode::UnknownColumn); +} + +TEST_CASE("groups: more than 32 entries on a side is refused where the filter compiles", "[table][filter][groups]") { + // Engine::setFilter compiles without validate's QueryLimits, so the bound that keeps every entry a bit of a + // std::uint32_t mask is compileGroup's own. 33 include entries, only the 33rd ("F") able to match. + std::vector thirtyThree; + for (int i = 1; i <= 32; ++i) thirtyThree.push_back(eq("A" + std::to_string(i))); + thirtyThree.push_back(eq("F")); + std::vector thirtyTwo(thirtyThree.end() - 32, thirtyThree.end()); // "A2".."A32", "F" + CHECK(by({.group = "company", .include = thirtyThree}).error().code == TableErrorCode::LimitExceeded); + CHECK(by({.group = "company", .include = {eq("F")}, .exclude = thirtyThree}).error().code == + TableErrorCode::LimitExceeded); + CHECK(by({.group = "company", .include = thirtyTwo}) == Rows{0, 1, 2, 3}); // 32 a side compiles + CHECK(by({.group = "company", .include = thirtyTwo, .exclude = {eq("X")}}) == Rows{2}); + Engine engine{f.source}; + FilterSpec over; + over.groups.push_back({.group = "company", .include = thirtyThree}); + CHECK(engine.setFilter(over).error().code == TableErrorCode::LimitExceeded); + CHECK(engine.filter().empty()); // the filter is unchanged + // Mutation: compileGroup without its 32-a-side bound — the first CHECK gets rows (and a shift by 32), not + // LimitExceeded. validate still refuses include + exclude over maxEntries (Step 5); that is a query's bound. +} + +TEST_CASE("groups: a declared group is checked where the columns are read", "[table][filter][groups]") { + // setGroups with: one column; 17 columns; mixed kinds (Text + Integer); a column in two groups. + // apply(*source, {}) on each is TableErrorCode::SourceContract; a well-formed declaration applies. +} + +TEST_CASE("groups: the JSON shape reads and writes", "[table][filter][groups]") { + auto const json = R"({"group":"company","mode":"together","match":{"atLeast":2},"combine":"all","include":[{"eq":"F"},{"eq":"S"}],"exclude":[{"eq":"X"}]})"; + GroupFilter g; + REQUIRE_FALSE(glz::read_json(g, std::string{json})); + CHECK(g.mode == GroupMode::Together); CHECK(g.match.kind == ColumnCount::Kind::AtLeast); CHECK(g.match.n == 2); + for (auto const* m : {R"("any")", R"("all")", R"({"atLeast":3})", R"({"exactly":0})"}) { /* read then write gives m back */ } +} + +// Generators shared by the two property cases (file scope in test_table_filter.cpp): +// Cell randomCell(std::mt19937& rng, double unloaded) +// -> Cell{Unloaded{}} with probability `unloaded` (std::bernoulli_distribution), otherwise one of +// "A", "B", "C", "D", "E" or empty (std::uniform_int_distribution{0, 5}). +// GroupFilter randomGroupFilter(std::mt19937& rng, std::size_t k) +// -> .columns = c0..c{k-1}; mode Columns or Together (equal odds); +// Columns: match any / all / atLeast n / exactly n (n uniform in 0..k), combine any or all, 1..k include +// entries; Together: 2..k include entries (the only counts besides 0 that compile); +// each entry eq, oneOf (1..3 letters), ne or startsWith, operands drawn from "A".."E"; +// 0..2 exclude entries of the same kinds. +// std::vector> completions(std::vector const& row) +// -> every row obtained by replacing each Unloaded cell by one of "A".."E" or empty (6^u rows, u <= k). + +TEST_CASE("groups: invariant 24 over random tables", "[table][filter][groups]") { + // std::mt19937 seed 24; 300 tables of 40 rows, k = 2..5 Text columns of randomCell(rng, 0.0); + // one randomGroupFilter(rng, k) per table. + // Oracle: Columns mode counts columns whose cell satisfies the entries one by one (CompiledFilter::matches); + // Together tries every injective assignment of entries to columns; an exclude rejects on any match. + CHECK(f.by(spec) == oracleRows); // Mutation: Together decided as atLeast with n = entry count +} + +TEST_CASE("groups: invariant 1 over random completions", "[table][filter][groups]") { // gate G7's oracle + // std::mt19937 seed 1; 200 tables of 30 rows, k = 3 columns of randomCell(rng, 1.0 / 3); + // one randomGroupFilter(rng, 3) per table; for each row r, m = groupMatch(source, filter, r), and over every + // row of completions(row r) the invariant-24 oracle gives: + // m == Match::Yes => the oracle passes every completion; + // m == Match::No => it passes none. + // Unknown is not checked: invariant 1 is soundness only, and `exactly n` or the Together wildcard pass may + // answer Unknown where every completion agrees. + // Mutation: the known pass reading an unknown column as matching every entry — a Yes row has a failing completion. +} + +TEST_CASE("groups: undecided rows are the three-valued rule's", "[table][filter][groups]") { // gate G7 + // std::mt19937 seed 7; 1,000 rows, k = 3 Text columns of randomCell(rng, 1.0 / 3); two filters: `any` with + // oneOf {"A", "B"} (G1's shape) and Together with eq "A", eq "B" (G4's shape). + // Oracle, written in the test from the spec's table and sharing no code with evaluateGroup: per row, y and q + // counted with CompiledFilter::matches on loaded cells; `any` is Unknown when y == 0 and q > 0; Together is + // Yes when an injective assignment exists over known matches, else Unknown when one exists with every + // unloaded cell matching every entry, else No. + auto const page = apply(*source, TableQuery{.sort = {}, .filters = spec, .page = {}}); + CHECK(page->undecided == oracleUnknown); + CHECK(static_cast(f.by(spec)->size()) == oracleYes); + // Mutation: Together's wildcard pass skipped (No instead of Unknown) — `undecided` is below the oracle's. +} + +TEST_CASE("groups: a row costs k lookups and at most one augmentation an entry", "[table][filter][groups]") { // gate G5 + // 1,000 rows, a group of 16 Text columns, every cell valid: "v<0..31>" from std::mt19937{5}; no exclude entries. + // FilterCounters over every row. + CHECK(absentSetCounters.setLookups == 16 * 1'000); // `any`, oneOf {"zz1", "zz2"}: no row holds it, no early stop + CHECK(heldSetCounters.setLookups >= 1'000); // `any`, oneOf {"v0", "v1"}: stops at the first match + CHECK(heldSetCounters.setLookups < 16 * 1'000); + CHECK(togetherCounters.setLookups == 16 * 1'000); // Together, 16 eq entries "v0".."v15": reads every column + // per row, a fresh FilterCounters: a row whose cells leave some entry unmatched has 0 augmentations, + // every other row at most 16. + CHECK(maxAugmentationsOnUncoveredRows == 0); + CHECK(maxAugmentationsOnCoveredRows <= 16); +} +``` + +- [ ] **Step 2: Write the failing pooled-values test** in `test_table_distinct.cpp`: + +```cpp +TEST_CASE("distinct: a group's values are pooled", "[table][distinct][groups]") { + // the truth-table source plus row 5: empty, F, U(nloaded); and a column filter companyA notEmpty is NOT set + auto const d = distinctValues(*source, {}, DistinctRequest{.group = "company"}); + // F counted once per row that has it in any column + CHECK(countOf(d, "F") == 5); // rows 0, 1, 2, 3, 5 + CHECK(countOf(d, "S") == 2); // rows 0, 2 + CHECK(d->blanks == 1); // row 5: the rows an isEmpty entry under any admits + CHECK(d->partial); // row 5's unloaded cell + TableQuery own; // the group's own filter is removed, others stay + own.filters.groups.push_back({.group = "company", .include = {eq("Z")}}); + CHECK(countOf(distinctValues(*source, own, {.group = "company"}), "F") == 5); + CHECK(distinctValues(*source, {}, {.group = "nope"}).error().code == TableErrorCode::UnknownColumn); + // A values list is a read of every column of the group. + ApplyOptions hiddenB; + hiddenB.mayRead = [](std::string_view id) { return id != "companyB"; }; + auto const refused = distinctValues(*source, {}, {.group = "company"}, hiddenB); + REQUIRE_FALSE(refused); + CHECK(refused.error().code == TableErrorCode::ColumnNotReadable); + CHECK(refused.error().column == "companyB"); + // Mutation: the request's group columns not passed through detail::checkColumn — the list comes back with + // companyB's values in it. + TableQuery viaQuery; + viaQuery.distinct = DistinctRequest{.group = "company"}; + CHECK(validate(viaQuery, source->columns(), {}, hiddenB.mayRead, source->groups()).error().code == + TableErrorCode::ColumnNotReadable); +} +``` + +- [ ] **Step 2a: Write the failing server-path and typed-row tests.** In `test_table_description.cpp` (a `ServedTable` over the truth-table source, whose description's `groups` is `source->groups()`): + +```cpp +TEST_CASE("answer query: a declared group filters and pools on the server", "[table][description][groups]") { + TableQuery q; + q.filters.groups.push_back({.group = "company", .mode = GroupMode::Together, .include = {eq("F"), eq("S")}}); + auto const page = detail::answerQuery(served, q); + REQUIRE(page); + CHECK(page->keys == std::vector{std::int64_t{0}, std::int64_t{2}}); + // Mutation: answerQuery calling validate without the source's groups — UnknownColumn naming "company". + // Mutation: detail::PinnedSource not forwarding groups() — the same error, from the compile. + TableQuery pooled; + pooled.distinct = DistinctRequest{.group = "company"}; + auto const values = detail::answerQuery(served, pooled); + REQUIRE(values); + REQUIRE(values->distinct); + CHECK(*values->distinct == *distinctValues(*source, {}, *pooled.distinct)); + // The same two requests over table::scoped(source, keys 0..4) and over a served table with one level + // (so the view is computed over a LeveledSource) answer the same; mutation: either wrapper returning {}. +} +``` + + In `test_table_columns.cpp`, with Step 3's `GroupRow`: + +```cpp +TEST_CASE("typed rows declare their groups to the source", "[table][columns][groups]") { + // rows: {F, S, X, "a"}, {F, F, X, "b"}, {S, F, F, "c"}; keyed by `name` + RowsSource const source{rows, key}; + REQUIRE(source.groups().size() == 1); + CHECK(source.groups()[0] == ColumnGroupInfo{.id = "company", .label = "company", + .columns = {"companyA", "companyB", "companyC"}}); + TableQuery q; + q.filters.groups.push_back({.group = "company", .mode = GroupMode::Together, + .include = {FilterEntry{.eq = "F"}, FilterEntry{.eq = "S"}}}); + auto const page = apply(*rows, key, q); // the typed apply + REQUIRE(page); + CHECK(page->rows.size() == 2); // rows "a" and "c" + // Mutation: RowsSource::groups() returning {} — the typed apply is UnknownColumn. + // And: the description table::typed serves has one group, id "company", label "Company" + // (inferTitle), the same three columns (mutation: typed leaving description.groups empty). +} +``` + +- [ ] **Step 3: Write the failing `x-column-group` test** in `test_table_columns.cpp`: a row type `GroupRow{std::string companyA, companyB, companyC, name;}` with `static constexpr auto columnGroups() noexcept` returning one `{"company", {"companyA","companyB","companyC"}}` (`table::ColumnGroup{std::string_view id; std::span columns;}`, declared in `data_source.hpp`); `"derived columns carry x-column-group"`: the schema property of `companyB` holds `"x-column-group": "company"`, `deriveColumns` copies it into `companyB`'s entry, `name` has none. Mutation: the copy list in `deriveColumns` without `"x-column-group"`. + +- [ ] **Step 4: Run; the new cases fail to compile** (`GroupMode`, `ColumnCount`, `setGroups` undeclared). + +- [ ] **Step 5: Implement declarations and compile.** + - Move `ColumnGroupInfo` (unchanged members, `operator== = default` and Doxygen) from `description.hpp` to `data_source.hpp`; add `struct ColumnGroup` (the typed row's constexpr declaration), `DataSource::groups()`, `VectorSource::setGroups`, and `[[nodiscard]] std::optional detail::checkGroups(std::span, std::span)`: each group has 2 to 16 columns, all present and of one kind, and no column is in two groups; otherwise `SourceContract` naming the group's id. `apply`, `distinctValues`, `Engine::setFilter` and `detail::answerQuery` run it before compiling. + - **Groups on the server** (index decision 43). `RowsSource::groups()` returns a vector built once in its constructor from `Row::columnGroups()` when the row declares it (`requires { Row::columnGroups(); }`), each `ColumnGroup{id, columns}` becoming `ColumnGroupInfo{id, id, columns}` (the label is the id: `query.hpp` does not include `forms.hpp`); `table::typed` copies that vector into the served description's `groups` with each label set to `inferTitle(id)`, as it labels a column with no declared label. `detail::PinnedSource` copies `groups()` beside `columns()` when it pins and returns the copy; `LeveledSource::groups()` returns its base's; the source `table::scoped` returns forwards the shared source's. `detail::computeView` compiles with `source.groups()`. `detail::answerQuery` reads `served.source->groups()` once and passes it to `validate`, `checkGroups` and, through the sources it builds, to `computeView` and `distinctValues`. A `DataSource` wrapper that does not forward `groups()` makes every `{"group": id}` filter `UnknownColumn`, which Step 2a's cases fail on. + - `FilterEntry`, `ColumnFilter`, `GroupFilter`, `ColumnCount` and `FilterSpec` get their defaulted `operator==` (index decision 38). + - `GroupFilter` gains members in the order of the Interfaces block (existing designated initializers `.columns, .combine, .include` stay valid). `glz::meta` for `GroupMode` and the custom read/write for `ColumnCount`. + - `compileGroup(GroupFilter const&, columns, services, groups)`: exactly one of `group` and `columns` is non-empty, else `InvalidSpec`; `group` resolves through `groups` (`UnknownColumn` naming it when absent); a column named twice is `InvalidSpec`; `Together` takes 0, or 2 to k, include entries, else `InvalidSpec` (0 is an exclude-only group, which compiles in either mode, as table.md's "Column groups" states); `AtLeast`/`Exactly` take `0 <= n <= k`, else `InvalidSpec`; more than 32 include entries, or more than 32 exclude entries, is `LimitExceeded` with an empty column. That last bound is `compileGroup`'s own, not only `validate`'s, because `Engine::setFilter` compiles with no `QueryLimits` (it calls `compileFilterGuarded` directly) and each side's entries are bits of one `std::uint32_t` mask. `CompiledFilter::Group` keeps `k` (the named column count), `mode`, `match`, and per column the include and exclude entries that compiled for it; a column on which `combine: all` cannot compile every include entry, or `any` none, never satisfies (it counts as a known *no*). An include or exclude entry that compiles on none of the columns is the error the existing rule returns. A group with no include and no exclude entry compiles to nothing: `compileFilter` keeps a compiled group when its `include` or its `exclude` is non-empty (the condition `!group.include.empty()` becomes `!group.include.empty() || !group.exclude.empty()`). + - Per column, the compile builds a **value index**: one hash map from a cell key to the bit mask (`std::uint32_t`: `Columns` mode takes up to 32 entries a side, as `compileGroup` enforces; `Together` is capped at k ≤ 16) of the include entries that are `eq` or `oneOf` on it (folded text unless `caseSensitive`), and the list of the other include entries with their bit. `exclude` is compiled the same way into its own index. + - `checkFilters`: a group's `include + exclude` count against `maxEntries`, every exclude entry against `maxTextLength`; `group` and `columns` resolve and pass `checkColumn` (a declared group through `source.groups()`, which `validate` receives as a new trailing `std::span groups = {}` parameter). + +- [ ] **Step 6: Extend `CompiledFilter::evaluateGroup(Group const&, keys, row, counters)`** with this algorithm (the spec fixes it; G5 counts it): + +```text +mask(c): cell = keys[c] at row; counters->cellReads += 1 + Unloaded -> unknown column + Empty / Invalid -> entries matching by the column-filter rules (isEmpty / notEmpty only) + Valid -> index lookup (counters->setLookups += 1) | each condition entry tested + +empty include: the include part is Yes, and neither `mode` nor `match` is consulted (an exclude-only group + compiles in either mode); only the exclude part below decides. + +Columns mode (each column known-satisfies when combine any: mask != 0; all: mask == every compiled include bit +and the column compiled every include entry): read columns in order, keeping y (satisfying), q (unknown), +r (columns not yet read); stop as soon as decided: + any Yes y>=1 No y+q+r == 0 + all Yes y == k No y+q+r < k + atLeast Yes y>=n No y+q+r < n + exactly Yes y==n, q==0, r==0 No y>n or y+q+r < n + otherwise, after the last column: Unknown + +Together mode (E = include entries, full = (1< No (no augmentation) + known pass: Kuhn matching over known masks; for e in 0..E-1: + counters->augmentations += 1; if !augment(e) { fail; break } + all augmented -> Yes + unknownCols empty -> No + wildcard pass: the same matching with mask(c) = full for every unknown column + (not counted) -> Unknown if it covers every entry, else No + augment(e): for each column c with bit e in mask(c), not visited: visit c; + if owner[c] is none or augment(owner[c]): owner[c] = e; return true + return false + +exclude (both modes): any known cell matching any exclude entry -> No; otherwise any unknown column -> Unknown; + otherwise Yes. A group with exclude entries reads every column: once the include part is decided its reading + stops, and the columns it did not read are still read for the exclude index (one exclude-index lookup per valid + cell, counted in setLookups like the include index's). Empty and invalid cells do no index lookup. +group result: No if include-part or exclude-part is No; else Unknown if either is Unknown; else Yes. +``` + + `FilterRun`'s group stage and `evaluateRow` already call `evaluateGroup` (Task 3); they pass no counters. + +- [ ] **Step 7: Engine and pooled values.** `Engine::compile` passes `_source->groups()`; `fitToColumns` keeps a `GroupFilter` whose `group` the source still declares and drops one whose `group` it no longer declares, then erases groups whose `columns` and `group` are both empty. `distinctValues` with `request.group`: the group resolves through `source.groups()` (`UnknownColumn` naming it when absent) and every one of its columns passes `detail::checkColumn` with `options.mayRead` (`ColumnNotReadable` naming the first that does not), in the request's validation, which `validate` runs too for `query.distinct`; then the rows passing every filter with every `GroupFilter` whose `group == request.group` removed; per candidate row, the set of distinct keys over the group's loaded valid cells (a row counts once per value); `blanks` counts rows with at least one empty cell, `invalid` rows with at least one invalid cell; an unloaded cell sets `partial` and the row's loaded cells still count. A value's text and operand come from the first row and column (in group order) that holds it. Remove 8a's `Unavailable` branch. `levelsNeeded` adds the level of every column of `request.group` to `order`, and resolves a group filter's `group` too: it gains a trailing `std::span groups = {}` parameter, which every caller passes as it passes `validate`'s; test `"distinct: a group's levels are order levels of the request"` in `test_table_distinct.cpp` (group `company` with `companyB` at level `"slow"`: `levelsNeeded(q with distinct{.group = "company"}, …).order == {"slow"}`; mutation: the group's columns left out). + +- [ ] **Step 8: `x-column-group`.** `mergeSchemaExtras` writes `"x-column-group": ""` on each property a row's `columnGroups()` names; `deriveColumns` adds `"x-column-group"` to the keys it copies. `docs/spec/forms/views.md`: one line under the copied keys, and the `v-columns` row's key list gains `"x-column-group"?`. + +- [ ] **Step 9: Fixture.** `bench::WideTableSource::groups()` returns, from `layout()`'s `group` attributes, `{"g3", "Group of 3", {t004, t005, t006}}` and `{"g16", "Group of 16", {t011 ... t026}}` (`wideColumns(30)` keeps only `t004`...`t006`, so the 30-column source declares `g3` alone). `bench::WideTableModel`'s three descriptions take their `groups` from `source->groups()` rather than from the layout a second time. + +- [ ] **Step 10: Run** `ctest --test-dir build/cl-debug -R "groups|distinct|x-column-group|filter|answer query|typed rows" --output-on-failure`; expected: all pass, and the existing group cases (`"columns combine by AND, and a group matches on any of its columns"`, `"an all-group uses only the columns that evaluate every entry"`) unchanged and passing. + +- [ ] **Step 11: Mutations.** (a) `Together` decided as `atLeast` with n = entry count: the truth table fails on row `F, F, X`. (b) `exactly` deciding `Yes` while `q > 0`: the three-valued case `{F,X,U}` fails. (c) the known pass reading unknown columns as matching every entry: the three-valued case `{F,F,U}` reports `Yes`. (d) skipping the covered-mask check: G5 fails (augmentations on rows that cannot match). (e) `compileGroup` without its 32-a-side bound: `"groups: more than 32 entries on a side is refused where the filter compiles"` fails on its first `CHECK`. (f) `Together` requiring 2 to k include entries with no exception for 0: `"groups: duplicate columns, exactly zero and too many together entries"` fails on the exclude-only `Together` line. (g) `Filtered::by` compiling without `source->groups()`: the truth-table case fails with `UnknownColumn`. (h) `answerQuery` validating without the source's groups, and (i) `detail::PinnedSource::groups()` returning `{}`: `"answer query: a declared group filters and pools on the server"` fails with `UnknownColumn`. (j) `RowsSource::groups()` returning `{}`: `"typed rows declare their groups to the source"` fails. (k) the pooled request's columns not passed through `checkColumn`: `"distinct: a group's values are pooled"` fails on `ColumnNotReadable`. (l) `Together`'s wildcard pass skipped: `"groups: undecided rows are the three-valued rule's"` fails on `undecided`. Paste each; revert. + +- [ ] **Step 12: Timings G1–G4, G6, G7.** `TEST_CASE("table benchmark: column groups", "[.benchmark][table][groups]")` on 100,000 rows generated with `std::mt19937{7}` (a group of 3 and one of 16 Text columns, keys built): G1 `any` with a 2-value `oneOf`; G2 with a 1,000-value `oneOf`; G3 `atLeast 2` and `exactly 1`; G4 `together` 2 entries over 3 columns and 16 over 16; G6 pooled distinct values, first 200; G7 G1 and G4 with a third of the cells `Unloaded` (timing only: G7's count gate is Step 1's ordinary case `"groups: undecided rows are the three-valued rule's"`, which CI runs). Write the figures into table.md "Benchmarks: column groups". + +- [ ] **Step 13: Confirm table.md states `Together` with no include entry.** The spec is not edited: its "Column groups" bullet "**`Together` mode.**" already says "It takes at least 2 include entries and at most as many as the group has columns, so at most 16. A group with no include entry is an exclude-only group in either mode: only its `exclude` decides." + Check: `grep -n "exclude-only group" docs/spec/table/table.md` prints that one line. + +- [ ] **Step 14: Docs build; commit** `feat(table): column groups with quantifiers` (the twelve mutations' failing lines in the body; the G1–G4, G6, G7 figures in table.md in the same commit). + +--- + +### Task 8c: Values with units + +**Spec:** "Values with units" (all subsections); "Rows on the wire" (the `Measure` row of the cell table); invariant 25; Tests rows "Values with units", "Unit numbers across registries", "The generic page" (measure half); Failure modes row "A level cache read under a registry of another lineage"; gate M5; timings M1–M4. + +**Files:** +- Modify: `include/morph/table/data_source.hpp` (`UnitInfo`, `UnitId`, `kUnknownUnit`, `UnitRegistry`, `UnitRegistryBuilder`, `addUnitsOf`, `Measure`, `Cell`'s last alternative, `ColumnKind::Measure`, `ColumnInfo::dimensions`, `Services::units`, `displayText`, `unitsFor`) +- Modify: `include/morph/table/sort.hpp` (`KeyColumn` for `Measure`, `compareKeys`) +- Modify: `include/morph/table/filter.hpp` (operands with units, `ValueSet` of measures) +- Modify: `include/morph/table/query.hpp` (`MeasureValue`, `kindOf`, `toCell`, `RowsSource`'s registry, typed `apply`, `distinctValues` on measures, `DistinctValue::{dimension, unit}`, the `SourceContract` check) +- Modify: `include/morph/table/description.hpp` (`TableDescription::units` after `levels`; the generic page's `Measure` cell; `registryOf`; `servedDescription` fills `units`, so `DescribeTable::invoke` and every page's revision both carry them) +- Modify: `include/morph/table/state_store.hpp` (`detail::listsUnit`; `fitState` compiles a stored filter with `registryOf(description)`, so a measure operand the description's units resolve is kept) +- Modify: `include/morph/table/level_cache.hpp` (`LevelCacheOptions::units`, the lineage check) +- Modify: `include/morph/forms/forms.hpp` (a forward declaration of `table::MeasureValue`, `detail::isMeasureValue`, `x-measure` on such a property), `include/morph/forms/views.hpp` (`inferColumnKind` → `"measure"`) +- Create: `include/morph/ui/measure.hpp` (`ui::TypedMeasure`, `ui::parseMeasure`, `ui::measureOperand`); `tests/table/test_table_measure.cpp` (in `morph_table_tests`; add to `tests/CMakeLists.txt`) +- Modify: `include/morph/ui/table_config.hpp` and `tests/test_ui_table_config.cpp` (Task 12a landed first; Step 8a below) +- Modify: `tests/table/test_table_description.cpp`, `tests/table/bench_table.cpp`, `tests/table/wide_table_model.{hpp,cpp}` (its 10 measure columns become `ColumnKind::Measure` over the fixture registry below) + +**Interfaces:** +- Consumes: 8a's `ValueSet`, `distinctValues`; Task 3's `Unloaded`, `SourceContract`; Task 1's generic page; Task 5's `CellLevelCache`, `LevelCacheOptions`, `LevelCacheStats`. +- Produces: + ```cpp + struct UnitInfo { std::string id; std::string symbol; std::string dimension; math::Rational toBase; std::uint32_t decimals = 0; + [[nodiscard]] bool operator==(UnitInfo const&) const = default; }; + // UnitInfo needs ==: TableDescription's defaulted operator== (Task 1) covers `units`, and without it that + // operator is deleted. table::UnitInfo is not ui::UnitInfo (ui/expression.hpp); ui code names it qualified. + using UnitId = std::uint32_t; + inline constexpr UnitId kUnknownUnit = std::numeric_limits::max(); // never a live unit + class UnitRegistry { + public: + [[nodiscard]] std::optional find(std::string_view id) const; // counts findCalls() + [[nodiscard]] UnitInfo const& info(UnitId unit) const; // precondition: contains(unit) + [[nodiscard]] bool contains(UnitId unit) const noexcept; // false for a tombstone or kUnknownUnit + [[nodiscard]] std::span dimensions() const; + [[nodiscard]] std::span unitsOf(std::string_view dimension) const; + [[nodiscard]] std::uint64_t lineage() const noexcept; + [[nodiscard]] std::uint64_t findCalls() const noexcept; // relaxed counter, for gate M5 + }; + class UnitRegistryBuilder { + public: + UnitRegistryBuilder(); // seeds {"", "", "ratio", 1, 6} + explicit UnitRegistryBuilder(std::shared_ptr previous); + std::expected add(UnitInfo unit); + bool remove(std::string_view id); + [[nodiscard]] std::shared_ptr build() &&; + }; + template + std::expected addUnitsOf(UnitRegistryBuilder& builder, std::span units, + std::string_view (*dimensionOf)(E)); + struct Measure { math::Rational amount; UnitId unit = 0; + [[nodiscard]] bool operator==(Measure const&) const = default; }; // amount by Rational's == + using Cell = std::variant; + // ColumnKind::Measure appended after Custom, JSON "measure"; ColumnInfo::dimensions (std::vector, last member) + // Services::units: std::shared_ptr + [[nodiscard]] std::vector unitsFor(UnitRegistry const& registry, std::span columns); + // query.hpp + struct MeasureValue { math::Rational amount; std::string unit; }; // JSON {"num","den","unit"}; schema x-measure + struct DistinctValue { /* 8a members */ std::string dimension; std::string unit; }; + // description.hpp + [[nodiscard]] std::expected, TableError> registryOf(TableDescription const& description); + // writeGenericPage / readGenericPage gain a trailing `UnitRegistry const* units = nullptr`: + [[nodiscard]] GenericPage writeGenericPage(PageRows const& page, DataSource const& source, + std::span columns, UnitRegistry const* units = nullptr); + // Task 1's writer returns a GenericPage, not an expected, so it has no error to return: a non-null `units` + // when a written column is Measure is its documented precondition (an assert in debug builds), and + // detail::answerQuery checks it first, answering SourceContract when served.services.units is null + [[nodiscard]] std::expected + readGenericPage(std::string_view json, TableDescription const& description, UnitRegistry const* units = nullptr); + // units == nullptr: resolved through registryOf(description), built once per call and only when a + // column of the page is Measure — a client has no registry of its own, only the description's units + // level_cache.hpp + // LevelCacheOptions::units: std::function()> (empty: no units) + // ui/measure.hpp + namespace morph::ui { + struct TypedMeasure { math::Rational amount; std::string unit; // unit: the unit's id + [[nodiscard]] bool operator==(TypedMeasure const&) const = default; }; + // parseMeasure's tests compare std::optional with a TypedMeasure + [[nodiscard]] std::optional parseMeasure(std::string_view text, std::span units, + LocaleFacts const& locale, std::string_view chosen = {}); + [[nodiscard]] std::string measureOperand(TypedMeasure const& measure); // "0.3 kg"; "0.003" for the ratio unit + } + ``` + +The test registry used below (built once in the file): `""` (seeded), `kg` (`"kg"`, mass, 1, 3), `g` (`"g"`, mass, 1/1000, 0), `percent` (`"%"`, ratio, 1/100, 2). Helper `m(std::string_view amount, std::string_view unit) -> Cell` is `Measure{dec(amount), *registry->find(unit)}`. Columns: `col("w", ColumnKind::Measure)` with `dimensions = {"mass", "ratio"}` unless a case says otherwise; `ApplyOptions::services.units = registry`. The filter helpers dereference, so two of them compare as plain vectors (`TableError` has no `operator==`, so two `std::expected`s would not compile): `rowsOf(FilterEntry) -> Rows` is `REQUIRE`d to succeed and returns `*f.by(…)`; `error(FilterEntry) -> TableError` and `errorOnMassOnly(FilterEntry) -> TableError` are `REQUIRE`d to fail and return `.error()`; `groupRows(GroupFilter) -> Rows` does the same over the two-column source of the group case, compiling with `source->groups()`. + +- [ ] **Step 1: Write the failing order and filter tests** in `test_table_measure.cpp` (header mutation line: "a key that ignores the unit's factor: `300 g sorts between 0.2 kg and 0.5 kg` fails"): + +```cpp +// rows: 0: 0.5 kg 1: 0.3 % 2: 300 g 3: 0.2 kg 4: empty 5: 0.2 % +TEST_CASE("measure: 300 g sorts between 0.2 kg and 0.5 kg in both directions", "[table][measure]") { + CHECK(sorted(SortDirection::Ascending) == std::vector{3, 2, 0, 5, 1, 4}); + CHECK(sorted(SortDirection::Descending) == std::vector{0, 2, 3, 1, 5, 4}); // groups stay, amounts reverse +} + +TEST_CASE("measure: filters compare base amounts within a dimension", "[table][measure]") { + CHECK(rowsOf(gt("250 g")) == Rows{0, 2}); // drops 0.2 kg and both percents + CHECK(rowsOf(eq("300 g")) == rowsOf(eq("0.3 kg"))); + CHECK(rowsOf(eq("0.3 kg")) == Rows{2}); // 300 g; not 0.3 %: they are not equal + CHECK(rowsOf(ne("250 g")) == Rows{0, 1, 2, 3, 5}); // other dimensions included; empty never matches + CHECK(rowsOf(eq("0.003")) == Rows{1}); // no unit: a ratio, equal to 0.3 % + CHECK(rowsOf(oneOf({"300 g", "0.2 percent"})) == Rows{2, 5}); + CHECK(rowsOf(between("0.25 kg", "600 g")) == Rows{0, 2}); + CHECK(error(eq("250 lb")).code == TableErrorCode::InvalidValue); CHECK(error(eq("250 lb")).column == "w"); + CHECK(error(between("1 kg", "50 percent")).code == TableErrorCode::InvalidValue); + CHECK(errorOnMassOnly(eq("0.003")).code == TableErrorCode::InvalidValue); // dimensions = {"mass"} +} + +TEST_CASE("measure: a group of measure columns filters by base amount", "[table][measure][groups]") { + // columns w1, w2 (Measure, dimensions {"mass", "ratio"}), declared group {"weights", "Weights", {w1, w2}} + // 0: 0.3 kg, 1 kg 1: 5 %, 300 g 2: 30 %, 2 kg 3: empty, 0.3 kg 4: 300 g, 0.3 kg + // row 2's 30 % is 0.3 in the ratio's base unit: equal in amount to 300 g's 0.3 kg, of another dimension, so a + // value index keyed by the amount alone puts it in the first result (0.3 % would be 0.003 and never collide) + CHECK(groupRows({.group = "weights", .include = {eq("300 g")}}) == Rows{0, 1, 3, 4}); // not row 2: 30 % is not 0.3 kg + CHECK(groupRows({.group = "weights", .include = {oneOf({"0.3 kg", "0.3"})}}) == Rows{0, 1, 2, 3, 4}); + CHECK(groupRows({.group = "weights", .match = {.kind = ColumnCount::Kind::All, .n = 1}, + .include = {eq("300 g")}}) == Rows{4}); + CHECK(groupRows({.group = "weights", .mode = GroupMode::Together, .include = {eq("300 g"), eq("1 kg")}}) == Rows{0}); + CHECK(groupRows({.group = "weights", .include = {}, .exclude = {gt("1.5 kg")}}) == Rows{0, 1, 3, 4}); + FilterCounters counters; // every row evaluated with evaluateGroup for the first filter + CHECK(counters.setLookups == 7); // `any` stops at a match: rows cost 1, 2, 2, 1 (the empty cell none), 1 + // Mutation: the group value index keyed by amount without the place — row 2 joins the first result. + // Mutation: a Measure `eq` kept as a condition entry instead of an index entry — setLookups is 0. +} + +TEST_CASE("measure: invalid cells and the registry contract", "[table][measure]") { + // Measure{1, kUnknownUnit}; a ratio cell in a mass-only column: both Invalid, sort with empty after valid + CHECK(sortedMassOnly(SortDirection::Ascending).back() == /* the empty row */); + ApplyOptions none; // services.units null + CHECK(apply(*source, sortBy("w"), none).error().code == TableErrorCode::SourceContract); +} + +TEST_CASE("measure: negative and zero amounts", "[table][measure]") { // Review Focus 4 + // mass+ratio column: -300 g, -0.2 kg, 0 g, 0 kg, -0.5 % + CHECK(sortedAsc == std::vector{0, 1, 2, 3, 4}); // -300 g < -0.2 kg < 0 g = 0 kg (by row), then ratio + CHECK(sortedDesc == std::vector{2, 3, 1, 0, 4}); // mass reversed, ties by source row, ratio last + CHECK(distinctCount("0 g") == 2); // 0 g and 0 kg one value + CHECK(errorOnMassOnly(eq("0")).code == TableErrorCode::InvalidValue); +} + +TEST_CASE("measure: 0.3 kg and 300 g are one distinct value", "[table][measure]") { + // rows: 0.3 kg, 300 g, 0.3 % + REQUIRE(d->values.size() == 2); + CHECK(d->values[0].count == 2); CHECK(d->values[0].dimension == "mass"); CHECK(d->values[0].unit == "kg"); + CHECK(d->values[0].text == "0.3 kg"); CHECK(d->values[0].operand == "0.3 kg"); + CHECK(d->values[1].dimension == "ratio"); CHECK(d->values[1].text == "0.3 %"); CHECK(d->values[1].operand == "0.3 percent"); +} + +TEST_CASE("measure: invariant 25 over random amounts", "[table][measure]") { + // std::mt19937 seed 25; 500 rows of random amounts in kg, g, percent, ""; sort ascending and descending; + // within a dimension the order equals the order by amount * toBase (exact Rational), ties by source row; + // eq on any one row's operand matches exactly the rows of equal base amount and equal dimension. +} + +TEST_CASE("measure: keys look units up by number only", "[table][measure]") { // gate M5 + auto const before = registry->findCalls(); + // build the Measure KeyColumn over 100,000 cells (KeyColumn::forColumn + buildKeys) + CHECK(registry->findCalls() == before); +} +``` + +- [ ] **Step 2: Write the failing registry tests:** + +```cpp +TEST_CASE("units: a unit id is a token", "[table][measure]") { + UnitRegistryBuilder b; + for (std::string_view bad : {"k g", "1kg", "-kg", "+kg", ".kg", ",kg", "", "abcdefghijklmnopqrstuvwxyz0123456"}) // last: 33 bytes + CHECK(b.add({.id = std::string{bad}, .symbol = "x", .dimension = "mass", .toBase = dec("1"), .decimals = 0}).error().code + == TableErrorCode::InvalidSpec); + CHECK(b.add(kg)); CHECK_FALSE(b.add(kg)); // a second unit of one id + CHECK(b.add({.id = "z", .symbol = "z", .dimension = "mass", .toBase = dec("0"), .decimals = 0}).error().code == TableErrorCode::InvalidSpec); + auto const r = std::move(b).build(); + CHECK(r->find("") == UnitId{0}); CHECK(r->info(0).dimension == "ratio"); + CHECK(std::ranges::equal(r->dimensions(), std::vector{"ratio", "mass"})); +} + +TEST_CASE("units: numbers survive a successor and tombstones stay", "[table][measure]") { + auto const first = /* "", kg, g, percent */; + UnitRegistryBuilder next{first}; + CHECK(next.remove("g")); + auto const mg = next.add({.id = "mg", .symbol = "mg", .dimension = "mass", .toBase = dec("0.000001"), .decimals = 0}); + auto const second = std::move(next).build(); + CHECK(second->find("kg") == first->find("kg")); + CHECK_FALSE(second->find("g")); + CHECK_FALSE(second->contains(*first->find("g"))); + CHECK(*mg == 4); // after "", kg, g, percent; g's 2 never reused + CHECK(second->lineage() == first->lineage()); + CHECK(std::move(UnitRegistryBuilder{}).build()->lineage() != first->lineage()); + CHECK(std::ranges::equal(second->unitsOf("mass"), std::vector{*first->find("kg"), *mg})); // largest factor first + // a Measure{1, g's number} under `second` is an invalid cell +} + +TEST_CASE("units: a level cache keeps values under a successor and drops them under another lineage", "[table][measure]") { + // CellLevelCache over one Measure column, LevelCacheOptions::units returning `current`; + // load key 1 (Measure 300 g), snapshot reads it, stats().loaderCalls == 1. + current = successor; // same lineage + CHECK(read(1) == LevelRead::Loaded); CHECK(cache.stats().loaderCalls == 1); + current = fresh; // another lineage + CHECK(read(1) == LevelRead::Unloaded); CHECK(cache.stats().invalidatedKeys >= 1); +} + +TEST_CASE("units: addUnitsOf reads a unit enum", "[table][measure]") { + // tests' own enum TmUnit { kg, g, percent } with UnitTraits (meta + relations g->kg 1/1000); + // dimensionOf maps kg, g -> "mass", percent -> "ratio". + // registry holds kg (toBase 1, decimals from meta), g (1/1000); percent is refused (InvalidSpec): + // a ratio unit must reach the dimension's base "" through relations, and TmUnit has none to it. +} +``` + + `addUnitsOf` rule pinned by this test: within a dimension the base is the dimension's existing base unit (`""` for ratio) or else the first enumerator of `units` in that dimension; every other unit's `toBase` is the product of `UnitRelation::fromTo` along a relation path to the base (searched in both directions, the reverse taking the reciprocal); a unit with no path is `InvalidSpec`; `symbol` is `UnitMeta::display`, `decimals` `UnitMeta::defaultDecimals`. + +- [ ] **Step 3: Write the failing wire, typed-row and parser tests.** In `test_table_description.cpp`: `"generic page: a measure round-trips"` — a page of one Measure column holding `Measure{3/10, kg}` writes `[3, 10, "kg"]` (`writeGenericPage(…, registry.get())`), and reads back as `std::get(cell) == Measure{dec("0.3"), kgId}` both through `readGenericPage(json, description, registryOf(description)->get())` and through `readGenericPage(json, description)` with no registry passed (the description's `units` hold `kg`, so `kgId` is `registryOf(description)`'s number for it); an unknown id in the JSON reads as `Measure{…, kUnknownUnit}` (an invalid cell). Mutation: `readGenericPage` with `units == nullptr` returning `SourceContract` instead of building `registryOf(description)` — the no-registry read fails. In `test_table_measure.cpp`: + +```cpp +TEST_CASE("measure: typed rows carry their unit by id", "[table][measure]") { + struct MRow { std::int64_t id; MeasureValue weight; }; // file-scope in the real test, for glaze + // typed apply with services.units: column "weight" is ColumnKind::Measure; sort ascending by weight over + // {0.5 kg, 300 g, "lb"(unknown)} gives 300 g, 0.5 kg, then the unknown unit as invalid. + // schemaJson() property weight has "x-measure": true; deriveColumns gives kind "measure". +} + +TEST_CASE("measure: what a user types", "[table][measure]") { + auto const en = ui::localeFacts("en"); auto const de = ui::localeFacts("de"); + CHECK(ui::parseMeasure("0.3kg", units, en) == ui::TypedMeasure{dec("0.3"), "kg"}); + CHECK(ui::parseMeasure("0.3 kg", units, en) == ui::TypedMeasure{dec("0.3"), "kg"}); + CHECK(ui::parseMeasure("300 g", units, en) == ui::TypedMeasure{dec("300"), "g"}); + CHECK(ui::parseMeasure("0.3 KG", units, en) == ui::TypedMeasure{dec("0.3"), "kg"}); // then without case + CHECK(ui::parseMeasure("5 %", units, en) == ui::TypedMeasure{dec("5"), "percent"}); // by symbol + CHECK(ui::parseMeasure("0,3 kg", units, de) == ui::TypedMeasure{dec("0.3"), "kg"}); + CHECK_FALSE(ui::parseMeasure("0.3 kg", units, de)); // '.' is de's group separator + CHECK(ui::parseMeasure("12", units, en, "g") == ui::TypedMeasure{dec("12"), "g"}); + CHECK(ui::parseMeasure("12", units, en) == ui::TypedMeasure{dec("12"), ""}); + CHECK(ui::parseMeasure("-1.5 g", units, en) == ui::TypedMeasure{dec("-1.5"), "g"}); + CHECK_FALSE(ui::parseMeasure("0.3 lb", units, en)); + CHECK(ui::measureOperand({dec("0.3"), "kg"}) == "0.3 kg"); + CHECK(ui::measureOperand({dec("0.003"), ""}) == "0.003"); +} +``` + +- [ ] **Step 4: Run; the new cases fail to compile** (`UnitRegistryBuilder`, `Measure`, `ColumnKind::Measure` undeclared). + +- [ ] **Step 5: Registry and cell** (`data_source.hpp`): the Interfaces block; `static_assert(sizeof(Measure) <= sizeof(QuantityCell))` beside `Cell`. `UnitRegistry` stores units in a vector indexed by `UnitId` (a tombstone slot is kept), a `std::unordered_map` for `find`, dimensions in first-registration order (kept from `previous`), and per dimension its unit ids sorted by `toBase` descending. `lineage()` is drawn from a process-wide `std::atomic` when a builder starts from nothing and copied from `previous` otherwise. The builder refuses (`InvalidSpec`): an id of 0 or more than 32 bytes, holding white space, or beginning with a digit, `+`, `-`, `.` or `,`; an id already live; `toBase <= 0`; an empty `dimension`. The ratio unit `""` is seeded only by the default constructor and cannot be removed. `displayText(Measure)` is the amount's decimal text (`formatRationalDecimal`); a unit's symbol is the display layer's. `unitsFor` returns the live units of every dimension a `Measure` column of `columns` allows (all dimensions for an empty `dimensions`), in registry order. `ColumnKind::Measure` is appended after `Custom` with JSON `"measure"`. + +- [ ] **Step 6: Keys and order** (`sort.hpp`). `KeyColumn` gains `std::vector places` (per row) and, built once in `forColumn` from `services.units`, `std::vector unitPlaces` and `std::vector unitFactors` indexed by `UnitId` (`-1` for a tombstone or a dimension the column does not allow; the place is the dimension's index in `info.dimensions`, or in `registry.dimensions()` when that is empty). Reading a cell into a `Measure` column: `Measure` → place and `checkedMul(amount, factor)` into `exact` (overflow or `-1` → `Invalid`); `Rational`/`int64` → the ratio unit `""`; `std::string` → parsed as an operand (Step 7's grammar); anything else `Invalid`. `compareKeys` for `Measure`, after the rank rule: + +```text +if places[l] != places[r]: return places[l] < places[r] ? -1 : 1 // direction not applied +result = sign(exact[l] <=> exact[r]); return dir == Descending ? -result : result +``` + +- [ ] **Step 7: Filters** (`filter.hpp`). `operatorDefined(Measure, op)` is the numeric kinds' rule. An operand on a `Measure` column is `` or ` ` (one space; the decimal by `parseDecimal`); no id is the ratio unit `""`. The unit must be live, its dimension allowed by the column, and `checkedMul` must fit; otherwise `InvalidValue` naming the column. `CompiledFilter::Entry` gains `std::array places`; `between`'s two places must be equal (`InvalidValue`). `matches` on a valid `Measure` cell: `Ne` → `places != entry.places[0] || exact != operand`; every other comparison → `false` when the places differ, else `compare` on `exact`. `ValueSet` holds `(place, base amount)` pairs for a `Measure` column, and so does a group's per-column **value index** (8b Step 5): its key for a `Measure` column is that pair, so an `eq` or `oneOf` entry of a group over `Measure` columns is one lookup a cell, and an entry whose operand does not compile for a column (its dimension not allowed there) does not apply to that column, by the group rule. + +- [ ] **Step 8: Typed rows, distinct, wire, level cache, parser.** + - `query.hpp`: `MeasureValue` with `glz::meta` writing `{"num","den","unit"}`; `kindOf()` is `Measure`; the cell readers become `Cell (*)(Row const&, UnitRegistry const*)` and `toCell(MeasureValue)` resolves the id (`find`), giving `kUnknownUnit` when absent; `RowsSource` takes `std::shared_ptr units` as its last constructor parameter and the typed `apply` passes `options.services.units`. **A typed table on the bridge** has no `ServedTable` of its own making, so `detail::serve` (Task 2), when it builds the `RowsSource` of a `table::typed` table, asks the model: a model that declares `std::shared_ptr tableUnits(TableContext const&)` (detected by `requires`) has it called on the strand, and its result becomes both the `RowsSource`'s registry and `served.services.units`; a model without it serves a null registry, and a row type with a `MeasureValue` member is then `SourceContract` from `Table.` and `Table..describe` alike ("a table with measures needs a unit registry"). Test `"typed table: a model's units reach its measures"` in `test_table_description.cpp`: `detail::serve` over a model with `tableUnits` answers a page whose `weight` cell is `[3, 10, "kg"]` and a description listing `kg`; the same model without `tableUnits` is `SourceContract`. Mutation: `serve` leaving `served.services.units` null. `apply`, `distinctValues` and `Engine::setSort`/`setFilter` return `SourceContract` when a column they sort, filter or list values of is `Measure` and `services.units` is null; so does `detail::answerQuery` when a column it would write is `Measure` and `served.services.units` is null, checked before it calls `writeGenericPage` (whose non-null `units` for a `Measure` column is a precondition: it returns a `GenericPage`, not an `expected`). `distinctValues` on a `Measure` column groups by `(place, base amount)`; a value's `text` is ` ` of its first row (no space and no symbol for `""`), `operand` ` `, `dimension` and `unit` that row's. + - `description.hpp`: `TableDescription::units` (`std::vector`, after `levels`, so `describe`'s revision covers it); `servedDescription` (Task 16; what `DescribeTable::invoke` and `detail::answerQuery` both take their revision from, so a page and the describe reply agree) sets `units = unitsFor(*served.services.units, columnInfos(description))` before `describe` when a column is `Measure` and the model left `units` empty, and answers `SourceContract` when a column is `Measure` and `services.units` is null, and `detail::answerQuery` passes `served.services.units.get()` to `writeGenericPage`. `registryOf(description)` builds a registry from `description.units` (`""` already seeded and skipped). The page writer writes `Measure` as `[num, den, ""]` through `units`. The reader resolves the id through `units` when given one; with `units == nullptr` and a `Measure` column in the page it builds `registryOf(description)` once for the call and resolves through that (an error from `registryOf` is returned as is). Part D's `WindowRows` calls `readGenericPage(json, description)` with no registry, which is why the default resolves through the description: a client learns units from the description and from nowhere else. + - `level_cache.hpp`: the cache records `units()->lineage()` with each stored value set; `snapshot()` first compares the current registry's lineage with the recorded one and, when they differ, runs `invalidateAll()` (counted in `invalidatedKeys`). + - `forms.hpp` includes no table header and gains none. It forward-declares `namespace morph::table { struct MeasureValue; }` and adds `template inline constexpr bool detail::isMeasureValue = std::same_as, table::MeasureValue>` (true through `std::optional` too, as `isQuantity` members are unwrapped); the pass that writes `x-decimalPlaces` for a `Quantity` member writes `"x-measure": true` for such a member. Comparing against an incomplete type is well-formed, so a translation unit that never includes `query.hpp` still compiles. `views.hpp`: `inferColumnKind` returns `"measure"` for an `x-measure` property, tested **before** its `num`/`den` rule: a `MeasureValue`'s schema has both, and would otherwise read as `"decimal"` (mutation: the `x-measure` test placed after that rule — `"measure: typed rows carry their unit by id"` fails on the kind). + - `ui/measure.hpp`: `parseMeasure` reads an optional `-`, digits, at most one `locale.numeric.decimalSeparator` followed by digits, optional spaces, then a unit: an exact match of a unit's `symbol` or `id` first, then the same compared ASCII-case-insensitively, first in `units` order; no unit text takes `chosen`. Anything else (a group separator included) is `std::nullopt`. `measureOperand` writes `formatRationalDecimal(amount)`, then `" " + unit` unless `unit` is empty. + +**Carried from 9b.** Task 9b (the table state store) landed before this task and leaves two things for it: +- `table::detail::listsUnit` (`include/morph/table/state_store.hpp`), which the state document's fitting uses to keep or drop a stored display unit, is a stand-in that always returns `false`, because a description carries no units yet. With `TableDescription::units` in place it must return whether the description lists `unit` for `dimension`. Add `include/morph/table/state_store.hpp` to this task's Files. +- 9b's case `"table state: stale state is fitted"` (`tests/table/test_table_state.cpp`) uses a `weight` column of kind `Quantity`. This task makes it a `Measure` column whose description lists the units `g` and `kg` of dimension `mass`, and adds a `CHECK` that a stored display unit the description lists (`mass` → `g`) is kept. Mutation: `listsUnit` returning `false` — the listed unit is dropped and that `CHECK` fails. + +- [ ] **Step 8a: The configuration functions learn `Measure`** (Task 12a, `ui/table_config.hpp`, landed before this task). Its two switches over `ColumnKind`, in `canonicalOperand` and `conditionOps`, name every kind with no `default`, and MSVC is told to treat C4062 as an error there, so adding `ColumnKind::Measure` fails to compile until both handle it: + - `canonicalOperand` gains the trailing parameters `std::span units = {}, std::string_view chosenUnit = {}`; a `Measure` operand is `ui::parseMeasure(typed, units, locale, chosenUnit)`, written by `ui::measureOperand`, and `nullopt` when it does not parse. + - `conditionOps(Measure)` is the numeric list (`=`, `≠`, `<`, `≤`, `>`, `≥`, between). + - In `test_ui_table_config.cpp`, with a file-local `massUnits()` (the `UnitInfo`s `kg` and `g` of dimension mass): `"typed operands: …"` gains `CHECK(ui::canonicalOperand("0,3 kg", table::ColumnKind::Measure, de, massUnits()) == "0.3 kg");` and `CHECK(ui::canonicalOperand("250", table::ColumnKind::Measure, de, massUnits(), "g") == "250 g");`; `"conditions follow the column's kind"` adds `table::ColumnKind::Measure` to the numeric loop; `"header menu: entries, order and enablement"` sets the Display unit case's column kind to `Measure`. Mutation: the `Measure` branch passing the typed text through — `"0,3 kg"` reaches the wire unchanged. + +- [ ] **Step 9: Fixture.** `bench::WideTableSource` owns a registry of three dimensions and ten units — mass `kg` 1, `g` 1/1000, `mg` 1/1'000'000, `t` 1000; volume `l` 1, `ml` 1/1000, `m3` 1000; ratio `""` 1, `percent` 1/100, `permille` 1/1000 — exposes it as `std::shared_ptr units() const`, and `m000`...`m009` become `ColumnKind::Measure` (role `Measure`, `dimensions` empty) holding `Measure` cells drawn over those units from the same `cellBits(seed, id, row)`; `"wide table: the column mix is the spec's"` keeps counting them as the 10 measures. The call sites that now need the registry (each passes `source.units()` / `.get()`): + - `bench::WideTableModel`'s three `ServedTable`s `wide`, `small`, `scoped` (Part A, Task 2): `services.units = source->units()`, so `DescribeTable` fills `units` and `answerQuery` writes measures; + - Part A's `"generic page"` cases that write a `WideTableSource{1'000, 30, 7}` page with an empty column list (the 30 layout holds `m000`): `writeGenericPage(…, source.units().get())`; + - `tests/table/bench_table.cpp`: the `[.benchmark][wire]` cases (W1, W2, W7) and every `apply`/`Engine` over a `WideTableSource` whose query sorts, filters or writes an `m` column; + - the rest found by `grep -rn "WideTableSource\|WideTableModel" tests` — each `ApplyOptions`/`EngineOptions`/`ServedTable` built over the fixture gets `services.units = source.units()`, whether or not it touches an `m` column today, so a later query cannot hit `SourceContract`. + +- [ ] **Step 10: Run** `cmake --build --preset cl-debug --target morph_table_tests morph_tests`, then `ctest --test-dir build/cl-debug -R "measure|units|generic page|wide table|over the bridge" --output-on-failure`, then `-R "table|views"`; expected: all pass. `morph_net_tests` (the wide model over a socket) is POSIX-only: run `-R "push"` on `linux-everything` before merging. + +- [ ] **Step 11: Mutations.** (a) `KeyColumn` storing `amount` instead of `amount * factor`: `"300 g sorts between…"` fails. (b) `compareKeys` negating the place comparison under `Descending`: the same case's descending line fails. (c) `ne` returning `false` across dimensions: `"filters compare base amounts…"` fails on `ne("250 g")`. (d) `forColumn` dropped and `find(info(unit).id)` per cell: M5 fails. (e) the level cache skipping the lineage check: the level-cache case fails. (f) `readGenericPage` with `units == nullptr` returning `SourceContract` instead of resolving through `registryOf(description)`: `"generic page: a measure round-trips"` fails on the no-registry read. (g) the group value index keyed by amount without the place: `"measure: a group of measure columns filters by base amount"` fails on its first `CHECK`. (h) `inferColumnKind` testing `x-measure` after its `num`/`den` rule: `"measure: typed rows carry their unit by id"` fails on the kind. (i) `detail::serve` leaving a typed table's `served.services.units` null: `"typed table: a model's units reach its measures"` fails. Paste each; revert. + +- [ ] **Step 12: Timings M1–M4.** `TEST_CASE("table benchmark: values with units", "[.benchmark][table][measure]")`: 100,000 rows from `std::mt19937{7}`, one `Measure` column over the fixture registry (three dimensions, ten units) and a `Quantity` column of the same amounts converted by factor; M1 keys and sort of each; M2 `gt "250 g"` against the quantity column's `gt "0.25"`; M3 compile 1,000 operands with units, and `ui::parseMeasure` of 1,000 typed texts; M4 `distinctValues` on the measure column against a decimal column. Write the figures into table.md "Benchmarks: values with units". + +- [ ] **Step 13: Confirm table.md states that no units are in the schema** (see Decisions). The spec is not edited: "Values with units" already says "The row's schema marks the property `x-measure` and lists no units", and its bullet "**A client learns units from the table's description**" says "A typed row's schema carries none either; it marks a measure's property `x-measure` only." + - Check: `grep -n "x-units" docs/spec/table/table.md` prints nothing, and `grep -rn "x-units" docs/spec include` prints nothing. + +- [ ] **Step 14: Docs build; commit** `feat(table): values with units` (the M1–M4 figures of Step 12 in table.md in the same commit). + +--- + +### Task 8d: Column layout — widths, pinning and the fitting rule + +**Spec:** "Columns: order, visibility, pinning, width" (the `ColumnLayout` paragraph and "A layout survives a changed table"); "Configuring a table" (the `layout` value's shape); "Column groups" (a user-formed group in the layout, fitted with it); "Display" (`"units"` in the layout); invariant 26 (engine half); Tests row "Column layout" (engine half; gate D8 is Task 10's). + +**Files:** +- Modify: `include/morph/table/engine.hpp` (`ColumnLayoutValue`, `ColumnLayout`) +- Modify: `tests/table/test_table_columns.cpp` (new cases), `tests/table/test_table_engine.cpp` (the existing `rebuild` expectation) + +**Interfaces:** +- Consumes: `ColumnGroupInfo` from `data_source.hpp`, where 8b moved it (8d lands after 8b; `engine.hpp` already includes `data_source.hpp` and gains no include). +- Produces: + ```cpp + /// The stored shape of a layout: {"order", "hidden", "pinned", "widths", "groups", "units"}. + struct ColumnLayoutValue { + std::vector order; + std::vector hidden; // in display order + std::size_t pinned = 0; + std::map widths; // column id -> width in units, > 0 + std::vector groups; // user-formed groups + std::map> units; // column -> dimension -> unit id + [[nodiscard]] bool operator==(ColumnLayoutValue const&) const = default; + }; + class ColumnLayout { + public: + explicit ColumnLayout(std::vector ids, std::vector declaredHidden = {}); + // existing: order(), visible(), setVisible(), move(), reset() + bool setWidth(std::string const& columnId, std::optional width); // false: unknown id or width <= 0 + [[nodiscard]] std::map const& widths() const noexcept; + void setPinned(std::size_t n); // clamped to visible().size() + [[nodiscard]] std::size_t pinned() const noexcept; // the first n of visible() + [[nodiscard]] ColumnLayoutValue value() const; + void apply(ColumnLayoutValue const& value); // the fitting rule + void rebuild(std::vector ids, std::vector declaredHidden = {}); + }; + ``` + +- [ ] **Step 1: Write the failing tests** in `test_table_columns.cpp` (header mutation lines: "`apply` ignoring `hidden`: `a stored layout is fitted to the table` fails"; "`rebuild` appending a new column last: `a new column takes its declared place` fails"): + +```cpp +TEST_CASE("column layout: a stored layout is fitted to the table", "[table][layout]") { + ColumnLayout layout{{"id", "name", "a", "new", "b"}}; + layout.apply(ColumnLayoutValue{ + .order = {"b", "ghost", "name", "id", "a"}, .hidden = {"ghost", "a"}, .pinned = 9, + .widths = {{"name", 24}, {"ghost", 10}}, + .groups = {{.id = "g1", .label = "Company", .columns = {"a", "ghost", "b"}}, + {.id = "g2", .label = "X", .columns = {"ghost", "name"}}}, + .units = {{"a", {{"mass", "g"}}}, {"ghost", {{"mass", "kg"}}}}}); + auto const v = layout.value(); + CHECK(v.order == std::vector{"b", "name", "id", "a", "new"}); // "new" after its declared predecessor "a" + CHECK(v.hidden == std::vector{"a"}); + CHECK(layout.visible() == std::vector{"b", "name", "id", "new"}); + CHECK(v.pinned == 4); + CHECK(v.widths == std::map{{"name", 24}}); + REQUIRE(v.groups.size() == 1); + CHECK(v.groups[0].columns == std::vector{"a", "b"}); + CHECK(v.units == std::map>{{"a", {{"mass", "g"}}}}); +} + +TEST_CASE("column layout: every column hidden shows the first declared column", "[table][layout]") { + ColumnLayout layout{{"id", "name"}}; + layout.apply(ColumnLayoutValue{.order = {"name", "id"}, .hidden = {"name", "id"}}); + CHECK(layout.visible() == std::vector{"id"}); +} + +TEST_CASE("column layout: a new column takes its declared place", "[table][layout]") { + ColumnLayout layout{{"new0", "new1", "id", "name", "new2"}}; + layout.apply(ColumnLayoutValue{.order = {"name", "id"}}); + CHECK(std::vector(layout.order().begin(), layout.order().end()) == + std::vector{"new0", "new1", "name", "new2", "id"}); // new0 first (no placed predecessor), + // new1 after new0, new2 after name + ColumnLayout grown{{"a", "b", "c"}}; + grown.move("c", 0); + grown.rebuild({"a", "b", "x", "c"}); + CHECK(std::vector(grown.order().begin(), grown.order().end()) == + std::vector{"c", "a", "b", "x"}); +} + +TEST_CASE("column layout: widths and pinning", "[table][layout]") { + ColumnLayout layout{{"a", "b", "c"}, {"c"}}; + CHECK(layout.visible() == std::vector{"a", "b"}); // declared hidden + CHECK(layout.setWidth("a", 30)); + CHECK_FALSE(layout.setWidth("zzz", 30)); + CHECK_FALSE(layout.setWidth("b", 0)); + CHECK(layout.widths() == std::map{{"a", 30}}); + CHECK(layout.setWidth("a", std::nullopt)); + CHECK(layout.widths().empty()); + layout.setPinned(5); + CHECK(layout.pinned() == 2); + CHECK(layout.setVisible("b", false)); + CHECK(layout.pinned() == 1); // clamped as visibility changes + layout.setWidth("a", 12); + layout.reset(); + CHECK(layout.visible() == std::vector{"a", "b"}); + CHECK(layout.widths().empty()); + CHECK(layout.pinned() == 0); +} + +TEST_CASE("column layout: the stored shape round-trips as JSON", "[table][layout]") { + std::string json; + REQUIRE_FALSE(glz::write_json(fitted.value(), json)); + ColumnLayoutValue back; + REQUIRE_FALSE(glz::read_json(back, json)); + CHECK(back == fitted.value()); + CHECK_FALSE(glz::read_json(back, std::string{R"({"order":["a"],"hidden":[],"pinned":1,"widths":{"a":24}})"})); // groups, units absent +} + +TEST_CASE("column layout: a stored layout that repeats itself", "[table][layout]") { // Review Focus 5 + ColumnLayout layout{{"a", "b", "c"}}; + layout.apply(ColumnLayoutValue{.order = {"b", "a", "b", "c"}, .pinned = 40, + .widths = {{"a", 0}, {"b", -5}, {"c", 8}}, + .groups = {{.id = "g", .label = "G", .columns = {"a", "a", "c"}}}}); + CHECK(layout.value().order == std::vector{"b", "a", "c"}); + CHECK(layout.value().widths == std::map{{"c", 8}}); + CHECK(layout.pinned() == 3); + CHECK(layout.value().groups[0].columns == std::vector{"a", "c"}); +} +``` + +- [ ] **Step 2: Update** `"table: a column layout keeps one column visible and resets"` in `test_table_engine.cpp`: after `rebuild({"b", "c", "d"})` the order is `{"c", "d", "b"}` (d after its declared predecessor c) and `visible()` is `{"c", "d"}`. + +- [ ] **Step 3: Run; the new cases fail to compile** (`ColumnLayoutValue` undeclared), and the updated engine case fails on the order line. + +- [ ] **Step 4: Implement** in `engine.hpp`. `glz::meta` is not needed for `ColumnLayoutValue` (reflection), and reading leaves an absent member at its default. One function fits every input; `apply(value)` runs it with the current declared ids, `rebuild(ids, declaredHidden)` replaces the declared ids and declared hidden set and runs it on `value()`, `reset()` sets order to the declared ids, hidden to the declared hidden set, clears widths and `pinned`, and keeps `groups` and `units`: + +```text +fit(value, D = declared ids): + order = ids of value.order that are in D, first occurrence only + for d in D, in declared order, if d not in order: + p = nearest id before d in D that is in order + insert d right after p, or at the front when there is none + hidden = ids of value.hidden in D, listed in `order`'s order, + plus each unmentioned column that is declared hidden (it takes its declared visibility) + widths = entries of value.widths with id in D and width > 0 + groups = each group with its columns filtered to D, duplicates and columns an earlier group holds removed; + groups with < 2 or > 16 columns, or an earlier group's id, dropped + units = entries of value.units with column id in D + if D is not empty and no column of order is visible: show D[0] + pinned = min(value.pinned, number of visible columns) +``` + + `setVisible` and `rebuild` re-clamp `pinned`; `pinned()` counts the first visible columns of `order`. + +- [ ] **Step 5: Run** `ctest --test-dir build/cl-debug -R "column layout" --output-on-failure`; expected: all pass, the two existing engine layout cases included. + +- [ ] **Step 6: Mutations.** (a) `fit` taking `hidden` as empty: `"a stored layout is fitted to the table"` fails. (b) the new-column loop appending at the end: `"a new column takes its declared place"` fails. (c) `pinned` not clamped: `"widths and pinning"` fails at `pinned() == 2`. (d) `fit` showing every unmentioned column: `"a declared-hidden column a rebuild adds stays hidden without a reset"` fails. (e) `fit` keeping a group of 17 columns: `"user-formed groups are fitted to the group rules"` fails. (f) `reset` clearing the user-formed groups: `"reset keeps groups and units"` fails. Paste each; revert. (The three cases of (d)–(f) are in `test_table_columns.cpp` beside Step 1's: a rebuild adding a declared-hidden column; `reset` after a layout with a group and a unit; a stored layout with a 17-column group, a repeated id, a column two groups claim and a group left with one column.) + +- [ ] **Step 7: Docs build; commit** `feat(table): widths, pinning and fitting in the column layout`. + +--- + +## Self-review + +- **Spec coverage.** Value-set operator (8a Steps 1, 5, 6); its limits and wire bound D6 (8a Step 2); distinct values — which rows, which values, unloaded, order and bound, dates, levels (the column is read for every candidate, through `apply`'s key building), client mode, server mode, validation, caching (8a Steps 3, 7, 8); column groups — declaring, user-formed groups (fitted in 8d), the filter and its JSON, both truth tables, `Together`, excludes, the pooled values list, `x-column-group` (8b); values with units — registry, lineage, tombstones, unit-id rule, ratio, wire, typed rows, order, filters, `parseMeasure`, values list (8c); display units per dimension are stored by 8d and drawn by Task 15; the layout (8d). The menu halves, D7, D8 and D9 are Tasks 10 and 12, as the roadmap assigns. Neighbouring specs for step 3: `../forms/views.md` (8b Step 8); `engine.md`'s fitting-rule row is step 4, not here. +- **The server path.** Each of 8a, 8b and 8c has a case that calls `detail::answerQuery` (a distinct request, a declared group, a typed table's measures), because `apply` is not what a `Table.` request runs. +- **Type consistency.** `Engine::distinctValues` is declared in `engine.hpp` and defined in `query.hpp`, beside the core it shares with the free function; `FilterCounters` is introduced in 8a and used by 8b; `ValueSet` in 8a, extended to measures in 8c; `DistinctValue` gains `dimension`/`unit` in 8c only; `ColumnGroupInfo` moves to `data_source.hpp` in 8b and is consumed by 8d, which lands after it; `GroupFilter`'s member order keeps the existing designated initializers valid. +- **Proportion.** Code blocks are tests and signatures; the only bodies are the group evaluation, the measure comparison and the fitting rule, which the spec fixes and the tests alone would not determine. diff --git a/docs/superpowers/plans/2026-11-17-one-table-d-screen.md b/docs/superpowers/plans/2026-11-17-one-table-d-screen.md new file mode 100644 index 000000000..c68475b4f --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-one-table-d-screen.md @@ -0,0 +1,2098 @@ +# The One Table, Part D: the Table on a Screen — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Put every table of a screen on the one pipeline: `TableRows` with its two implementations, the model-backed `table` node lowered onto a `PageWindow`, persisted state loaded before the first rows, the column window in the mount and both backends, and `rows` tables ordered by the engine. + +**Architecture:** `include/morph/ui/table_rows.hpp` holds `TableRows`, `EngineRows`, `WindowRows` and `ValueRowsSource`; `include/morph/table/state_store.hpp` holds the store interface and the state document's reader, writer and fitting; `include/morph/ui/table_state.hpp` and `table_state_model.hpp` hold the preferences-backed store and its server model. The interpreter lowers a table node onto a `TableRows` and hands it to the mount through a new `ui::Table::source`; the mount realizes rows by view index and, from Task 10, columns through `ColumnExtents`, cell pools and a per-frame budget. The interpreter's own sort and page are removed in Task 11. + +**Tech Stack:** C++23, CMake presets `cl-debug` (core, `morph_tests`, `morph_table_tests`, `morph_net_tests`) and `cl-qt-debug` with `-DMORPH_BUILD_QT_QUICK=ON -DMORPH_BUILD_TUI=ON` (for `morph_qt_quick_tests`, `morph_tui_tests`), Catch2, glaze, Qt 6 Quick offscreen. + +**Spec:** `docs/spec/table/table.md`: "The pipeline", "Sources", "A document's rows as a source", "The client table model", "The renderer" (all subsections), "Every surface on the pipeline" → "The document `table` node on the engine", "What the interpreter does for a table", "The status line" (counts), "Persisted state" (interface, "The framework's stores", load before the first rows, saving sort and filters), "Where sort and filter run"; the matching rows of "Tests" and "Invariants" (16 to 21, 26 to 28, 31); gates U1–U8, K5, K8, F1–F10, T1, T3–T5, D8, W6, B1; "Neighbouring specs" rows for steps 4, 5 and 6; "Delivery order" steps 4, 5, 6. Roadmap: `docs/superpowers/plans/2026-11-17-one-table.md` (Tasks 9, 10, 11). + +Part D of 7; index: 2026-11-17-one-table.md + +## Global Constraints + +- Everything in the roadmap's Global Constraints and its standard task loop applies; this plan lists only what is specific to its tasks. +- Limits, verbatim: `Virtualization{threshold = 2000, overscan = 10, columnThreshold = 40, cellThreshold = 20'000, columnOverscan = 4, realizePerFrame = 240}`; `SessionOptions::tableStateTimeout = 300 ms`, `tableStateDebounce = 500 ms`, `tableSettle = 80 ms`, `tableAwaitedRefetch = 250 ms`, `maxRangeRows = 10'000`; `TableStateOptions::segmentBytes = 12 KiB`; a `save` part and a `load` head are at most 1 MiB, an envelope 8 MiB; a key member is 1 to 256 bytes; `PageWindow(pageSize = 200, maxPages = 8, maxKeys = 1000, maxColumns = 96)`; a status-line message lasts 6 s or until the next gesture on the table; client mode is bounded at 20,000 rows or 1,000,000 cells. +- Comments and specs state what the code does now and why; no history, no issue numbers (AGENTS.md). +- Count gates are ordinary tests. Timings carry the tag `[.benchmark]`, never gate CI, and are written into table.md's Performance tables with machine and load. +- No GUI application is launched. Qt Quick behaviour is tested only through the offscreen `morph_qt_quick_tests` (`QT_QPA_PLATFORM=offscreen`). +- Neutral domain only: test models and documents use `Lims_SampleModel`, table id `samples`. +- Test support (cross-part decision 42). `tests/ui_table_support.hpp` holds two types in `morph::ui::testing`, beside the existing `Harness` of `tests/ui_interpreter_support.hpp`, which is not edited. `RowsFixture` (9a) is what a `TableRows` test needs with no screen: `owner` (`StepExecutor`), `runtime`, `scheduler` (`ManualScheduler`), `session` (its `SessionOptions::catalog` is `tableCatalog()`, and its constructor calls `session.setLocale("en")`), `dispatcher` (`ScriptedDispatcher`), `settle()`, `advance(ms)`. `TableHarness` (9d) derives from it and adds `host` (`RecordingHost`), `backend` (`RecordingBackend`), `diagnostics` (a `std::vector` data member), `interpreter`, and `mount(text)`, which loads against `tableCatalog()`. Every helper is a free function taking the fixture (`lastQuery(h)`, `statusOf(h)`, `replyDescribe(h)`, `replyPage(h, json)`, …). A header click is the existing `h.backend.clickHeader(table, column)` (`recording_backend.hpp`), `table` being `h.backend.find("Table", "testId", …)` and `column` an index into `Table::columns`. +- Every test document is whole and names its model by an alias: `kModelTable` is `{"vocab":"ui/1","id":"samples","models":{"lab":{"type":"Lims_SampleModel"}},"view":{"kind":"table","id":"list","testId":"list","model":"lab","table":"samples","empty":[{"kind":"text","text":"No samples"}]}}`. +- A `column` argument is an index into `Table::columns`, which holds every column, hidden ones included, and does not change with the layout; only a `position` is a visible place (cross-part decision 37). +- `ui::Table` and `ui::TableOptions` (`view.hpp:2026`) are parallel structs: every member a task here adds to `Table` it adds to `TableOptions`, and the lowering fills both (cross-part decision 41). +- Equality (cross-part decision 38): `FilterEntry`, `ColumnFilter`, `GroupFilter` and `ColumnCount` have `operator==` from Part C's 8b; every struct this part adds that is compared or sits in a `Prop` declares its own. +- `table::UnitInfo` (Part C) and `ui::UnitInfo` (`ui/expression.hpp:307`) are different types with one name: code in `namespace morph::ui` always writes `table::UnitInfo`, `table::UnitRegistry`. +- `table::readGenericPage(json, description)` is called with no registry: Part A resolves a page's units through `registryOf(description)`. +- Qt Quick and terminal suites need their options; configure once with + `cmake --preset cl-qt-debug -DMORPH_BUILD_QT_QUICK=ON -DMORPH_BUILD_TUI=ON` and build/run there: + `cmake --build --preset cl-qt-debug --target morph_qt_quick_tests morph_tui_tests`, + `ctest --test-dir build/cl-qt-debug -L qt_quick -R "" --output-on-failure` (the `qt_quick` label sets `QT_QPA_PLATFORM=offscreen`), `ctest --test-dir build/cl-qt-debug -R "" --output-on-failure` for `morph_tui_tests`. + +## Interfaces assumed from Parts A–C + +The roadmap names these; it does not pin their exact signatures. This plan uses the spec's signatures where the spec gives them and the shapes below where it does not. An implementer finding a different shape in the landed code uses the landed one and fixes this list. + +| From | Used as | +|---|---| +| Task 0, 2 | `bench::WideTableOptions`, `bench::WideTableSource`; `bench::WideTableModel` (registered type `bench::kWideModelType`, `"WideTableModel"`, set up with `WideTableModel::configure(WideTableOptions wide, WideTableOptions small)`), so the fixture's records are `WideTableModel.wide` and `WideTableModel.small`; the library `morph_wide_table_model` linked into `morph_tests`, `morph_net_tests` and `morph_qt_quick_tests`; B5's browser harness `tests/qt_quick/wasm/` run with `emrun`. | +| Task 1 | `TableQuery::columns` (`std::optional>`, absent: every column; cross-part decision 2), `table::TableColumn`, `table::TableDescription` (with `capabilities`, as the spec's block has it), `table::GenericRow`, `table::GenericPage`; `table::readGenericPage(std::string_view, TableDescription const&) -> std::expected`; glaze metadata for `TableDescription` so a reply's JSON reads with `glz::read_json`. | +| Task 2 | Action ids `Table.` and `Table..describe`; the record `.` (here `Lims_SampleModel.samples`); its catalog entry marks `Table.` opaque (`ActionRecordInfo::opaque`). | +| Task 4 | `TableQuery::keys` (`std::optional>`), `table::UnloadedLevels{std::span levels; std::span failed;}` (views into the window: copy before the window changes); `GenericPage::{unloadedRows, undecided, awaiting, failed, indices}`. | +| Task 5 | `table::rowIdOf(glz::raw_json const&) -> std::optional` (and its inverse `changeKeys(std::span) -> std::vector`, not used here). `effects::RecordChange::keys` absent is a whole-type change. | +| Task 7 | `Session::watchRecord`, `CallOptions::stop` and `Session::read(channel, actionId, body, stop) -> async::Completion` (7b; resolves with the reply's JSON text, cross-part decision 30; `WindowRows` sends every fetch through it, see 9a's "Decoding replies"), and `PageFetch`, `RowsFetch`, `Refresh`, `RefreshPlan` and the `PageWindow` members exactly as table.md "The window under changes" and "The client's caches" declare them; `PageWindow(pageSize, maxPages, maxKeys, maxColumns)` (no key function), `bool accept(PageFetch const&, GenericPage)` (`false`: ignored), `std::vector patch(RowsFetch const&, GenericPage)`, and the accessors of cross-part decision 8: `RowId const* key(std::int64_t)`, `Cell const* cell(std::int64_t, std::string_view column)`, `bool holds(std::int64_t, std::string_view column)`, `std::uint64_t revision()`; plus `unloadedLevels(index)`, `undecided()`, `awaiting()`, `failed()`, `total()`, `totalKind()`, `error()`, `pending()`. `WindowRows` reads rows only through these. | +| Task 8d | `ColumnLayout::value() -> table::ColumnLayoutValue{order, hidden, pinned, widths, groups, units}` and `apply(ColumnLayoutValue const&)` (cross-part decision 7); its JSON is the spec's `layout` shape. | +| Task 15 | `ui::formatCell(table::Cell const&, table::TableColumn const&, ui::FormatContext const&, DisplayUnits const& = {}) -> std::string` (cross-part decision 9), which replaces this plan's stand-in. | + +## Review Focus + +1. **A description that changes revision while state is held** (roadmap item 1). A sort key, a filter and the fetched columns naming column `c` when a page reply carries a new `revision` whose description lacks `c`: the client refetches the description once, drops the key and the filter (the filter reported once; a dropped sort key is not reported, as 9b has it), mounts the table again from the new description, and the next query names neither `c` nor its level. A view selection and a cell draft do not exist before Tasks 17a and 24; those tasks extend this test. Test: Task 9d. +2. **The table unmounted while its state load or a fetch is in flight.** A screen closed before a held load completes, then the load released: nothing is applied, no query is sent, no handler runs on a destroyed table, and the debounced save of a changed state goes out at once on unmount. Test: Task 9d. +3. **A stored document that is not JSON, or of a version the framework does not know.** The table starts from its defaults, the problem is reported once at the table's path, nothing is written until the user changes something, and then the framework's version overwrites it. Tests: Task 9b (the parser), 9c (the store's merge) and 9d (the table). +4. **An empty model-backed view.** Before the first reply, and while rows are undecided, the node's `empty` content is not shown and the status line says the table is loading or counts "0 so far, N loading"; after a reply with `total: 0, totalKind: exact, undecided: 0` it is shown and the count reads "0 rows". Test: Task 9d. +5. **Rows with a duplicate key in a `rows` table.** Three rows with keys 1, 2, 1: the table shows two rows, the first occurrence of key 1 in the engine's order, the duplicate is reported as the mount reports it today (`site::kDuplicateKey`, once per duplicate), and a sort never brings the second row back. Test: Task 11a. + +--- + +## File map + +| File | Task | Holds | +|---|---|---| +| `include/morph/ui/table_rows.hpp` (new) | 9a, 11a | `TableTotal`, `TableRowRef`, `TableCountsView`, `TableRows`, `EngineRows`, `WindowRows`, `WindowRowsOptions`, `WindowRowsStats`, `cellValue`, `countsText`, the stand-in cell text, `RowRecord`, `RecordOf` (`ui::SortChain` is `table_config.hpp`'s, Task 12a); `ValueRowsSource`, `kGroupRunColumn`, `EngineRows::setRestoring` (11a, 11b); `readTypedPage`, `WindowRowsOptions::{action, queryMember}` (11c) | +| `include/morph/table/state_store.hpp` (new) | 9b | `TableStateKey`, `StoredTableState`, `SaveOutcome`, `SaveResult`, `ITableStateStore`, `MemoryTableStateStore`, `StateDocument`, `readState`, `writeState`, `fitState`, `FitReport` | +| `include/morph/ui/table_state.hpp` (new) | 9c | `PreferencesTableStateStore`, `TableStates` (the session's kept states, load batching, save debounce) | +| `include/morph/ui/table_state_model.hpp` (new) | 9c | `TableStateModel` (`morph.tableState`), its request types, `TableStateOptions`, `registerTableState` | +| `include/morph/ui/view.hpp` | 9d, 10a | `TableSource`, `TableRowLook`, `CellLoad`, `Table::source`, `Table::status`, `TableStatus`, `TableColumn::id` (9d); `Virtualization` additions, `Table::arrangement`, `Table::highlightKey` (10a) | +| `include/morph/ui/mount.hpp` | 9d, 10a | rows by view index from `TableRows`; `ColumnExtents`, `windowingOf`, the column window, cell pools, the frame budget, focus by key and column | +| `include/morph/ui/backend.hpp` | 9d, 10a | `TableWidget::setStatus`, `setColumnWindow`, `setOnHorizontalRange`, `setOnSelectRange`, `setFocusCell`, `setCounts` | +| `include/morph/ui/testing/recording_backend.hpp` | 9d, 10a | records the new table calls; `scrollTableColumns`, `selectTableRange` | +| `include/morph/ui/interpreter.hpp`, `src/ui/interpreter.cpp` | 9d, 10a, 11b, 11c | `SessionOptions` members; the lowering of both table kinds onto `TableRows`; `RtScope::onMissingRowField` | +| `src/qt_quick/table.cpp`, `src/qt_quick/qml/MorphTable.qml` | 10b | the column window, pinned columns, pools, the status line | +| `src/tui/table_widget.cpp`, `.hpp` | 10b | the column range, the status line | +| `src/ui/document.cpp` | 9d, 11b, 11c | the loader: a table's keys `table`, `status`, `persist`, `model` + `table` without `action` (9d); a column's `kind`, the `persist`-without-`id` refusal (11b); the `model` + `action` refusals (11c) | +| `include/morph/ui/preferences.hpp` | 9c | `PreferencesModel` refuses the names table state reserves | +| `tests/ui_table_support.hpp` (new) | 9a, 9d | `RowsFixture`, `WindowRowsProbe`, `TestRowsSource`, the test catalog, description and page builders (`pageJson`, `pageJsonAt`, `keyedJson`) (9a); `GatedTableStateStore` (9c); `TableHarness` and the screen helpers (9d) | +| `tests/test_ui_document.cpp` | 9d, 11b | the loader cases | +| `tests/test_ui_table_model.cpp` (new), `tests/test_ui_table_state.cpp` (new) | 9 to 11 | in `morph_tests` | +| `tests/table/test_table_state.cpp` (new) | 9b | in `morph_table_tests` | + +--- + +### Task 9: `TableRows` and the model-backed table on a screen (table.md step 4) + +Four commits, each its own reviewer gate. + +#### 9a — `TableRows`, `EngineRows` and `WindowRows` + +**Files:** +- Create: `include/morph/ui/table_rows.hpp`, `tests/ui_table_support.hpp`, `tests/test_ui_table_model.cpp` +- Modify: `tests/CMakeLists.txt` (add `test_ui_table_model.cpp`, and in 9c `test_ui_table_state.cpp`, to `add_executable(morph_tests …)`), `include/morph/ui/interpreter.hpp` (`SessionOptions` members below) + +**Interfaces:** +- Consumes: Task 7's `PageWindow`, `Session::read` (the reply's JSON text on the owner; no cache entry; a stop settles it cancelled), `Session::watchRecord`; Task 1's description and generic page; Task 5's `rowIdOf`; `table::Engine` (existing: `setSort`, `setFilter`, `viewRowCount`, `rowIdAt`, `sourceRowOf`, `onViewChange`, `pending`). +- Produces (namespace `morph::ui`, every member as table.md "The client table model" declares it): + +```cpp +// `ui::SortChain` is `table_config.hpp`'s alias (Task 12a); this header includes it and declares no other. +struct TableTotal; // rows, kind, known +struct TableRowRef; // key, row +struct TableCountsView; // view, source, undecided, pending, awaiting, failed +class TableRows; // total, row, unloadedLevels, visible, keysOf, setSort, setFilter, counts, onChange +// `onChange` is a single slot (cross-part decision 40): a call replaces the handler, and the mount is what sets it. +// Whatever else needs a source's changes wraps the `TableRows` in a forwarding decorator and hands the wrapper to +// the mount. Its Doxygen says so. + +/// A row's key and its record, owned (cross-part decision 28). +struct RowRecord { table::RowId key; Value row; }; +/// What EngineRows reads a row's key and record through: its source's snapshot and a source row. +using RecordOf = std::function; +class EngineRows final : public TableRows { +public: + EngineRows(std::shared_ptr source, RecordOf recordOf, table::EngineOptions options); + [[nodiscard]] table::Engine& engine() noexcept; + [[nodiscard]] std::size_t recordsBuilt() const noexcept; // calls of recordOf, for the memo's test +}; + +struct WindowRowsOptions { + std::shared_ptr channel; // the model's channel + std::string table; // the table id: actions "Table.
", "Table.
.describe" + std::string record; // ".
", watched for the window's life + Value body; // the node's `body`, the query's fixed part + std::int64_t pageSize = 200; + std::size_t maxPages = 8; + std::size_t maxKeys = 1000; + std::size_t maxColumns = 96; + bool restoring = false; // sends no query until `release` +}; +struct WindowRowsStats { + std::size_t pageFetches = 0; // page and column fetches sent + std::size_t rowsFetches = 0; // keyed fetches sent + std::size_t cancelled = 0; + std::size_t cellsConverted = 0; // cells turned into a row record's fields (K8) +}; +class WindowRows final : public TableRows { +public: + WindowRows(Session& session, WindowRowsOptions options); + void setDescription(table::TableDescription description); // fits sort, filters and columns to it + void setDescription(Value const& described); // the describe entry's value; one that does not read sets error() + [[nodiscard]] table::TableDescription const* description() const noexcept; + void onStaleDescription(std::function handler); // a reply named another revision + void release(); // leaves the restoring state: the first query + void retry(); // the query again with `TableQuery::retry` + [[nodiscard]] std::optional const& error() const noexcept; + [[nodiscard]] WindowRowsStats const& stats() const noexcept; + // Added by Part G's Task 24 (cross-part decision 35), not by this part: + // void onRowsAbsent(std::function)> handler); // keys a keyed fetch named and its reply holds no row for +}; + +/// A cell as the document reads it. +[[nodiscard]] Value cellValue(table::Cell const& cell, table::ColumnInfo const& column); +/// The status line's counts part. +[[nodiscard]] std::string countsText(TableCountsView const& counts, std::int64_t selected, FormatContext const& format); +namespace detail { +/// The text of a cell until `ui::formatCell` lands (Task 15 replaces every call). +[[nodiscard]] std::string standInCellText(table::Cell const& cell, table::TableColumn const& column); +} +``` + +`ui::SortChain` is already declared in `ui/table_config.hpp` (Part E's Task 12a, which landed first) as `using SortChain = table::SortChain;`. Task 9a includes that header and reuses the alias rather than declaring it again. + +- `SessionOptions` gains `std::chrono::milliseconds tableSettle{80}`, `std::chrono::milliseconds tableAwaitedRefetch{250}` (this commit) and, in 9c, `std::shared_ptr tableState`, `std::chrono::milliseconds tableStateTimeout{300}`, `std::chrono::milliseconds tableStateDebounce{500}`, `std::string application` (the `application` of every table-state key). + +Decisions the signatures do not carry: + +- `EngineRows` memoises `RecordOf`'s result per source row of the engine's `viewSnapshot()`; the memo is dropped for the rows an `Updated` names and whole on a new snapshot of `Reset`. `row(index)` returns a `TableRowRef` whose references point into the memo and hold until the next `onChange`. +- Decoding replies. Every page, keyed and column fetch is sent as `session.read(options.channel, "Table." + table, body, token)` (cross-part decision 30): no cache entry is made, no effect is applied, and the fetch's stop token cancels it. `Session::read` resolves with the reply's **text**, which `WindowRows` decodes as `table::readGenericPage(text, *description())`; a reply is never read into a `Value`, because `ui::valueFromJson` (`value.hpp:570`) refuses every JSON number with a fraction or an exponent ("a number with a fraction is not exact"), so a page holding one `Number` cell (`2.5`, `1e308`, `-0.0`) would fail whole. The description is read from the `Table.
.describe` query entry (W6), whose `Value` is lossless for a description — every number in one is an integer or a `math::Rational` written as `{"num","den","dp"}` (`rational.hpp:1747`), which `valueFromJson` reads as a `Decimal` and `valueToJson` writes back unchanged — as `glz::read_json(ui::detail::canonicalJson(value))` (`interpreter.hpp:410`). A description that does not read sets `error()` to `TableError{.code = InvalidValue}` and sends no page fetch. +- `cellValue`: empty and unloaded → `null`; `int64` in `Integer`/`Key` → `Int`; in `Date` → the `String` `YYYY-MM-DD`; in `DateTime` → `Timestamp` of seconds × 1000 ms; `Rational` → `Decimal{rational}` (its places kept); `double` → `Decimal` parsed by `table::parseDecimal` from the text `std::to_chars(first, last, value, std::chars_format::fixed)` writes (the shortest fixed-notation text that reads back as the same `double`, never an exponent, which `parseDecimal` refuses, `data_source.hpp:123`); a `double` that text does not parse for — non-finite, more than 18 fraction digits (`1e-20`), or a magnitude beyond an `int64` numerator (`1e308`) — is the `String` of `std::to_chars`'s shortest text (`"1e+308"`, `"inf"`), so the cell still shows its value and is never silently `null`, the rule cross-part decision 46 gives the query cache; text → `String`; `bool` → `Bool`; `QuantityCell` → `Decimal` of `amount × toCanonical`; a `Measure` (once Task 8c lands) → `Quantity{amount, unit id}`. +- `standInCellText` is `table::displayText(cell)`, and the empty string for an unloaded cell. +- `countsText`, numbers grouped with `format.numeric`'s separator: nothing known (`!view.known`) → `""`; `undecided > 0` → `" so far, loading"`; `selected > 0` → `" of selected"`, `` followed by `" or more"` under `AtLeast`; `AtLeast` → `" or more"`; otherwise `"1 row"` or `" rows"`. +- `WindowRows` row records: `row(index)` returns a record holding one field per column of the latest `visible(…, columns)` set for which `PageWindow::holds(index, column)`, each read with `cell(index, column)` and its key with `key(index)`, memoised per key until the row's cells change; `cellsConverted` counts each conversion. A record of a 300-column table of which twenty are named converts twenty cells. +- `WindowRows` timing: a fetch for a page held or adjacent to a held page goes at once, and so does the page of the first visible row while no page is held (the first query, and the one after a sort or filter); any other waits until `visible` has stayed within one page for `tableSettle`, measured on `SessionOptions::scheduler`; every `superseded()` fetch is cancelled through its stop token and handed to `cancelled`. While `awaiting()` is not empty, every event invalidates (table.md, "When a fetch is sent") and a refetch of a held page goes no sooner than `tableAwaitedRefetch` after the last one: the first after a quiet spell at once. +- `WindowRows` order of work: `watchRecord` first; the first page fetch only after it resolves, after `setDescription`, and (with `restoring`) after `release`. Its handler maps a change with `keys` to `refresh` of each key read by `rowIdOf` (a key that does not read invalidates), and a change without `keys` to `invalidate()`; after every `accept` it sends `owed()` and calls `visible` again. +- A reply whose `revision` differs from the held description's calls the `onStaleDescription` handler once per revision and is still accepted. +- `WindowRows`' change is the diff by key of the rows held before a reply against those held after it (table.md, "The client table model"): a new total moves the view's end (`Inserted`/`Removed` there), the reply's page is diffed by key (`Moved`, `Inserted`, `Removed`, and `Changed` for every held row of the page, whose cells were replaced), and an evicted page is `Changed` places. The operations are valid in sequence and never hold a key twice: a shrunk view loses its end before the page's diff, a grown view gains it after, and the diff covers the page's places both views have. A new query (sort, filter, description revision) is a `Reset`, and so is a page holding a key twice or a page diff over the `ViewChange` bound of 5,000 operations. Tests: a row that moves within its page is a move; a new total with the same keys moves the end; a row that came and a row that went are an insert and a remove; a page spanning a shrunk view's end, and one spanning a grown view's end. Each replays the change op by op, checking every op in bounds, the keys unique after each, `Changed` places read from the new view, and the end equal to the new view. +- `retry()`'s flag stays set until every fetch of that refetch has gone, one held back by `tableSettle` or `tableAwaitedRefetch` included. A keyed reply that does not read, and a keyed body that does not write, are handled as a failed keyed fetch: `error()` is set and the window invalidates. +- The client catalog keeps a table action's opaque holding: `ui::author::detail::recordsInfo` copies `ActionRecord::opaque`, tested through `recordsInfo` itself, which `CatalogFacts::action` uses (`"table catalog: a table's action holds its record opaquely in the client's catalog"`). `CatalogFacts::action` cannot name a table action, which is not a `Runs` action; 9d builds its catalog by hand and carries that gap. +- The reader bounds what the window indexes by: `table::readGenericPage` refuses (`InvalidValue`) a page whose `unloadedRows` index is outside its rows or not above the one before, or whose `indices` is neither empty nor one non-negative view row per row. Test `"generic page: unloaded rows and indices are bounded by the page's rows"` in `tests/table/test_table_description.cpp` (mutation: the check removed). +- Beyond the cases below, 9a tests a description that does not read (no page fetch), a reply of another revision (reported once, taken) and a change with keys (one keyed fetch that patches in place). + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_model.cpp`, over `RowsFixture` (Global Constraints; `h` below) and the helpers of `tests/ui_table_support.hpp`. `h.windowRows(table, description = samplesDescription(3))` returns a `std::shared_ptr` (a `WindowRows` is neither copied nor moved: its watch handler holds `this`) built with the fixture's channel, the description set and `release()` called, after answering the `watch`; `h.restoringRows(table)` is the same with `restoring = true` and no `release()`. `h.columns` is `h.columnIds(0, 3)`. `h.answerFirstPage(rows, total)` calls `rows.visible(0, 30, h.columns)` and answers every page fetch that causes — page 0, then page 1, which goes at once beside it — each with `pageJson(, 200, total, h.columns)`, so nothing is in flight afterwards (a page 1 left in flight would be superseded by the first scroll and counted in `cancelled`). `h.replyPage(json)` answers the oldest unanswered `Table.samples` call; `h.pending("Table.samples")` counts the unanswered ones; `h.stopped(index)` is whether call `index`'s `CallOptions::stop` was requested (`ScriptedDispatcher::Call` gains `::core::async::StopToken stop`, recorded from the options of `execute`, in Task 7b's change to that file; if it is not there, this commit adds it). `h.change(keys)` delivers an `effects::RecordChange` for `Lims_SampleModel.samples` with those keys to the session, as a `changes` event does. `tableCatalog()` (the corpus catalog plus `Table.samples` and `Table.samples.describe` on `Lims_SampleModel`), `samplesDescription(int columns)` (`id` Integer key, `name` Text, then `c3…` Decimal), `describeJson(TableDescription)`, `pageJson(offset, count, total, columns, TotalKind kind = Exact, std::int64_t undecided = 0, std::vector awaiting = {})` whose row keys are `offset + i` and names `"row-"`; `formatFor(std::string_view tag) -> FormatContext`, built from the locale table as `Session::scopedFormatting` builds one (`interpreter.cpp:777`): `LocaleFacts const& f = ui::localeFacts(tag);` then `FormatContext{.locale = std::string{tag}, .numeric = f.numeric, .currency = f.currency, .datePattern = std::string{f.datePattern}, .dateTimePattern = std::string{f.dateTimePattern}}` (`f.numeric` views static storage, `locale_table.hpp:78`). A default `FormatContext` has an empty `groupSeparator` (`render::NumericLocale{}`), and so does a `Session` until `setLocale` runs (`interpreter.hpp:598`), so `RowsFixture`'s constructor calls `session.setLocale("en")` (and only it: the existing `Harness` is untouched, cross-part decision 42): every count asserted through a screen ("9,093 rows", "100,000 rows") is grouped by the locale table, not by a default. `h.columnIds(first, count)` is the ids of the description's columns in order; `h.window(rows)` is a test accessor to the `PageWindow` (`WindowRows` befriends `ui_table_support`'s `WindowRowsProbe`). `TestRowsSource(n)` is a `table::DataSource` of `n` rows `{id: i, name: "row-"}` with `rename(row, name)` (notifies `Updated` for that row) and `recordOf()`; `valueToJsonText(value)` is `glz::write_json(valueToJson(value))`; `h.keysNow(rows, first, count)` calls `keysOf`, runs `h.settle()` once and returns the keys, failing the test when the completion has not delivered by then or a `Table.samples` call was made. + +```cpp +// Mutations: a fetch per `visible` call (the first CHECK: 19 calls); no cancel of `superseded()` (the `stopped` and +// `cancelled` CHECKs); an adjacent page waiting for the settle (the last CHECK). Gate K6. +TEST_CASE("window rows: a scroll that passes sends no fetch until it rests, and cancels what it left", "[ui][table]") { + RowsFixture h; auto const rows = h.windowRows("samples"); + h.answerFirstPage(*rows, /*total*/ 100'000); // pages 0 and 1 are held + std::size_t const before = h.dispatcher.count("Table.samples"); + for (std::int64_t at = 2'500; at < 50'000; at += 2'500) { rows->visible(at, 30, h.columns); h.advance(10ms); } + CHECK(h.dispatcher.count("Table.samples") == before); // inside tableSettle each time + h.advance(80ms); // rests at 47,500 + std::size_t const rested = h.dispatcher.count("Table.samples"); + CHECK(rested > before); CHECK(rested <= before + 3); // K6: at most three for a resting place + for (std::int64_t at = 50'000; at < 100'000; at += 2'500) { rows->visible(at, 30, h.columns); h.advance(10ms); } + h.advance(80ms); // rests at 97,500; the first rest is unanswered + for (std::size_t call = before; call < rested; ++call) { CHECK(h.stopped(call)); } // what it left is cancelled + CHECK(rows->stats().cancelled == rested - before); + std::size_t const second = h.dispatcher.count("Table.samples"); + CHECK(second > rested); CHECK(second <= rested + 3); + while (h.pending("Table.samples") > 0) { h.replyPage(pageJson(97'400, 200, 100'000, h.columns)); } + rows->visible(97'790, 30, h.columns); h.settle(); // into the page after a held one, no clock advance + CHECK(h.dispatcher.count("Table.samples") == second + 1); // at once +} +// Mutation: a refetch per event (the first refetch's reply is older than the events after it and is fetched again +// at once: the 249 ms CHECK counts two). A refetch in flight dedupes the events after it, so the first CHECK holds +// under the mutation; a view of one page keeps each refetch one fetch. +TEST_CASE("window rows: an awaited order is throttled", "[ui][table]") { + RowsFixture h; auto const rows = h.windowRows("samples"); + std::string const awaited = pageJson(0, 200, 200, h.columns, table::TotalKind::Exact, 0, {"recipe"}); + rows->visible(0, 30, h.columns); h.replyPage(awaited); // the order awaits `recipe` + std::size_t const before = h.dispatcher.count("Table.samples"); + for (std::int64_t key = 0; key < 10; ++key) { h.change({key}); h.advance(10ms); } // ten events in 100 ms + CHECK(h.dispatcher.count("Table.samples") == before + 1); // one, at the first event + h.replyPage(awaited); + h.advance(149ms); CHECK(h.dispatcher.count("Table.samples") == before + 1); // 249 ms after it + h.advance(1ms); CHECK(h.dispatcher.count("Table.samples") == before + 2); // tableAwaitedRefetch + h.replyPage(awaited); h.advance(1'000ms); + CHECK(h.dispatcher.count("Table.samples") == before + 2); // no event since: nothing more +} +// Mutation: build the record from every column the window holds for the row (converts 40, not 20). Gate K8. +TEST_CASE("window rows: a row of 300 columns converts the twenty it is asked for", "[ui][table]") { + RowsFixture h; auto const rows = h.windowRows("samples", samplesDescription(300)); + std::vector const forty = h.columnIds(0, 40); // id, name, c3 … c40 + std::vector const twenty = h.columnIds(0, 20); // the first twenty of them + rows->visible(0, 50, forty); + h.replyPage(pageJson(0, 200, 9093, forty)); // the window now holds 40 columns of row 0 + REQUIRE(h.window(*rows).holds(0, "c40")); // the precondition K8 needs: 40 held + std::size_t const sent = h.dispatcher.count("Table.samples"); + rows->visible(0, 50, twenty); h.settle(); + CHECK(h.dispatcher.count("Table.samples") == sent); // held already: no fetch + REQUIRE(rows->row(0).has_value()); + CHECK(rows->row(0)->row.asRecord()->size() == 20); + CHECK(rows->stats().cellsConverted == 20); // K8; the mutation converts 40 + static_cast(rows->row(0)); CHECK(rows->stats().cellsConverted == 20); // memoised +} +// Mutations: decoding through a `Value` (`ui::valueFromJson` refuses 2.5 and the page fails whole: `error()` is set); +// a double `parseDecimal` refuses read as `null` (the row 1 REQUIRE). +TEST_CASE("window rows: a page with a Number cell is read from the reply's text", "[ui][table]") { + RowsFixture h; + table::TableDescription d = samplesDescription(2); // id Integer key, then one more column + d.columns[1].info = table::ColumnInfo{.id = "ratio", .kind = table::ColumnKind::Number}; + auto const rows = h.windowRows("samples", table::describe(d)); + std::vector const columns{"id", "ratio"}; + rows->visible(0, 30, columns); + h.replyPage(R"({"revision":")" + rows->description()->revision + + R"(","columns":["id","ratio"],"keys":[1,2],"rows":[[1,2.5],[2,1e308]],"total":2})"); + REQUIRE_FALSE(rows->error().has_value()); + CHECK(rows->total().rows == 2); + REQUIRE(rows->row(0)->row.field("ratio")->asDecimal() != nullptr); // cellValue: double → Decimal + CHECK(valueToJsonText(*rows->row(0)->row.field("ratio")) == R"({"num":5,"den":2,"dp":1})"); + REQUIRE(rows->row(1)->row.field("ratio")->asString() != nullptr); // beyond a Decimal: its text + CHECK(*rows->row(1)->row.field("ratio")->asString() == "1e+308"); +} +// Mutation: send the first page before `release`. +TEST_CASE("window rows: a restoring window sends no query until released", "[ui][table]") { + RowsFixture h; auto const rows = h.restoringRows("samples"); + rows->visible(0, 30, h.columns); h.settle(); + CHECK(h.dispatcher.count("Table.samples") == 0); + REQUIRE(rows->setSort({{.column = "name", .dir = table::SortDirection::Descending}})); + h.settle(); CHECK(h.dispatcher.count("Table.samples") == 0); // still restoring + rows->release(); h.settle(); + CHECK(h.dispatcher.count("Table.samples") == 1); // T3: one query, carrying the sort + CHECK(h.dispatcher.calls.back().body.contains(R"("column":"name")")); + CHECK(h.dispatcher.calls.back().body.contains(R"("dir":"desc")")); // the wire's name for a direction +} +// Mutations: countsText ignoring `undecided`; countsText grouping with a fixed "," (the "de" line fails). +TEST_CASE("status line: counts for exact, lower-bound and undecided totals", "[ui][table]") { + using enum table::TotalKind; + FormatContext const en = formatFor("en"); + FormatContext const de = formatFor("de"); + REQUIRE(en.numeric.groupSeparator == ","); // the helper took the locale table's row + CHECK(countsText({.view = {9093, Exact, true}}, 0, de) == "9.093 rows"); + CHECK(countsText({.view = {9093, Exact, true}}, 0, en) == "9,093 rows"); + CHECK(countsText({.view = {100000, AtLeast, true}}, 0, en) == "100,000 or more"); + CHECK(countsText({.view = {12, AtLeast, true}, .undecided = 40}, 0, en) == "12 so far, 40 loading"); + CHECK(countsText({.view = {9093, Exact, true}}, 3, en) == "3 of 9,093 selected"); + CHECK(countsText({.view = {1, Exact, true}}, 0, en) == "1 row"); + CHECK(countsText({}, 0, en).empty()); +} +// Mutations: `keysOf` completing only after the next view change (`keysNow` fails the test); `row` answering nothing +// outside the last `visible` range (the row 499 REQUIRE). +TEST_CASE("engine rows: every row is present, visible does nothing, keysOf completes at once", "[ui][table]") { + RowsFixture h; auto const source = std::make_shared(500); + EngineRows rows{source, source->recordOf(), table::EngineOptions{.owner = &h.owner}}; + CHECK(rows.total().rows == 500); CHECK(rows.total().known); CHECK(rows.total().kind == table::TotalKind::Exact); + rows.visible(0, 10, {}); h.settle(); // names ten rows and no column + REQUIRE(rows.row(499).has_value()); + CHECK(rows.row(499)->key == table::RowId{std::int64_t{499}}); + CHECK(*rows.row(499)->row.field("name")->asString() == "row-499"); + CHECK(rows.unloadedLevels(499).levels.empty()); + CHECK_FALSE(rows.row(500).has_value()); + CHECK(h.keysNow(rows, 100, 3) == std::vector{std::int64_t{100}, std::int64_t{101}, std::int64_t{102}}); + CHECK(rows.counts().undecided == 0); CHECK_FALSE(rows.counts().pending); +} +// Mutation: no memo (recordsBuilt is 2 after the two reads). +TEST_CASE("engine rows: a row's record is built once until the row changes", "[ui][table]") { + RowsFixture h; auto const source = std::make_shared(10); + EngineRows rows{source, source->recordOf(), table::EngineOptions{.owner = &h.owner}}; + static_cast(rows.row(0)); static_cast(rows.row(0)); CHECK(rows.recordsBuilt() == 1); + source->rename(0, "renamed"); h.settle(); + CHECK(*rows.row(0)->row.field("name")->asString() == "renamed"); CHECK(rows.recordsBuilt() == 2); + static_cast(rows.row(1)); CHECK(rows.recordsBuilt() == 3); // another row: its own record +} +``` + +- [ ] **Step 2: Run to verify they fail** +Run: `cmake --build --preset cl-debug --target morph_tests` → FAIL: `ui/table_rows.hpp` not found. + +- [ ] **Step 3: Implement** the interfaces above in `include/morph/ui/table_rows.hpp` and the `SessionOptions` members in `interpreter.hpp`, with complete Doxygen. + +- [ ] **Step 4: Run to verify they pass** +Run: `ctest --test-dir build/cl-debug -R "window rows|engine rows|status line" --output-on-failure` → all pass; then the whole `morph_tests` target green. + +- [ ] **Step 5: Mutations** (each named above): apply, see the named case fail, revert; paste each failing line into the commit body. + +- [ ] **Step 6: Commit** `feat(ui): table rows over the engine and over a page window`. + +#### 9b — The store interface and the state document + +Needs Task 8c (`fitState` reads `TableDescription::units` directly) and Task 8b (`operator==` on `FilterEntry`, `ColumnFilter`, `GroupFilter` and `ColumnCount`, which `CarriedState`'s defaulted `operator==` uses; cross-part decision 38). + +**Files:** +- Create: `include/morph/table/state_store.hpp`, `tests/table/test_table_state.cpp` +- Modify: `CMakeLists.txt` (`include/morph/table/state_store.hpp` in the `morph` target's `FILE_SET HEADERS`; configure refuses a public header no file set lists), `tests/CMakeLists.txt` (`table/test_table_state.cpp` in `morph_table_tests`), `tests/table/bench_table.cpp` (T1) + +**Interfaces:** +- Consumes: `table::ColumnLayoutValue` and `ColumnLayout::apply` (8d), `table::TableDescription`, `table::FilterSpec`, `table::compileFilter` (existing compile path in `filter.hpp`). +- Produces (namespace `morph::table`): `TableStateKey`, `StoredTableState`, `SaveOutcome`, `SaveResult`, `ITableStateStore` exactly as table.md "Persisted state" declares them (`shares()` included, default `false`), except `publish` and `kNoDocument`, which Part E's Task 14a adds with `ViewOperation`, with one addition: `TableStateKey` declares `[[nodiscard]] bool operator==(TableStateKey const&) const = default;` (tests and the session's kept states compare keys; cross-part decision 38), and: + +```cpp +class MemoryTableStateStore final : public ITableStateStore { +public: + explicit MemoryTableStateStore(exec::IExecutor& executor); // completions delivered there + // revisions are "1", "2", … per key. Part E's Task 14a adds a defaulted second parameter, giving + // `explicit MemoryTableStateStore(exec::IExecutor&, Sharing = Sharing::Private)`; every call here stays valid. +}; + +inline constexpr int kStateVersion = 1; +/// Parts of a stored state that name a column or group the caller's description lacks. Not applied; merged back +/// by `writeState` into the places they had. +struct CarriedState { + struct Column { + std::string id; + std::string after; // the id it followed in the stored `order`; empty: it was first + bool hidden = false; + std::optional width; + std::map units; // dimension -> unit id, as stored + [[nodiscard]] bool operator==(Column const&) const = default; // cross-part decision 38 + }; + std::vector columns; // in stored order + std::vector> sort; // each key with its index in the stored chain + std::map filters; // by the absent column's id + std::vector groupFilters; // naming an absent group + std::vector groups; // user groups that name an absent column + /// `ColumnFilter` and `GroupFilter` compare by Part C's 8b `operator==` (cross-part decision 38). + [[nodiscard]] bool operator==(CarriedState const&) const = default; +}; +struct StateDocument { // part "state"; declared after `CarriedState`, which it holds + int version = kStateVersion; + std::optional layout; + std::optional sort; // `table::SortChain` (`sort.hpp:71`) + std::optional filters; + std::optional view; + CarriedState carried; // what the caller's description lacks, written back as it was +}; +struct FitDrop { + enum class What : std::uint8_t { Column, SortKey, Filter, GroupFilter, Group, Unit }; + What what; + std::string id; // the column, group or "column/dimension" of a unit + bool carried = false; // kept in `carried` (the description lacks it) or gone + [[nodiscard]] bool operator==(FitDrop const&) const = default; +}; +struct FitReport { std::vector dropped; }; // in the order of the fitting list +[[nodiscard]] std::expected readState(std::string_view json); // migrates forward +[[nodiscard]] std::string writeState(StateDocument const& document); +[[nodiscard]] StateDocument fitState(StateDocument document, TableDescription const& description, FitReport& report); +``` + +Decisions: +- The stored shape is table.md's, not the wire's. A stored sort key is `{"column": id, "direction": "asc" | "desc"}`, while `table::SortKey`'s member is `dir` and its wire form `{"column", "dir"}` (`sort.hpp:58-62`, `engine.md` "a sort key is `{ "column", "dir" }`"). `readState` and `writeState` therefore map the `sort` part by hand through a file-local `struct StoredSortKey { std::string column; SortDirection direction; }` (glaze reflects its member names; `SortDirection`'s `glz::meta` already spells `asc`/`desc`), converting to and from `SortKey`; they never reflect `SortKey` itself, which would read `direction` as an unknown key and leave every key ascending. `layout` reads as `ColumnLayoutValue` and `filters` as `FilterSpec`, whose reflected names are the stored ones. +- `readState` refuses text that is not JSON and a `version` above `kStateVersion` with a message; a lower version is migrated one version at a time (none exist yet, so the migration table is empty and its loop is tested by a version-0 fixture added when a version 2 exists — not now). +- `fitState` applies table.md's fitting list in order: columns as `ColumnLayout::apply` fits them; sort keys on missing or unsortable columns dropped; filters on missing columns or groups, filters that do not compile for the column's kind, and units not in `description.units` dropped; user groups left with fewer than two columns dropped with their filter. A drop because the description lacks the column or group moves the entry into `carried`; any other drop is gone. A user group that names an absent column is carried whole (it is whole again when the column returns); one left with fewer than two present columns for any other reason is gone with its filter. A user-formed group's filter is a `GroupFilter` with `group` empty and `columns` set to the group's columns (Part C's `compileGroup` takes exactly one of `group` and `columns`), so `fitState` finds the filter of a user group by `columns` equal to that group's `columns` (as sets), and moves or drops it with the group; a `GroupFilter` naming a declared `group` is fitted against `description.groups` by id. +- `writeState` merges `carried` back: a column into `order` right after its `after` id, or first when `after` is empty, or at the end when `after` is itself absent from the written order; its hidden flag, width and units with it; a sort key at its stored index, clamped to the chain's length; filters, group filters and groups appended. Reading that text with the same description carries the same entries again. +- The lowering reports, once each at the table's path, the drops the spec says are reported: `Filter`, `GroupFilter` and `Unit`. `Column`, `SortKey` and `Group` drops are not reported. + +- [ ] **Step 1: Write the failing tests** in `tests/table/test_table_state.cpp`. The file's fixtures, each defined once: + +- `describedSamples()` is `table::describe` of: columns `id` (`Integer`, the key), `name` (`Text`), `alias` (`Text`), `weight` (`Measure`, `dimensions = {"mass"}`), in that order, each `sortable`, `filterable` and `shown`; `units` lists `g` and `kg` of dimension `mass`; one declared group `g1 = {name, alias}`. It has no column `gone`, `a` or `b` and no group `g2`. +- `userGroups()` is `readState` of `{"version":1,"layout":{"order":["id","name","alias","weight"],"groups":[{"id":"u1","label":"One","columns":["name","gone"]},{"id":"u2","label":"Two","columns":["name","alias"]}]},"filters":{"columns":{},"groups":[{"columns":["name","gone"],"include":[{"contains":"x"}]},{"columns":["name","alias"],"include":[{"contains":"y"}]}]}}`. +- `StepExecutor executor;` and `saveNow(store, key, json, expected = {}) -> SaveResult`, `loadNow(store, key) -> std::optional`: each calls the store, runs `executor.runAll()` and returns what the completion delivered (failing the test when it delivered nothing). + +```cpp +// Mutation: fitState returning the document unchanged (the sort, filter and hidden CHECKs fail). +TEST_CASE("table state: stale state is fitted", "[table][state]") { + TableDescription const d = describedSamples(); + StateDocument const stored = readState(R"({"version":1, + "layout":{"order":["id","gone","name","alias","weight"],"hidden":["id","name","alias","weight"],"pinned":2, + "widths":{"gone":9},"units":{"weight":{"mass":"zz"}}}, + "sort":[{"column":"gone","direction":"asc"},{"column":"name","direction":"desc"}], + "filters":{"columns":{"gone":{"include":[{"eq":"x"}]},"weight":{"include":[{"gt":"abc"}]}}, + "groups":[{"group":"g2","include":[{"eq":"x"}]}]}})").value(); + REQUIRE(stored.sort->at(1).dir == SortDirection::Descending); // "direction" was read, not ignored + FitReport report; + StateDocument const fitted = fitState(stored, d, report); + CHECK(fitted.layout->order == std::vector{"id", "name", "alias", "weight"}); + CHECK(fitted.layout->hidden.size() < 4); // every column was hidden: one shows + CHECK(*fitted.sort == SortChain{{.column = "name", .dir = SortDirection::Descending}}); + CHECK(fitted.filters->columns.empty()); + CHECK(fitted.filters->groups.empty()); + CHECK_FALSE(fitted.layout->units.contains("weight")); // unknown unit "zz" dropped + using W = FitDrop::What; + CHECK(report.dropped == std::vector{ + {W::Column, "gone", true}, {W::SortKey, "gone", true}, {W::Filter, "gone", true}, + {W::Filter, "weight", false}, {W::GroupFilter, "g2", true}, {W::Unit, "weight/mass", false}}); + CHECK(fitted.carried.columns == std::vector{{.id = "gone", .after = "id", .width = 9}}); + std::string const written = writeState(fitted); + CHECK(written.contains(R"("direction":"desc")")); // the stored name, not the wire's "dir" + CHECK_FALSE(written.contains(R"("dir":)")); + StateDocument const again = readState(written).value(); + CHECK(again.layout->order == std::vector{"id", "gone", "name", "alias", "weight"}); // its place kept + CHECK(again.sort->at(0).column == "gone"); // carried key back at index 0 + CHECK(again.sort->at(1) == SortKey{.column = "name", .dir = SortDirection::Descending}); + CHECK(again.filters->columns.contains("gone")); + CHECK_FALSE(again.filters->columns.contains("weight")); // did not compile: gone at the next save + REQUIRE(again.filters->groups.size() == 1); CHECK(again.filters->groups.front().group == "g2"); + FitReport second; // reading it again carries the same + CHECK(fitState(again, d, second).carried == fitted.carried); +} +// Mutation: fitState looking up a user group's filter by `group` id (an empty id finds nothing: u3's filter, whose +// group is dropped for having one column, stays in `filters`). u1's filter cannot show that mutation: a filter over +// listed columns that matches no user group is still fitted by its columns, and one naming the absent `gone` is +// carried either way. +TEST_CASE("table state: a user group and its filter are fitted together", "[table][state]") { + FitReport report; StateDocument const fitted = fitState(userGroups(), describedSamples(), report); + REQUIRE(fitted.layout->groups.size() == 1); CHECK(fitted.layout->groups.front().id == "u2"); + REQUIRE(fitted.filters->groups.size() == 1); // u2's, matched by its columns + CHECK(fitted.filters->groups.front().columns == std::vector{"name", "alias"}); + REQUIRE(fitted.carried.groups.size() == 1); CHECK(fitted.carried.groups.front().id == "u1"); + REQUIRE(fitted.carried.groupFilters.size() == 1); // u1's, carried with its group + CHECK(fitted.carried.groupFilters.front().group.empty()); + CHECK(fitted.carried.groupFilters.front().columns == std::vector{"name", "gone"}); + // A user group left with one column, every column present, is gone, and its filter with it. + StateDocument const single = readState(R"({"version":1,"layout":{"groups":[{"id":"u3","label":"Three","columns":["weight"]}]}, + "filters":{"groups":[{"columns":["weight"],"include":[{"isEmpty":true}]}]}})").value(); + FitReport dropped; StateDocument const alone = fitState(single, describedSamples(), dropped); + CHECK(alone.layout->groups.empty()); CHECK(alone.filters->groups.empty()); CHECK(alone.carried.groupFilters.empty()); +} +// Review Focus 3 (the parser's half; the table's half is 9d's). Mutation: readState accepting an unknown version. +TEST_CASE("table state: a document that is not JSON or of an unknown version is refused", "[table][state]") { + CHECK_FALSE(readState("{not json").has_value()); + CHECK_FALSE(readState(R"({"version":2,"sort":[]})").has_value()); + CHECK(readState(R"({"version":1})").has_value()); +} +// Mutation: save ignoring `expected` (the third save answers Saved). +TEST_CASE("memory table state store: a save with a stale revision is a conflict", "[table][state]") { + MemoryTableStateStore store{executor}; + TableStateKey const key{.application = "lims", .model = "Lims_SampleModel", .table = "samples", + .qualifier = "samples", .part = "views"}; + CHECK_FALSE(loadNow(store, key).has_value()); + SaveResult const first = saveNow(store, key, R"({"a":1})"); + CHECK(first.outcome == SaveOutcome::Saved); CHECK(first.revision == "1"); + SaveResult const second = saveNow(store, key, R"({"b":1})", "1"); + CHECK(second.outcome == SaveOutcome::Saved); CHECK(second.revision == "2"); + SaveResult const stale = saveNow(store, key, R"({"c":1})", "1"); + CHECK(stale.outcome == SaveOutcome::Conflict); CHECK(stale.revision == "2"); + CHECK(loadNow(store, key)->json == R"({"b":1})"); // the conflict wrote nothing + CHECK(saveNow(store, key, R"({"d":1})").outcome == SaveOutcome::Saved); // no `expected`: replaces +} +``` +T1 benchmark: `"table state benchmark: parse, fit and apply 300 columns, 8 keys, 32 filters"` tagged `[.benchmark][table][state]`; it asserts first that every one of the 8 keys and 32 filters survives fitting. + +- [ ] **Step 2: Run to verify they fail** — `cmake --build --preset cl-debug --target morph_table_tests` → FAIL: `state_store.hpp` not found. +- [ ] **Step 3: Implement** `state_store.hpp` as above. +- [ ] **Step 4: Run to verify they pass** — `ctest --test-dir build/cl-debug -R "table state|memory table state" --output-on-failure`; `morph_table_tests` green. +- [ ] **Step 5: Mutations**, as named. +- [ ] **Step 6: Commit** `feat(table): the table state store and the state document`. + +#### 9c — The preferences-backed store and the session's kept states + +**Files:** +- Create: `include/morph/ui/table_state.hpp`, `include/morph/ui/table_state_model.hpp`, `tests/test_ui_table_state.cpp` +- Modify: `include/morph/ui/interpreter.hpp` (`SessionOptions` members listed in 9a; `Session::tableStates() -> TableStates*`, null without a store), `include/morph/ui/preferences.hpp` (`PreferencesModel` refuses the names table state reserves), `tests/test_ui_preferences.cpp` (that refusal), `tests/ui_table_support.hpp` (`ProbePreferencesStore`), `tests/net/test_push_tables.cpp` ("The person is the store's") + +**Interfaces:** +- Consumes: `IPreferencesStore`, `PrefKey` (existing), `session::current()` as `PreferencesModel` reads it, `morph::session::detail::sha256`, `Dispatcher`/`ModelChannel` (existing), 9b's interface. +- Produces: + +```cpp +// preferences.hpp, namespace morph::ui (see "Reserved names") +inline constexpr std::string_view kTableStateModel = "morph.tableState"; +// table_state_model.hpp, namespace morph::ui +struct TableStateOptions { + std::size_t segmentBytes = std::size_t{12} * 1024; + std::size_t partBytes = std::size_t{1} << 20; // a save part and a load head + std::optional maxBytesPerPerson; // unset: no quota +}; +struct TableStateLoad { std::vector keys; }; +struct TableStateHead { bool found = false; std::string revision; std::uint64_t size = 0; std::string text; + std::string error; }; // why this key failed (a missing segment); the others still load +struct TableStateLoaded { std::vector entries; }; // one per key, in order +struct TableStateRead { table::TableStateKey key; std::string revision; std::uint64_t offset = 0; }; +struct TableStateChunk { std::string revision; std::string text; }; // another revision: start again +struct TableStateSave { table::TableStateKey key; std::string expected; std::string upload; + std::uint64_t offset = 0; std::string text; bool last = true; }; +struct TableStateSaved { table::SaveResult result; }; +struct TableStateRemove { table::TableStateKey key; }; +struct TableStateRemoved{ bool removed = false; }; +class TableStateModel; // execute(TableStateLoad), execute(TableStateRead), execute(TableStateSave), execute(TableStateRemove) +void registerTableState(std::shared_ptr store, model::detail::ActionDispatcher& dispatcher, + model::detail::ModelRegistryFactory& registry, TableStateOptions options = {}); + +// table_state.hpp +class PreferencesTableStateStore final : public table::ITableStateStore { +public: + PreferencesTableStateStore(Dispatcher& dispatcher, exec::IExecutor& owner); + [[nodiscard]] bool shares() const override { return true; } +}; +enum class StateParts : std::uint8_t { Layout = 1, Sort = 2, Filters = 4, View = 8 }; // a bit set +class TableStates { // one per Session with a store +public: + // `owner`: where `load` answers, a kept key at once, with no store completion to deliver on. + TableStates(std::shared_ptr store, exec::IExecutor& owner, + reactive::Scheduler* scheduler, std::chrono::milliseconds debounce); + [[nodiscard]] std::optional kept(table::TableStateKey const& key) const; + async::Completion> load(table::TableStateKey const& key); + /// Marks @p parts of the key's state changed to those of @p document; a debounced save, one in flight per key. + void changed(table::TableStateKey const& key, table::StateDocument const& document, StateParts parts); + void flush(table::TableStateKey const& key); // unmount: save now + void onSaveFailed(std::function handler); + /// The store it loads from and saves to, for a part this class does not debounce (Part E's `views`, 14b). + [[nodiscard]] table::ITableStateStore& store() const noexcept; + /// Replaces the session's kept copy of @p key after a save made through `store()`, so a later mount restores it. + void keep(table::TableStateKey const& key, table::StoredTableState state); +}; +``` + +Decisions: +- Action ids. `TableStateModel` is registered as `morph.tableState` with four actions, by the traits-only macros `preferences.hpp` uses for its own (`BRIDGE_DETAIL_ACTION_TRAITS_ONLY_BODY`, `Loggable::No`): `"load"` (`TableStateLoad` → `TableStateLoaded`), `"read"` (`TableStateRead` → `TableStateChunk`), `"save"` (`TableStateSave` → `TableStateSaved`), `"remove"` (`TableStateRemove` → `TableStateRemoved`). `PreferencesTableStateStore` binds `kTableStateModel` once through its `Dispatcher` and sends exactly these ids; Part E's Task 14a adds `"publish"`. +- Reserved names. The preferences model writes to the same `IPreferencesStore` with whatever `app`, `scope` and `point` its caller names (`preferences.hpp`, `keyOf`), so without a rule a person could overwrite the quota's usage entry or a state's head through `morph.preferences`. `PreferencesModel::checkName` therefore refuses, on `load`, `set` and `remove` alike, an `app` equal to `kTableStateModel` (`"morph.tableState"`) and a `scope` that starts with `morph.table` (`std::invalid_argument`, "`` is kept for table state"), before the store is called. The two constants (`kTableStateModel`, `inline constexpr std::string_view kTableStateScopePrefix = "morph.table"`) are declared in `preferences.hpp`, which `table_state_model.hpp` includes, so the model that reserves and the model that refuses read one definition. +- Server layout per table.md "The framework's stores": person from the verified session (none: `load` answers `found = false` for every key, `save` and `remove` are refused); `app` = the key's `application`; scope `morph.table.` + the first 32 lower-case hex digits of `sha256(model + "\x1F" + table + "\x1F" + qualifier)`; point `` holds `{"key": {…in clear…}, "revision": r, "document": …}` for a document of at most `segmentBytes`, else `{"key": …, "revision": r, "segments": n, "bytes": b}` with segments at `..`, each a JSON string of at most `segmentBytes`. A head whose clear key differs from the asked key reads as not found. A missing segment fails the load. +- Write order, with an intent entry because `IPreferencesStore` has only `get`, `set` and `remove` by exact key (`preferences.hpp:62-73`) and so cannot list the segments under a scope: (1) read `.pending`; if present, it names up to two revisions, `{"revision": r, "segments": n, "previous": r0, "previousSegments": n0}`; read the head, and remove the segments `..<0…count−1>` of each named revision the head does not name, then remove `.pending`; (2) when the new document or the one the head now names is segmented, write `.pending` naming the new revision (`segments` 0 for an unsegmented one) and the head's (`previousSegments` 0 likewise); (3) the segments; (4) the head; (5) remove the previous revision's segments; (6) remove `.pending`. A save stopped before (4) leaves the old head and its segments readable and the new segments stray; one stopped between (4) and (6) leaves the previous revision's segments stray; in both cases the next save of the key removes exactly the strays in step (1), because the head names the one revision to keep. A save that writes no segments and replaces none writes no intent. A removal that fails in steps (5) or (6) does not fail the save, whose head is written: it leaves strays that the intent names, for the next save. +- Key bounds: `application`, `table`, `qualifier` and `part` are 1 to 256 bytes; `model` is 0 to 256 bytes, because a table over a document's rows has an empty `model` (table.md "Persisted state", the key's comment, the "Bounds" bullet, and Task 11b). The spec already states these bounds and is not edited by this task. The model checks the bounds on every request (a `std::invalid_argument` naming the member, as the preferences model refuses a name) before it reads the store. +- Revision: the first 16 hex digits of `sha256(previousRevision + document)`. +- Quota. The spec's quota is "across one person's stored state", so it spans applications: with `maxBytesPerPerson` set, the model keeps the person's total at `PrefKey{.person = person, .app = std::string{kTableStateModel}, .scope = "morph.table", .point = "usage"}` (`"morph.tableState"` is not an application's id and `"morph.table"` is no state's scope, which is always `morph.table.<32 hex>`), as `{"bytes": n}`. Arithmetic, all in `std::uint64_t` document bytes (the length of the document's text as `save` received it; entries, envelopes and segment quoting are not counted): `n` is the stored value, 0 when the entry is absent or does not read as `{"bytes": }`; `b0` is the replaced document's size, 0 when the key has no head, else the head's `bytes` for a segmented head and the length of its `document` member's text for a small one; `b1` the new document's size. A save is refused when `n − b0 + b1 > maxBytesPerPerson` (computed as `n + b1 > quota + b0`, so no subtraction wraps): it answers `SaveResult{Refused, reason = "over the table-state quota"}` and writes nothing, `usage` included. Otherwise it writes the document (the order above), then `usage = n − b0 + b1`. A remove of a present key writes `usage = n − min(n, b0)`; of an absent key writes nothing. A multi-part save is checked once, at its `last` part, against the whole text. Without the option no `usage` entry is read or written. A preferences store has no conditional write, so two saves of one person reaching two model instances in the same moment can both pass the check; the quota can then be overshot by one document, which an operator's ceiling tolerates as the spec's `expected` rule tolerates its own race. +- `PreferencesTableStateStore::load` calls made in one turn of `owner` go out as one `TableStateLoad`; a head shorter than `size` is completed with `TableStateRead` calls by offset, restarting when the revision changes. A `save` over `partBytes` is sent as parts under one upload id (`upload` = a random 16-hex id), committed by the part with `last`. +- `onSaveFailed` is one slot for the session: the handler is called on the owner for every save of a `state` part that did not end `Saved` (the store's completion failed, or answered `Refused` or `Conflict`), with the key and the result (`outcome = Refused` and the failure's text as `reason` for a failed completion). The session sets it once, when it builds its `TableStates`, to a function that finds the mounted tables of that key and posts to each (9d). The kept copy is not replaced by a save that did not end `Saved`. +- `TableStates` keeps every document it loaded or saved, by key, for the session's life; `load` of a kept key resolves at once with no call. `keep` replaces a kept entry (or adds one) and cancels nothing: a debounced save of the same key still goes out with its own document. `store()` and `keep` are what Part E's Task 14b uses for the `views` part, which saves with `expected` and is not debounced. +- A change before the key's load settles is held, not saved: when the load completes (or fails, or is given up on at the table's timeout and later completes) the save writes the loaded document with only the changed parts replaced (`writeState` over the loaded `StateDocument` with `layout`, `sort`, `filters` or `view` taken from the change per `parts`). A load that failed saves the change over an empty document, and so does a load whose text `readState` refuses (not JSON, or a version above `kStateVersion`): the stored text is never merged into and never written back, so the first save after a change overwrites it with a `kStateVersion` document holding the changed parts only, and until a change nothing is written (Review Focus 3). So a sort changed while a slow load is held never overwrites the stored filters. + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_state.cpp`, over an in-process server built as `tests/ui_preferences_support.hpp`'s `prefs_test::Server` is (a `RemoteServer` over a `ThreadPoolExecutor`, the `TokenAuthorizer` that makes the request's token the verified principal, and `server->handle` called directly — no socket): `registerTableState(prefs, dispatcher, registry, options)` in place of `registerPreferences`, and a client `Dispatcher` whose channel sends each `execute` through `server->handle` with token `person`. `prefs` is `ProbePreferencesStore` (new, `tests/ui_table_support.hpp`): a `MemoryPreferencesStore` wrapper that records every key it was given so a test can list what the model cannot, with `has(PrefKey)`, `value(PrefKey) -> std::string`, `erase(PrefKey)`, `pointsUnder(scope) -> std::set` (the points of every live entry with that scope), `largestValue()`, `setCount()`, `removeCount()`, `failSetsAfter(std::size_t n)` and `failRemovesAfter(std::size_t n)` (every `set`, or `remove`, after the n-th answers `false` and changes nothing), `healSets()` and `healRemoves()`; `usageKey(person)` is the quota entry's `PrefKey` above, `pendingPoint(key)`/`segmentPoint(key, i)`/`scopeOf(key)` the layout's names: + +```cpp +// Mutation: no segments (the whole document in its head, an entry over segmentBytes). +TEST_CASE("table state: state of any size", "[ui][state]") { + std::string const big = stateWithOneOfValues(20'000); // a 20,000-value oneOf, well over 1 MiB + REQUIRE(save(store, key, big).outcome == SaveOutcome::Saved); + CHECK(load(store, key)->json == big); + CHECK(prefs.largestValue() <= 12 * 1024); // every entry within segmentBytes, quotes included + prefs.failSetsAfter(prefs.setCount() + 1 + segmentsOf(big2)); // the intent and the segments are written; the head is not + CHECK_FALSE(trySave(store, key, big2)); + CHECK(load(store, key)->json == big); // the previous state still reads + CHECK(prefs.has(pendingPoint(key))); // the stopped save left its intent + prefs.healSets(); + REQUIRE(save(store, key, big3).outcome == SaveOutcome::Saved); // the next save cleans up first + CHECK_FALSE(prefs.has(pendingPoint(key))); + CHECK(prefs.pointsUnder(scopeOf(key)) == headAndSegmentsOf(store, key)); // no stray segment of big2 or big + prefs.erase(segmentPoint(key, 3)); + CHECK_THROWS(load(store, key)); // a missing segment is a failed load +} +// Mutation: the intent naming only the new revision (the previous revision's segments stay after a stop at step 5). +TEST_CASE("table state: a save stopped after its head leaves no stray segment behind the next save", "[ui][state]") { + REQUIRE(save(store, key, big).outcome == SaveOutcome::Saved); + prefs.failRemovesAfter(prefs.removeCount()); // step 5 fails: big's segments stay + REQUIRE(save(store, key, big2).outcome == SaveOutcome::Saved); // the head names big2 + prefs.healRemoves(); + REQUIRE(save(store, key, small).outcome == SaveOutcome::Saved); // unsegmented; step 1 cleans big's, then big2's + CHECK(prefs.pointsUnder(scopeOf(key)) == std::set{"state"}); +} +// Mutation: bounds "1 to 256" on every member (a rows table's key, model "", is refused). +TEST_CASE("table state: a key's model may be empty, its table may not", "[ui][state]") { + CHECK(save(store, keyWithModel(""), "{}").outcome == SaveOutcome::Saved); + CHECK_THROWS(save(store, keyWithTable(""), "{}")); + CHECK_THROWS(save(store, keyWithModel(std::string(257, 'm')), "{}")); +} +// Mutation: the quota checked as n + b1, the replaced size not subtracted (a replace of a large state is refused). +TEST_CASE("table state: a save over the quota is refused and the previous state still reads", "[ui][state]") { + // registerTableState with maxBytesPerPerson = 10'000 + REQUIRE(save(store, keyA, docOf(6'000)).outcome == SaveOutcome::Saved); + REQUIRE(save(store, keyA, docOf(9'000)).outcome == SaveOutcome::Saved); // a replace: 9,000 in use + auto const over = save(store, keyB, docOf(2'000)); + CHECK(over.outcome == SaveOutcome::Refused); CHECK(over.reason == "over the table-state quota"); + CHECK_FALSE(load(store, keyB)); + CHECK(load(store, keyA)->json == docOf(9'000)); + CHECK(prefs.value(usageKey(person)) == R"({"bytes":9000})"); // 6,000 replaced, not added + CHECK(remove(store, keyA)); + CHECK(prefs.value(usageKey(person)) == R"({"bytes":0})"); + CHECK(save(store, keyB, docOf(2'000)).outcome == SaveOutcome::Saved); // 9,000 freed + REQUIRE(save(store, keyC, docOf(8'000)).outcome == SaveOutcome::Saved); // 10,000: at the quota is allowed + CHECK(save(store, keyC, docOf(20'000)).outcome == SaveOutcome::Refused); // 10,000 − 8,000 + 20,000 > 10,000 + CHECK(prefs.value(usageKey(person)) == R"({"bytes":10000})"); // a refusal writes nothing +} +// Mutation: b0 read as the head entry's length for a segmented head (the head is ~60 bytes: the replace is refused). +TEST_CASE("table state: the quota counts a segmented document by its bytes", "[ui][state]") { + // maxBytesPerPerson = 40'000; save docOf(30'000) (segmented: 3 segments of 12 KiB) + REQUIRE(save(store, keyA, docOf(30'000)).outcome == SaveOutcome::Saved); + CHECK(save(store, keyA, docOf(35'000)).outcome == SaveOutcome::Saved); // 30,000 − 30,000 + 35,000 + CHECK(prefs.value(usageKey(person)) == R"({"bytes":35000})"); +} +// Mutation: usage written without the option set. +TEST_CASE("table state: no quota, no usage entry", "[ui][state]") { + REQUIRE(save(store, keyA, docOf(6'000)).outcome == SaveOutcome::Saved); + CHECK_FALSE(prefs.has(usageKey(person))); +} +// Review: a save during a held load. Mutation: the change saved over an empty document at once. +TEST_CASE("table state: a change during a held load keeps the stored parts", "[ui][state]") { + // gated store holding {"version":1,"filters":{"columns":{"name":{"include":[{"contains":"a"}]}}}} + states.changed(key, docWithSort("name", Descending), StateParts::Sort); h.advance(600ms); + CHECK(gated.saves() == 0); // held until the load settles + gated.release(); h.advance(600ms); + REQUIRE(gated.saves() == 1); + CHECK(gated.lastSaved().contains(R"("contains":"a")")); // stored filter carried + CHECK(gated.lastSaved().contains(R"("column":"name")")); +} +// Review Focus 3, the store's half. Mutation: merging the change into the stored text (the save still holds "junk"). +TEST_CASE("table state: a change over a stored document that does not read replaces it", "[ui][state]") { + for (std::string const stored : {std::string{"{not json"}, std::string{R"({"version":2,"junk":true})"}}) { + GatedTableStateStore gated{h.owner, stored}; TableStates states{sharedOf(gated), h.owner, &h.scheduler, 500ms}; + gated.release(); REQUIRE(loaded(states, key)); + h.advance(600ms); CHECK(gated.saves() == 0); // nothing is written until a change + states.changed(key, docWithSort("name", Descending), StateParts::Sort); h.advance(500ms); + REQUIRE(gated.saves() == 1); + CHECK_FALSE(gated.lastSaved().contains("junk")); + table::StateDocument const saved = table::readState(gated.lastSaved()).value(); // the framework's version + CHECK(saved.version == table::kStateVersion); CHECK(saved.sort->at(0).column == "name"); + } +} +// Mutation: no call of the handler for a Refused save (`failures` stays empty). +TEST_CASE("table state: a save that is refused reaches the session's handler and keeps the kept copy", "[ui][state]") { + GatedTableStateStore gated{h.owner, R"({"version":1})"}; TableStates states{sharedOf(gated), h.owner, &h.scheduler, 500ms}; + std::vector failures; + states.onSaveFailed([&](table::TableStateKey const&, table::SaveResult const& result) { failures.push_back(result); }); + gated.release(); REQUIRE(loaded(states, key)); + gated.refuseSaves("over the table-state quota"); + states.changed(key, docWithSort("name", Descending), StateParts::Sort); h.advance(500ms); + REQUIRE(failures.size() == 1); + CHECK(failures.front().outcome == table::SaveOutcome::Refused); + CHECK(failures.front().reason == "over the table-state quota"); + CHECK(states.kept(key)->json == R"({"version":1})"); // what the store still holds +} +// Mutation: keep() not replacing the kept copy (the remount restores the loaded document). +TEST_CASE("table state: a kept copy replaced by keep() is what the next load answers", "[ui][state]") { + REQUIRE(loaded(states, key)); + states.keep(key, table::StoredTableState{.json = docWithSortOn(7), .revision = "9"}); + auto const again = loadNow(states, key); // no store call + CHECK(store.loads() == 1); CHECK(again->revision == "9"); CHECK(&states.store() == &store); +} +// Mutation: each table's load sent on its own (five calls). Gate T5. +TEST_CASE("table state: five tables of a screen load in one call, and a second mount in none", "[ui][state]") { + CHECK(dispatcher.count("load") == 1); + remountScreen(); + CHECK(dispatcher.count("load") == 1); +} +// Mutation: no debounce (fifty saves). Gate T4. +TEST_CASE("table state: fifty changes within a second are one save of the last", "[ui][state]") { + REQUIRE(loaded(states, key)); + for (int i = 0; i < 50; ++i) { states.changed(key, docWithSortOn(i), StateParts::Sort); h.advance(10ms); } + h.advance(500ms); + CHECK(store.saves() == 1); CHECK(readState(store.lastSaved())->sort == docWithSortOn(49).sort); +} +``` +The fixture of this file: `h` is a `RowsFixture` (its `owner` and `scheduler`); `key` is `{application "lims", model "Lims_SampleModel", table "samples", qualifier "samples", part "state"}`; `GatedTableStateStore(executor, json)` holds each load until `release()` or `fail()`, counts `loads()` and `saves()`, keeps `lastSaved()` and `lastLoadKey()`, and after `refuseSaves(reason)` answers every save `Refused` with that reason; `sharedOf(store)` is a non-owning `std::shared_ptr` to it; `loaded(states, key)` calls `load`, settles and returns whether it delivered; `docWithSort(column, direction)` and `docWithSortOn(i)` are `StateDocument`s with that one sort key (`docWithSortOn(i)` sorts on column `c`). + +In `tests/test_ui_preferences.cpp`, over the existing `prefs_test::Server` (its `call(action, body, token)` and its `RecordingStore`): + +```cpp +// Mutation: no reservation in `checkName` (the first call answers "ok" and the store records a `set`). +TEST_CASE("preferences: the names table state keeps are refused", "[ui][preferences][remote]") { + prefs_test::Server server; + std::string const scope = "morph.table.0123456789abcdef0123456789abcdef"; + CHECK(server.call("set", R"({"app":"morph.tableState","scope":"morph.table","point":"usage","value":"{\"bytes\":0}"})", + "alice").kind != "ok"); // the quota's usage entry + CHECK(server.call("set", R"({"app":"lims","scope":")" + scope + R"(","point":"state","value":"{}"})", "alice").kind != "ok"); + CHECK(server.call("remove", R"({"app":"lims","scope":")" + scope + R"(","point":"state"})", "alice").kind != "ok"); + CHECK(server.call("load", R"({"app":"lims","scope":")" + scope + R"(","points":["state"]})", "alice").kind != "ok"); + CHECK(server.store->calls().empty()); // nothing reached the store + CHECK(server.call("set", R"({"app":"lims","scope":"lims.results","point":"density","value":"1"})", "alice").kind == "ok"); +} +``` + +In `tests/net/test_push_tables.cpp`: `"table state: the person is the store's"` — two principals over one socket server save different `state` documents under one `TableStateKey` and each loads its own; a `TableStateLoad` body carrying a `"person"` member is read with that member ignored (glaze `error_on_unknown_keys = false`), so no request names another person. Mutation: the model keying by a body member. + +- [ ] **Step 2: Run to verify they fail** — `cmake --build --preset cl-debug --target morph_tests` → FAIL: `table_state.hpp` not found. `morph_net_tests` is POSIX-only (cross-part decision 18): build and run its case on `linux-everything` (`cmake --preset linux-everything && cmake --build --preset linux-everything --target morph_net_tests`). +- [ ] **Step 3: Implement** the interfaces above. +- [ ] **Step 4: Run to verify they pass** — `ctest --test-dir build/cl-debug -R "table state|preferences" --output-on-failure` and `morph_tests` green; `ctest --test-dir build/linux-everything -R "table state" --output-on-failure` for the `morph_net_tests` case. +- [ ] **Step 5: Mutations**, as named. +- [ ] **Step 6: Commit** `feat(ui): table state in the application's preferences store`. + +#### 9d — The model-backed `table` node on the engine + +**Files:** +- Modify: `include/morph/ui/view.hpp` (`TableSource`, `TableRowLook`, `CellLoad`, `TableStatus`, `TableColumn::id`, `Table::source`, `Table::status`, `Table::onRetry`), `include/morph/ui/mount.hpp` (`mountKind(Table)` reads `Table::source` when set; cells per column with their own row signal; `MountStats`, `Mounted::stats()`), `include/morph/ui/backend.hpp` (`TableWidget::setStatus`, `setOnRetry`, `setCellLoad`), `include/morph/ui/testing/recording_backend.hpp` (records `status`, cell loads; `retryTable`), `include/morph/ui/interpreter.hpp` and `src/ui/interpreter.cpp` (the lowering; `RtScope::onMissingRowField`; `ScreenCore::tableMessage`, `kStatusMessageHold`; element values), `src/ui/document.cpp` (the loader, cross-part decision 44: see "The loader" below), `tests/test_ui_document.cpp` (the loader cases), `tests/ui_table_support.hpp` (`TableHarness` and the screen helpers), `tests/test_ui_table_model.cpp`, `tests/qt_quick/test_qt_quick_table.cpp` (F6, F7, F1) +- Docs: `docs/spec/ui/interpreter.md` ("Not yet lowered" loses the model-backed `table` entry; "Lowering" describes the lowering onto `TableRows`), `docs/spec/ui/document.md` (the `table` kind: `model` with `table` or `action`, `body`, `status`, `persist`, `empty` on a model-backed table, element values `viewCount`, `viewCountKind`, `undecided`, `awaiting`, `failed`, `pending`), `docs/spec/ui/preferences.md` (table state has its own model, `morph.tableState`, not bounded by `maxValueBytes`; the preferences model refuses the `app` `morph.tableState` and every scope starting `morph.table`; the `columns` and `saved` points read and write the table's state), `docs/spec/table/engine.md` ("Not here yet": the model-backed table entry goes). + +**Interfaces:** +- Consumes: 9a, 9b, 9c; Task 7's query-cache rules (the description is an entry of `Table..describe`). +- Produces: + +```cpp +// view.hpp +class TableRows; +/// Whether a cell's value is here (cross-part decision 29). Read from the row's `TableRows::unloadedLevels` and the +/// column's level. +enum class CellLoad : std::uint8_t { Loaded, Unloaded, Failed }; +/// A row's own parts beyond its cells, built once per realized row key, bound in the row's scope. Later parts +/// add members to this struct and do not replace it (cross-part decision 39): `std::optional> marks` +/// (Task 17b) and `bool summary` (Task 22). Nothing per cell is carried here. A cell view that later tasks wrap is +/// unwrapped by the mount outermost first: `MarkedCell` (Task 19), then `AccentedCell` (Task 15), then the content. +struct TableRowLook { + std::optional>> tone; // `rowTone`; disengaged: none + std::optional> label; // `rowLabel`; disengaged: the key as text + std::optional>> spans; // `rowSpans` (a rows table, Task 11b) + Node heading; // non-null: a heading row; no cell is built for it +}; +/// Rows by view index, and cells as a mount concept (cross-part decision 28). +struct TableSource { + std::shared_ptr rows; + /// One cell's view for the column at @p column (an index into `Table::columns`, which holds hidden columns too + /// and does not change with the layout: cross-part decision 37), built once per cell widget from + /// a signal the mount sets to the record of the row that cell shows. A cell owns its signal: from Task 10a a + /// pooled cell is rebound to another row by setting it, never by building the view again. What it returns is + /// the cell's content; Task 15 wraps it as `accentedCell(content, accent)` and Task 19 as `markedCell(…, marks)` + /// (cross-part decision 39), inside this same function. + std::function const& row)> cellView; + /// The row's own parts, built once per realized row key from a signal the mount keeps equal to its record. + std::function const& row)> rowView; + /// Column ids named to every `visible` call whatever the column window holds: what `rowView`, `rowTone`, + /// `rowLabel` and `onActivate` read. Laid-out columns in the window are added to it per call. + std::vector alwaysFetched; + /// Per `Table::columns` index, the level of that column (`ColumnInfo::level`); empty: the column has none. + std::vector levels; +}; +// TableColumn gains: std::string id; // the column's id; empty for a table built from C++ with no ids +struct TableStatus { + std::string counts; // the leading part + std::string state; // a failed level or fetch; empty when none + bool retry = false; // the state offers "Retry" + std::string message; // the latest refusal or notice; empty when none + bool shown = false; // whether the line takes space + [[nodiscard]] bool operator==(TableStatus const&) const = default; +}; +// struct Table gains: +std::optional source; // when set, `rows` is ignored and rows come by view index +Prop status; +std::function onRetry; +// `TableOptions` (view.hpp:2026) gains the same three members (cross-part decision 41). + +// backend.hpp, TableWidget gains (default: does nothing) +virtual void setStatus(TableStatus const& status); +virtual void setOnRetry(std::function onRetry); +/// A cell's load state; called after the row's key, and on every change. `Unloaded`: a placeholder of a fixed width +/// in the column's alignment; `Failed`: an error mark of the same width. Neither widens the column. +virtual void setCellLoad(Widget& row, std::size_t column, CellLoad load); + +// mount.hpp +struct MountStats { + std::size_t cellBinds = 0; // sets of a cell's row signal that changed its record (each re-evaluates the cell) + std::size_t rowBinds = 0; // sets of a realized row's own signal that changed its record (`rowView`'s) + std::size_t cellsCreated = 0; // `cellView` calls: cell widgets built + std::size_t cellsRebound = 0; // pooled cells bound to another row or column (Task 10a; 0 before) +}; +// Mounted gains: [[nodiscard]] MountStats const& stats() const noexcept; // the whole mount's, for tests + +// interpreter.hpp, RtScope gains +/// Called with a field a row expression read that the row's record does not hold; set on a server-mode row scope. +std::function const* onMissingRowField = nullptr; + +// interpreter.hpp +/// How long a status-line message stays, unless the next gesture on the table clears it first. +inline constexpr std::chrono::seconds kStatusMessageHold{6}; +// ScreenCore gains (src/ui/interpreter.cpp): +/// Shows @p text as the table's status-line message for `kStatusMessageHold`; an empty @p text clears it. +void tableMessage(ElementState& table, std::string text); +``` + +Decisions: +- The mount over a `TableSource`: rows are always windowed (a server-mode table is); `setRealizedWindow(first, count, total)` with `total = rows->total().rows`; a realized index whose `row()` is empty mounts a placeholder row of the estimated height and becomes a keyed row when it arrives; `onChange` applies the `ViewChange` to the keyed realized rows, so a row keeps its widget, native state and selection when it moves; the visible range and the columns (`alwaysFetched` plus the laid-out columns' ids) go to `rows->visible`. +- Cells (cross-part decision 28). A realized row has its own `reactive::Signal` (for `rowView`) and, per laid-out column, a cell: `{reactive::Signal row; Node view; widget}`, the view built once by `cellView(column, cell.row)` (`cellsCreated`). The mount sets a row's signal and each of its cells' signals to the record `rows->row(index)->row` when the row is realized, and again for every row a `ViewChange` names as updated; nothing else sets them. Each set that changes the held value (the signal's `EqualityPolicy::Auto` skips an equal one, `signal.hpp:90`) counts one `rowBinds` or one `cellBinds`. So F6's arrival for 50 rows of 20 columns is 1,000 `cellBinds` and 50 `rowBinds`, and K5's refetch that changed 20 of 200 rows is 20 `rowBinds`. Cells are not pooled in this task; Task 10a pools exactly these cells, and `cellsRebound` stays 0 until then. +- Cell load state (cross-part decision 29). For each realized cell of column `c`: `Loaded` when `levels[c]` is empty or not in `rows->unloadedLevels(index).levels`; `Failed` when it is in `.failed`; otherwise `Unloaded`. The mount calls `setCellLoad(row, c, load)` after the row's key and whenever a `ViewChange` updates the row, only when the state changed. The recording backend records it; Qt Quick and the terminal draw it in Task 10b. The cell's own view stays mounted and bound under a placeholder, so a level's arrival is one `setCellLoad(…, Loaded)` and one bind, not a new cell. +- The loader (`src/ui/document.cpp`, cross-part decision 44). Today it refuses every document this task lowers: a `table` with a `model` must name an `action` (`document.cpp:3125-3129`), `kTableKeys` (`:293`) holds none of `table`, `status`, `persist`, and a key it does not list is ignored (`:583`). This task: + - adds to `kTableKeys` `{"table", Shape::Name}`, `{"status", Shape::Flag}` (a literal `true` or `false`; absent is the default) and `{"persist", Shape::Expr}` checked to be a literal `true`, `false` or non-empty string (`"`persist` is a literal: true, false or a name"`); + - accepts `model` with `table` and no `action`: the alias is checked as `checkModelAction` checks it (`:2600`, "a model alias of this scope"), and, with a catalog, `Table.
` and `Table.
.describe` must both be in it and belong to the alias's model type (`"the table `
` is not in the catalog"`, or `checkModelAction`'s "belongs to" text); + - refuses `table` together with `action` (`"a table names a `table` or an `action`, not both"`), and `table` without `model` (`"`table` names one of a model's tables; give the table its `model`"`); + - reads a `filters` written as the literal `FilterSpec` object — an object whose only members are `columns` and `groups`, such as `{"columns":{"name":{"include":[{"contains":"a"}]}}}` — as that literal, checked by `glz::read_json` (`"`filters` is not a filter: "`); any other value is an expression, as today. On a table over `rows` the key is still refused (`checkRowsTableKeys`) until Task 12; + - keeps `model` with `action` and no `table` loading as it does today; it stays "not yet lowered" until 11c; + - keeps `checkTablePaging` (`:3276`) as it is: `pageSize` and `page` on a model-backed table are refused at load, which is what table.md says ("Refused on a model-backed table"). + `model` is a model alias the document declares in `models`, never a type name, so every test document has a `models` block (`kModelTable`, Global Constraints). +- Before the description, and when it changes. `Table::columns` is set once (`view.hpp:1253`), and so are `TableSource::levels` and the indices `cellView` takes, while the description arrives after the mount and may take a new revision later. The lowering therefore does not return a `Table`: it returns a `ForEach` of at most one row, keyed by the held description's `revision`, whose row view is the `Table` built from that description. With no description held (before the first `describe` reply, or after one that failed) the list is empty and the node draws its status line alone, through a `Table` with no columns and no source under the key `""`, so the line's place does not jump; `empty` is not shown. A new revision is a new key: the `Table` is mounted again from the new description. What lives in the element's state and not in that row — the `WindowRows` and its window, the sort chain, the filters, the selection, the status message, the kept persisted state — survives; what is the mount's — realized rows, cells, measured widths and the scroll offset — is built again; the `WindowRows` keeps the range it was last given, so the query its new description starts asks for the rows that were visible, and the new mount then names its own. A revision change is a deployment or a change of the caller's rights, so one rebuild is the accepted cost, and it is what keeps `Table::columns` a set-once member. +- The lowering: `model` with `table` binds the model's channel as any query does, makes a document query on `Table.
.describe` (one per mounted table, W6) and a `WindowRows` with `restoring` set when the session has a store and `persist` is not `false`. Columns: the description's columns with `shown`, overridden per id by the node's `columns` parts; a node with `columns` lays out those; each `ui::TableColumn::id` is the column's id. `cellView` lowers the column's `cell` (or a default text cell of the record's field, as a `rows` table's is: a record holds `Value`s, not cells) in a row scope over the cell's signal; `rowView` lowers `rowTone` and `rowLabel` in a row scope over the row's signal. `alwaysFetched`: the description's key, plus the fields `rowTone`, `rowLabel` and `onActivate` name as `{"row": ""}` (found when the table is lowered), plus every column when any of them, or a column's `cell`, passes the row on whole (`{"row": ""}` other than as the source of a `get`), reported once as a warning naming the node. A column's `cell` reads in its own cell, so its fields belong in `visible` only while that column is in the window; with no column window before Task 10a they are added to `alwaysFetched`, and 10a moves them. A `get` out of the whole row is the row's own read, which `onMissingRowField` names at run time. A row look carries `keep`, what its parts need alive (the row scope `onActivate` runs in), which the mount holds with the row. `levels`: each laid-out column's `ColumnInfo::level` from the description. +- `RtScope::onMissingRowField` on a server-mode row scope. Its handler is called from inside a binding's evaluation, where a signal write is refused and reported (`signal.hpp:117-124`, `kSetInComputed`), so it does no work there: it adds the field to a pending set and, when the set was empty, posts one task with `runtime.owner().post`. That task adds the pending fields to the table's extra columns and calls `rows->visible` once with them (one fetch for every miss of one turn), then clears the set. A field that is not a described column id is dropped by `WindowRows::visible`, as any id its description lacks, with no fetch and no report (it reads as absent, as any missing field does); it is never sent, since the server would refuse the query with `UnknownColumn`. A field already in the extra set is not added again. The read is `null` meanwhile, as the spec says it reads as absent; when the column arrives, the row's record gains the field and the binding runs again. +- `pageSize`/`page` on a model-backed table are refused at load (the existing check, `checkTablePaging`); `body` is the query's fixed part; header sorts and `filters` go to `setSort`/`setFilter`. +- State: key `{application = SessionOptions::application, model = , table =
, qualifier = persist string or the screen's id, part = "state"}`. The load starts at mount; when it completes within `tableStateTimeout` the fitted sort and filters are applied (bound `sort` or `filters` are the document's and are neither applied nor saved; a literal `sort` is the default a stored one replaces) and `release()` is called; past the timeout `release()` is called with the defaults and a later state is applied (one more query) unless the user scrolled, selected or changed the arrangement meanwhile. A failed load is reported once through the session and changes still save. The stored layout part is carried unchanged in this task: nothing here changes a layout. +- What a dropped part is reported as. `WindowRows::setDescription` and the lowering's use of `fitState` follow one rule, 9b's: a dropped `Filter`, `GroupFilter` or `Unit` is reported once at the table's path; a dropped `Column`, `SortKey` or `Group` is not. So a sort key and a filter on a column a new revision lacks are one diagnostic, the filter's. +- A stored document that does not read (Review Focus 3). `readState` refusing the loaded text is reported once at the table's path (`"the stored state of table `` is not used: "`), the table starts from its defaults and `release()` is called; nothing is saved until the user changes something, and that save is 9c's: a `kStateVersion` document of the changed parts. +- A save that did not end `Saved`. The session's `TableStates::onSaveFailed` handler (9c) calls `ScreenCore::tableMessage` on every mounted table whose key it names, with `"The table's arrangement could not be saved: "` (the reason alone when it is empty of one: `"The table's arrangement could not be saved"`), so under `status: false` it reaches `InterpreterHost::notify`. The table keeps the arrangement it shows; the next change saves again. +- Two things 9a leaves to this step. A failed fetch reaches `WindowRows::error()` as `TableError{Unavailable, }`: an action refusal's `table.` (`QueryTable::invoke` throws it) is not read back into `TableError::code`, so a status line that names the refusal reads it here. And `WindowRowsOptions::body`'s `query` record is overlaid by the window's own `sort`, `filters`, `page`, `columns`, `keys` and `retry`: a fixed filter in `body.query.filters` is replaced, not combined; decide here whether a node's fixed filter is combined with the header's. +- `status`: a model-backed table's `shown` is always true; the counts are `countsText(counts(), selectedCount, formatting)`; a fetch error fills `state` with `"The rows could not be loaded: "` and a failed level with `" data could not be loaded."`, both with `retry = true`, whose handler calls `WindowRows::retry`. A failed fetch changes no row, so `WindowRows::onStatus` tells the lowering of it (and of every fetch sent or answered), which bumps what the status line reads. A `body`'s `query` member is replaced by the table's own: a node's default filter is its literal `filters`, which a stored one replaces. +- Messages (cross-part decision 11). `ScreenCore::tableMessage(ElementState& table, std::string text)` is the one channel every later task posts a transient refusal or notice through (Parts E, F, G). A non-empty `text` sets `TableStatus::message` and (re)starts a `kStatusMessageHold` timer on `SessionOptions::scheduler`; when it fires and the message is still that text, the message is cleared. An empty `text` clears the message and the timer and notifies nothing; the lowering calls `tableMessage(table, "")` on each user gesture on the table this task lowers (a header click, a selection change, a scroll report, Retry), and later parts do the same for theirs. Under `status: false` a non-empty `text` is sent once to `InterpreterHost::notify(text, "warning")` (`interpreter.hpp:290`) and `TableStatus::message` stays empty. With no scheduler the message stays until the next gesture. +- `empty` on a model-backed table shows only when `total().known`, `total().rows == 0`, `kind == Exact` and `counts().undecided == 0`. + +- [ ] **Step 1: Write the failing tests.** `tests/ui_table_support.hpp` gains `TableHarness` (Global Constraints) and these, each defined once and reused by every later task: + +- `TableHarness()` and `TableHarness(std::shared_ptr)`, which sets `SessionOptions::tableState` and `application = "lims"`. `h.host` is a `NotifyingHost` (an `InterpreterHost` that records every `notify(text, role)` in `notified`, a `std::vector>`; `RecordingHost` is `final`). +- What `TableHarness` offers, by name, because Parts E, F and G call it: the members `mount`, `settle`, `advance`, `reply`, `fail`, `find`, `byTestId` and `text` with the signatures the existing `Harness` has (`ui_interpreter_support.hpp:470`), `dispatcher` (with `count`, `last`, `calls`), `backend`, `host` (with `notified`), `diagnostics`, `columns`. Widgets are looked up as `h.backend.find("Table", "testId", …)`. +- The catalog's extension seam, which later tasks use for their own actions: `TableHarness::extraActions`, a `std::map, std::less<>>` (action id → its request schema's JSON text and its `ActionInfo`), and the free function `addAction(TableHarness& h, std::string id, std::string schemaJson, ActionInfo info)`, which inserts into it. The harness's catalog is built so that its `Catalog::action` and `Catalog::schema` look in `h.extraActions` first and in `tableCatalog()` after; both the session's catalog and the one `mount` loads against are that catalog, so an action added before `mount` is known to the loader and to the session alike. +- `elementValue(screen, id, name)` is the JSON text of the element value `name` of the element `id` of a screen (`readJson(screen, {"ref":"."})`), such as `elementValue(*screen, "list", "viewCount")`: the harness does not keep the screen it mounted. +- `rowKeys(TableHarness&, int table)` is not defined here: Task 13 adds it (the realized rows' keys in child order, a text key's quotes removed), and nothing in this part uses that name. +- `tableOf(h)` is `h.backend.find("Table", "testId", "list")`. A header click is `h.backend.clickHeader(tableOf(h), column)` followed by `h.settle()`; a scroll is the existing `h.backend.scrollTable(tableOf(h), first, count)`. +- `replyDescribe(h, description = samplesDescription(3))` answers the open `Table.samples.describe` call with `describeJson(table::describe(description))` and makes it `h.described`; `replyPage(h, json)` answers the oldest open `Table.samples` call (open: neither answered nor stopped); `answerPages(h, total, kind, undecided, awaiting)` answers every open `Table.samples` call with its own page, against `h.described`'s revision, until none is open; `mountShown(h, text = kModelTable, total = 9093)` mounts, replies the description and every page fetch (`answerPages`) and returns the screen. The window covers the page before and the page after the rows in view, so the page next to a held one is fetched as soon as that one arrives, and a first query after `tableSettle` asks for both at once: the cases count calls from a mark, answer every page before a check that needs none in flight (`pending`), and find the call they mean by its offset or its columns rather than by its being the latest. A page against another description than `samplesDescription(3)` is written with `pageJsonAt(revision, …)` and `keyedJsonAt(revision, …)`. +- `lastQuery(h)` is the `table::TableQuery` read from the latest `Table.samples` call's body; `statusOf(h)` the `TableStatus` the table widget was last given; `headerLabels(h)` its header captions; `diagnosticsMentioning(h, text)` the count of `h.diagnostics` whose reason contains `text`; `change(h, keys)` delivers a change of `Lims_SampleModel.samples` with those keys, and with none (`RecordChange::keys` absent: every row changed) for an empty list, which is how "the page again" is asked for; `shownText(h, text)` whether a text is mounted and no column around it is hidden, since `RecordingBackend::find` finds hidden widgets too. +- `statsOf(screen)` is `Mounted::stats()`, `coreOf(screen)` its `ScreenCore` and `elementOf(screen, id)` an element's state (`Screen` befriends the file's `ScreenProbe`). +- `RecordingBackend` gains `cellLoad(table, rowKey, column) -> CellLoad` (the last `setCellLoad`, `Loaded` when none), `retryTable(table)`, `tableStatus(table)` and `tableColumns(table)`. `samplesDescription` labels its columns as a server does (`Id`, `Name`, `C3`), and `tableCatalog()` answers no table's actions but `samples`'s. `GatedTableStateStore` is 9c's; it also holds saves after `holdSaves()` until `releaseSave()`. +- `kStored` is `{"version":1,"sort":[{"column":"name","direction":"desc"}],"filters":{"columns":{"name":{"include":[{"contains":"a"}]}}}}`; `kBoundSort` is `kModelTable` with `"state":{"order":{"init":{"lit":[{"column":"id","direction":"asc"}]}}}` and, on the table, `"sort":{"ref":"order"}`; `kNoPersist` is `kModelTable` with `"persist":false`; `kNoStatus` with `"status":false`. + +In `tests/test_ui_table_model.cpp`, beside the table cases, since `tests/test_ui_document.cpp` cannot include the table support (`refusalOf(text)` loads against `tableCatalog()` and returns the refusal's reason): + +```cpp +// Mutations: `table` left out of kTableKeys (the first REQUIRE: "names its `action`"); no catalog check of +// `Table.` (the "nosuch" CHECK loads). +TEST_CASE("ui document: a model-backed table names a table of its model", "[ui][document]") { + REQUIRE(loads(kModelTable, tableCatalog())); + CHECK(loads(kNoPersist, tableCatalog())); CHECK(loads(kNoStatus, tableCatalog())); + CHECK(refusalOf(withTableKey(kModelTable, R"("table":"nosuch")")) == "the table `nosuch` is not in the catalog"); + CHECK(refusalOf(withTableKey(kModelTable, R"("action":"Lims_ListSamples")")) == + "a table names a `table` or an `action`, not both"); + CHECK(refusalOf(withTableKey(kModelTable, R"("model":"Lims_SampleModel")")) == + "`Lims_SampleModel` is not a model alias of this scope"); // a type is not an alias + CHECK(refusalOf(withTableKey(kModelTable, R"("persist":{"ref":"x"})")) == + "`persist` is a literal: true, false or a name"); + CHECK(loads(withTableKey(kModelTable, R"("filters":{"columns":{"name":{"include":[{"contains":"a"}]}}})"), tableCatalog())); + CHECK(refusalOf(withTableKey(kModelTable, R"("filters":{"columns":7})")).starts_with("`filters` is not a filter")); + CHECK(refusalOf(withTableKey(kModelTable, R"("pageSize":20)")) == + "a model-backed table's engine pages; `pageSize` and `page` are for a table over `rows`"); +} +``` +`withTableKey(text, member)` replaces the table node's member of that name, or adds it. + +In `tests/test_ui_table_model.cpp`: + +```cpp +// Mutation: a lowering that needs the node's `columns` (no header: `headerLabels` is empty). +TEST_CASE("model table: a client given only the catalog draws its columns, sorts and pages it", "[ui][table]") { + TableHarness h; auto screen = h.mount(kModelTable); + CHECK(h.dispatcher.count("Table.samples.describe") == 1); + CHECK(h.dispatcher.count("Table.samples") == 0); // no page before its description + replyDescribe(h); + REQUIRE(h.dispatcher.count("Table.samples") == 1); + replyPage(h, pageJson(0, 200, 9093, h.columns)); + CHECK(headerLabels(h) == std::vector{"Id", "Name", "C3"}); + CHECK(h.backend.find("Text", "text", "row-0").has_value()); // the default cell, by its stand-in text + CHECK(statusOf(h).counts == "9,093 rows"); CHECK(statusOf(h).shown); + h.backend.clickHeader(tableOf(h), 1); h.settle(); + CHECK(lastQuery(h).sort == table::SortChain{{.column = "name"}}); + replyPage(h, pageJson(0, 200, 9093, h.columns)); + h.backend.scrollTable(tableOf(h), 4'000, 30); h.advance(80ms); + CHECK(lastQuery(h).page.offset == 4'000); // the window pages + CHECK(h.dispatcher.count("Table.samples.describe") == 1); // W6: one request +} +// Mutation: a literal `filters` read as an expression (it evaluates to null and the query carries no filter). +TEST_CASE("model table: a literal filter and the element values reach the query and the document", "[ui][table]") { + TableHarness h; + auto screen = h.mount(withTableKey(kModelTable, R"("filters":{"columns":{"name":{"include":[{"contains":"a"}]}}})")); + replyDescribe(h); + REQUIRE(h.dispatcher.count("Table.samples") == 1); + REQUIRE(lastQuery(h).filters.columns.contains("name")); + CHECK(lastQuery(h).filters.columns.at("name").include.size() == 1); + CHECK(elementValue(h, "list", "pending") == "true"); + replyPage(h, pageJson(0, 200, 9093, h.columns, table::TotalKind::AtLeast, /*undecided*/ 40, {"recipe"})); + CHECK(elementValue(h, "list", "viewCount") == "9093"); + CHECK(elementValue(h, "list", "viewCountKind") == R"("atLeast")"); + CHECK(elementValue(h, "list", "undecided") == "40"); + CHECK(elementValue(h, "list", "awaiting") == R"(["recipe"])"); + CHECK(elementValue(h, "list", "failed") == "[]"); + CHECK(elementValue(h, "list", "pending") == "false"); +} +// Mutation: a table that ignores its store sends the default query (the count is 1 before `release`). Gate T3. +TEST_CASE("model table: persisted state before the first query", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), kStored); + TableHarness h{store}; + auto screen = h.mount(kModelTable); replyDescribe(h); + CHECK(h.dispatcher.count("Table.samples") == 0); + CHECK(store->lastLoadKey() == table::TableStateKey{.application = "lims", .model = "Lims_SampleModel", + .table = "samples", .qualifier = "samples", .part = "state"}); + store->release(); h.settle(); + REQUIRE(h.dispatcher.count("Table.samples") == 1); + CHECK(lastQuery(h).sort == table::SortChain{{.column = "name", .dir = table::SortDirection::Descending}}); + CHECK(lastQuery(h).filters.columns.contains("name")); +} +// Mutations: no debounce (fifty saves); unmount not flushing (the count stays 1); a change during a save dropped. +TEST_CASE("model table: saves are coalesced, and unmounting saves at once", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), R"({"version":1})"); + TableHarness h{store}; + auto screen = h.mount(kModelTable); replyDescribe(h); store->release(); h.settle(); + for (int i = 0; i < 50; ++i) { h.backend.clickHeader(tableOf(h), i % 2 == 0 ? 0 : 1); h.advance(5ms); } + CHECK(store->saves() == 0); // inside the debounce + h.advance(500ms); CHECK(store->saves() == 1); + CHECK(table::readState(store->lastSaved())->sort->at(0).column == "name"); // the last of the fifty + store->holdSaves(); + h.backend.clickHeader(tableOf(h), 0); h.advance(500ms); CHECK(store->saves() == 2); // in flight, held + h.backend.clickHeader(tableOf(h), 1); h.advance(500ms); CHECK(store->saves() == 2); // one per key in flight + store->releaseSave(); h.settle(); CHECK(store->saves() == 3); // one more after it + store->releaseSave(); h.settle(); + h.backend.clickHeader(tableOf(h), 0); screen.reset(); h.settle(); + CHECK(store->saves() == 4); // at once, no debounce +} +// Mutations: applying a late state after the user scrolled (a second query in the second section); a failed load +// reported per table mount or not at all; a failed load that stops saving. +TEST_CASE("model table: a slow or failed load", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), kStored); + TableHarness h{store}; + auto screen = h.mount(kModelTable); replyDescribe(h); + h.advance(299ms); CHECK(h.dispatcher.count("Table.samples") == 0); + h.advance(1ms); REQUIRE(h.dispatcher.count("Table.samples") == 1); // defaults after tableStateTimeout + CHECK(lastQuery(h).sort.empty()); + replyPage(h, pageJson(0, 200, 9093, h.columns)); + SECTION("the late state is applied") { + store->release(); h.settle(); + REQUIRE(h.dispatcher.count("Table.samples") == 2); // one more query + CHECK(lastQuery(h).sort.at(0).column == "name"); + } + SECTION("not under the user's hands") { + h.backend.scrollTable(tableOf(h), 40, 30); h.settle(); // within the held page: no fetch + store->release(); h.settle(); + CHECK(h.dispatcher.count("Table.samples") == 1); + CHECK(lastQuery(h).sort.empty()); + } + SECTION("a failed load") { + store->fail(); h.settle(); + CHECK(diagnosticsMentioning(h, "state") == 1); // reported once + CHECK(h.dispatcher.count("Table.samples") == 1); + h.backend.clickHeader(tableOf(h), 1); h.advance(500ms); + CHECK(store->saves() == 1); // changes still save + } +} +// Mutations: applying a stored sort over a bound one (the query sorts by name); saving a bound sort (the saved +// document has a `sort`); `persist: false` still loading. +TEST_CASE("model table: bound values win", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), kStored); + TableHarness h{store}; + SECTION("a bound sort") { + auto screen = h.mount(kBoundSort); replyDescribe(h); store->release(); h.settle(); + REQUIRE(h.dispatcher.count("Table.samples") == 1); + CHECK(lastQuery(h).sort == table::SortChain{{.column = "id"}}); // the document's + CHECK(lastQuery(h).filters.columns.contains("name")); // the stored filter still applies + screen.reset(); h.settle(); CHECK(store->saves() == 0); // nothing changed, nothing saved + } + SECTION("persist: false") { + auto screen = h.mount(kNoPersist); replyDescribe(h); h.settle(); + CHECK(store->loads() == 0); + REQUIRE(h.dispatcher.count("Table.samples") == 1); // no restoring state + h.backend.clickHeader(tableOf(h), 1); h.advance(500ms); screen.reset(); h.settle(); + CHECK(store->saves() == 0); + } +} +// Review Focus 3, the table's half. Mutations: no report (the count is 0); the stored text saved back unchanged. +TEST_CASE("model table: a stored state that does not read starts from the defaults", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), R"({"version":2,"junk":true})"); + TableHarness h{store}; + auto screen = h.mount(kModelTable); replyDescribe(h); store->release(); h.settle(); + REQUIRE(h.dispatcher.count("Table.samples") == 1); CHECK(lastQuery(h).sort.empty()); + CHECK(diagnosticsMentioning(h, "the stored state of table `list` is not used") == 1); + h.advance(1'000ms); CHECK(store->saves() == 0); // nothing written until a change + h.backend.clickHeader(tableOf(h), 1); h.advance(500ms); + REQUIRE(store->saves() == 1); + CHECK_FALSE(store->lastSaved().contains("junk")); + CHECK(table::readState(store->lastSaved())->version == table::kStateVersion); +} +// Invariant 31. Mutation: `onSaveFailed` not wired to `tableMessage` (the message stays empty). +TEST_CASE("model table: a refused save is said in the status line and keeps the arrangement", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), R"({"version":1})"); + TableHarness h{store}; + auto screen = h.mount(kModelTable); replyDescribe(h); store->release(); h.settle(); + store->refuseSaves("over the table-state quota"); + h.backend.clickHeader(tableOf(h), 1); h.advance(500ms); + CHECK(statusOf(h).message == "The table's arrangement could not be saved: over the table-state quota"); + CHECK(lastQuery(h).sort.at(0).column == "name"); // the arrangement stays + CHECK(h.backend.prop(tableOf(h), "sort") == "1:Ascending"); +} +// Mutation: the mount leaving out the rows a `Changed` operation names (rowBinds 0). Setting every realized row's +// signal would fail nothing: a set of an equal record changes nothing and is not counted. Gate K5. +TEST_CASE("model table: a refetch that changed 20 of 200 rows evaluates 20 rows again", "[ui][table]") { + TableHarness h; auto screen = mountShown(h); + h.backend.scrollTable(tableOf(h), 0, 30); h.settle(); // rows 0 to 39 realized (overscan 10) + MountStats const before = statsOf(*screen); + change(h, std::vector{}); // a change without keys: the page again + // the same page, with rows 0 to 19 renamed and rows 20 to 199 as they were + replyPage(h, pageJsonRenaming(0, 200, 9093, h.columns, /*renamed*/ 0, 20)); + CHECK(statsOf(*screen).rowBinds - before.rowBinds == 20); // K5 + CHECK(statsOf(*screen).cellsCreated == before.cellsCreated); + CHECK(h.backend.find("Text", "text", "renamed-0").has_value()); +} +// Review Focus 1. Mutation: setDescription not dropping keys and filters on a removed column (the query names c3). +TEST_CASE("table rows: a new description revision drops what names a removed column", "[ui][table]") { + auto store = std::make_shared(storeExecutor(), + R"({"version":1,"sort":[{"column":"c3","direction":"asc"}],"filters":{"columns":{"c3":{"include":[{"gt":"1"}]}}}})"); + TableHarness h{store}; + auto screen = h.mount(kModelTable); replyDescribe(h); store->release(); h.settle(); // revision A: id, name, c3 + REQUIRE(lastQuery(h).sort.at(0).column == "c3"); + table::TableDescription const b = table::describe(samplesDescription(2)); // revision B: id, name + replyPage(h, pageJsonAt(b.revision, 0, 200, 9093, h.columns)); // a reply names another revision + CHECK(h.dispatcher.count("Table.samples.describe") == 2); // exactly one more describe + replyDescribe(h, samplesDescription(2)); + table::TableQuery const q = lastQuery(h); + CHECK(std::ranges::none_of(q.sort, [](auto const& key) { return key.column == "c3"; })); + CHECK_FALSE(q.filters.columns.contains("c3")); + REQUIRE(q.columns.has_value()); + CHECK(std::ranges::find(*q.columns, "c3") == q.columns->end()); + CHECK(diagnosticsMentioning(h, "c3") == 1); // the filter; a sort key is not reported + CHECK(headerLabels(h) == std::vector{"Id", "Name"}); // mounted again from revision B + CHECK(h.dispatcher.count("Table.samples.describe") == 2); // once per revision +} +// Review Focus 2. Mutation: the load completion capturing the table by reference with no liveness check (a query +// is sent, or the test crashes under the sanitizer build). +TEST_CASE("model table: unmounted while its state load is held", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), kStored); + TableHarness h{store}; + auto screen = h.mount(kModelTable); replyDescribe(h); + h.backend.clickHeader(tableOf(h), 0); h.settle(); // nothing loaded yet: the change is held, not saved + CHECK(store->saves() == 0); + screen.reset(); h.settle(); + store->release(); h.settle(); + CHECK(h.dispatcher.count("Table.samples") == 0); // nothing applied, no query + REQUIRE(store->saves() == 1); // the held change, over the loaded document + CHECK(store->lastSaved().contains(R"("contains":"a")")); // the stored filter kept + CHECK(table::readState(store->lastSaved())->sort->at(0).column == "id"); +} +// Review Focus 4. Mutation: `empty` shown while `total().known` is false, or while rows are undecided. +TEST_CASE("model table: empty waits for the first reply and for undecided rows", "[ui][table]") { + TableHarness h; auto screen = h.mount(kModelTable); + CHECK_FALSE(h.backend.find("Text", "text", "No samples")); // before the description + replyDescribe(h); + CHECK_FALSE(h.backend.find("Text", "text", "No samples")); // before any page + CHECK(statusOf(h).counts.empty()); CHECK(statusOf(h).shown); + replyPage(h, pageJson(0, 0, 0, h.columns, table::TotalKind::AtLeast, /*undecided*/ 40)); + CHECK_FALSE(h.backend.find("Text", "text", "No samples")); + CHECK(statusOf(h).counts == "0 so far, 40 loading"); + change(h, std::vector{}); // the level arrived: the page again + replyPage(h, pageJson(0, 0, 0, h.columns)); + CHECK(h.backend.find("Text", "text", "No samples")); + CHECK(statusOf(h).counts == "0 rows"); +} +// Mutations: a status line built without `failed` (no state, no retry); Retry sending the query without `retry`. +TEST_CASE("model table: a failed level offers Retry, which sends `retry`", "[ui][table]") { + TableHarness h; auto screen = h.mount(kModelTable); + replyDescribe(h, withLevel(samplesDescription(3), "c3", "recipe")); + replyPage(h, pageJsonUnloaded(0, 200, 9093, h.columns, {{.index = 1, .levels = {"recipe"}, .failed = {"recipe"}}}, + /*failed*/ {"recipe"})); + CHECK(statusOf(h).state == "Recipe data could not be loaded."); + REQUIRE(statusOf(h).retry); + std::size_t const sent = h.dispatcher.count("Table.samples"); + h.backend.retryTable(tableOf(h)); h.settle(); + REQUIRE(h.dispatcher.count("Table.samples") == sent + 1); + CHECK(lastQuery(h).retry); +} +// Mutation: a page refetch per event (the call names no `keys`, or twenty calls go out). Gate E3 on a screen. +TEST_CASE("model table: an arrival is one keyed request", "[ui][table]") { + TableHarness h; auto screen = mountShown(h); + std::size_t const sent = h.dispatcher.count("Table.samples"); + std::vector keys(20); std::ranges::iota(keys, std::int64_t{0}); + change(h, keys); + REQUIRE(h.dispatcher.count("Table.samples") == sent + 1); // exactly one more call + REQUIRE(lastQuery(h).keys.has_value()); + CHECK(lastQuery(h).keys->size() == 20); // the twenty keys; the run's probe is key 0 +} +// Mutation: the mount ignoring unloadedLevels (every cell Loaded). Cross-part decision 29. +TEST_CASE("model table: a cell of an unloaded level is a placeholder, of a failed one an error mark", "[ui][table]") { + TableHarness h; auto screen = h.mount(kModelTable); + replyDescribe(h, withLevel(samplesDescription(3), "c3", "recipe")); // column 2 has the level + replyPage(h, pageJsonUnloaded(0, 200, 9093, h.columns, + {{.index = 0, .levels = {"recipe"}, .failed = {}}, + {.index = 1, .levels = {"recipe"}, .failed = {"recipe"}}}, /*failed*/ {"recipe"})); + int const table = tableOf(h); + CHECK(h.backend.cellLoad(table, Key{std::int64_t{0}}, 2) == CellLoad::Unloaded); + CHECK(h.backend.cellLoad(table, Key{std::int64_t{0}}, 1) == CellLoad::Loaded); // name has no level + CHECK(h.backend.cellLoad(table, Key{std::int64_t{1}}, 2) == CellLoad::Failed); + CHECK(h.backend.cellLoad(table, Key{std::int64_t{2}}, 2) == CellLoad::Loaded); + auto const created = statsOf(*screen).cellsCreated; + change(h, std::vector{0}); // the level arrives for row 0 + replyPage(h, keyedJson({{0, 0}}, 9093, h.columns)); // a keyed reply, the level loaded + CHECK(h.backend.cellLoad(table, Key{std::int64_t{0}}, 2) == CellLoad::Loaded); + CHECK(statsOf(*screen).cellsCreated == created); // the same cell, bound again +} +// Mutations: the miss fetched inside the binding (a signal write is refused there: the debug build aborts); +// `WindowRows::visible` keeping an id the description lacks (the query names "nosuch"). +TEST_CASE("model table: a row field the window lacks is fetched once, after the binding", "[ui][table]") { + // kReadsAcross: kModelTable with "columns":[{"id":"id"},{"id":"name","cell":[{"kind":"text","text":{"get": + // {"row":""},"path":"c7"}},{"kind":"text","text":{"get":{"row":""},"path":"nosuch"}}]}], over + // samplesDescription(8): c7 is described and not laid out. Each read is its own text: a `concat` whose first + // argument is `null` never reads the second. A document names a row field as {"row": ""}, + // which the lowering finds; a `get` out of the whole row it does not, so the binding misses c7 at run time. + // The checks count the calls since the reply that name c7 (exactly one, for page 0), not every call: the + // page next to the first is fetched as soon as the first arrives. + TableHarness h; auto screen = h.mount(kReadsAcross); replyDescribe(h, samplesDescription(8)); + std::vector const laidOut{"id", "name"}; + std::size_t const before = h.dispatcher.count("Table.samples"); + h.dispatcher.reply(h.dispatcher.last("Table.samples"), pageJson(0, 200, 9093, laidOut)); // no settle yet + h.owner.runOne(); // the reply is accepted, cells bind + CHECK(h.diagnostics.empty()); // no write refused inside a binding + h.settle(); + CHECK(h.dispatcher.count("Table.samples") == before + 1); // one fetch for every row's miss + REQUIRE(lastQuery(h).columns.has_value()); + CHECK(std::ranges::find(*lastQuery(h).columns, "c7") != lastQuery(h).columns->end()); + CHECK(std::ranges::find(*lastQuery(h).columns, "nosuch") == lastQuery(h).columns->end()); +} +// Mutations: no hold timer (the message is still there after six seconds); `status: false` still filling +// `message`; an empty text notifying. +TEST_CASE("model table: a message lasts six seconds or until the next gesture", "[ui][table]") { + SECTION("in the status line") { + TableHarness h; auto screen = mountShown(h); + detail::ScreenCore& core = coreOf(*screen); ElementState& list = elementOf(*screen, "list"); + core.tableMessage(list, "Refused"); h.settle(); CHECK(statusOf(h).message == "Refused"); + h.advance(5'999ms); CHECK(statusOf(h).message == "Refused"); + h.advance(1ms); CHECK(statusOf(h).message.empty()); + core.tableMessage(list, "Again"); h.settle(); + h.backend.clickHeader(tableOf(h), 1); h.settle(); CHECK(statusOf(h).message.empty()); // the next gesture + core.tableMessage(list, ""); h.settle(); CHECK(h.host.notified.empty()); // notifies nothing + } + SECTION("status: false") { + TableHarness h; auto screen = mountShown(h, kNoStatus); + coreOf(*screen).tableMessage(elementOf(*screen, "list"), "Refused"); h.settle(); + CHECK(h.host.notified == std::vector>{{"Refused", "warning"}}); + CHECK(statusOf(h).message.empty()); CHECK_FALSE(statusOf(h).shown); + } +} +``` +Helpers these cases add to `tests/ui_table_support.hpp`: `storeExecutor()` (a `StepExecutor` the harness's `settle()` also runs, declared before the harness so a store can be built first); `pageJsonRenaming(offset, count, total, columns, first, n)` (`pageJson` with the names of rows `first` to `first + n − 1` written `"renamed-"`); `pageJsonAt(revision, …)` (9a's: `pageJson` with that `revision`); `withLevel(description, column, level)` (sets `ColumnInfo::level` and lists the level in `levels`); `pageJsonUnloaded(offset, count, total, columns, unloadedRows, failed)` (`pageJson` with `unloadedRows` and the page's `failed`); `keyedJson({{key, viewRow}…}, total, columns)` (9a's: a keyed reply with `indices`, each row's `name` `"renamed-"`). + +In `tests/qt_quick/test_qt_quick_table.cpp`, over the fixture's `wide` model through a scripted dispatcher (the description and pages written from `bench::WideTableSource` at 100,000 × 300, the node declaring twenty columns): + +`WideScreen` is that file's fixture for it: a 1,280 × 800 offscreen window, an interpreter over a `ScriptedDispatcher`, the document `kWideTable` (a `models` block with the alias `wide` of `WideTableModel`, a `table` node naming `wide` and twenty columns `id`, then `d000`… of the `recipe` level), `shown()` (replies the description and the first page with every `recipe` cell unloaded, then renders a frame), `arrive(keys)` (a keyed change for those keys, answered with their `recipe` cells loaded, then a frame), `stats()` (`Mounted::stats()`), `realizedKeys()` and `widthChanges(column)` (how many times the table item's width for that column changed since `shown()`). + +```cpp +// Mutation: the mount setting every cell of every realized row on a change (cellBinds counts 50 × 20 on any +// arrival, and 1,000 again for the second arrival of ten rows). Gate F6. +TEST_CASE("qt_quick model table: an arrival for 50 rows re-evaluates their 1,000 cells and no other", "[qt_quick]") { + WideScreen screen; screen.shown(); + std::vector const keys = screen.realizedKeys(); + REQUIRE(keys.size() == 50); // 30 in view, overscan 10 each side + ui::MountStats const before = screen.stats(); + screen.arrive(keys); + CHECK(screen.stats().cellBinds - before.cellBinds == 1'000); // F6 + CHECK(screen.stats().rowBinds - before.rowBinds == 50); + CHECK(screen.stats().cellsCreated == before.cellsCreated); // nothing rebuilt + ui::MountStats const again = screen.stats(); + screen.arrive({keys.begin(), keys.begin() + 10}); // the same values for ten rows + CHECK(screen.stats().cellBinds == again.cellBinds); // equal records: no bind +} +// Mutation: widen a column on every cell report (a column's count reaches 50). Gate F7. +TEST_CASE("qt_quick model table: each column grows at most once on an arrival", "[qt_quick]") { + WideScreen screen; screen.shown(); + screen.arrive(screen.realizedKeys()); + int grown = 0; + for (std::size_t column = 0; column < 20; ++column) { + CHECK(screen.widthChanges(column) <= 1); grown += screen.widthChanges(column); + } + CHECK(grown >= 1); // the loaded values are wider than a placeholder +} +``` +`cellEvaluations` is the change in `Mounted::stats().cellBinds` across the arrival (the definition is in the Decisions above: one per cell signal set that changed its record), and `rowEvaluations(h)` in K5 the change in `rowBinds`. F1 is a `[.benchmark]` case in the same file: from the page reply to the first rendered frame, recorded. + +- [ ] **Step 2: Run to verify they fail** — `cmake --build --preset cl-debug --target morph_tests` → FAIL: no `Table::source`; with the build stubbed, the loader case fails with "a `table` with a `model` names its `action`" and the model table cases fail at `mount`. +- [ ] **Step 3: Implement** the interfaces and decisions above; remove the "Not yet lowered" entry for a model-backed `table` from the interpreter. +- [ ] **Step 4: Run to verify they pass** — `ctest --test-dir build/cl-debug -R "model table|table rows|ui document" --output-on-failure` (the existing `table` suites, `test_ui_table.cpp` and `test_ui_mount.cpp`, stay green: a `Table` without `source` mounts as before); `morph_tests` green; then `cmake --build --preset cl-qt-debug --target morph_qt_quick_tests` and `ctest --test-dir build/cl-qt-debug -L qt_quick -R "model table" --output-on-failure` green. +- [ ] **Step 5: Mutations**, as named. Record F1 (and U6's F1–F7/E1–E3 figures, measured with `morph_qt_quick_tests "[.benchmark]"` on `cl-qt-release`) in table.md's Performance tables. A host whose `cl-debug` has no Qt Quick writes F6's count gate on the recording backend in `morph_tests` ("an arrival for 50 rows re-evaluates their cells and no other") and leaves F6, F7 and F1 on Qt Quick to Task 10b, which draws the load states there. +- [ ] **Step 6: Neighbouring specs and docs build.** Update the four specs listed under Docs. Run the roadmap's docs build: green. +- [ ] **Step 7: Commit** `feat(ui): the model-backed table on a screen, with stored sort and filters`. + +--- + +### Task 10: The column window (table.md step 5) + +Two commits and an exit criterion. + +#### 10a — The column window in the mount + +**Files:** +- Modify: `include/morph/ui/view.hpp` (`Virtualization` additions; `Table::arrangement`, `Table::highlight`, `Table::onSelectRange`, `Table::focus`, `Table::onFocusCell`, and the same on `TableOptions`), `include/morph/ui/mount.hpp`, `include/morph/ui/backend.hpp`, `include/morph/ui/testing/recording_backend.hpp`, `src/ui/interpreter.cpp` (range selection through `keysOf`; `maxRangeRows`; the `highlightKey` lowering), `include/morph/ui/interpreter.hpp` (`SessionOptions::maxRangeRows = 10'000`) +- Test: `tests/test_ui_mount.cpp`, `tests/test_ui_table_model.cpp` + +**Interfaces:** + +```cpp +// view.hpp +struct Virtualization { // existing members kept; added, verbatim from the spec: + std::size_t columnThreshold = 40; + std::size_t cellThreshold = 20'000; + std::size_t columnOverscan = 4; + std::size_t realizePerFrame = 240; +}; +struct TableArrangement { // which columns show, in which order, how many pinned, user widths + std::vector visible; // indices into Table::columns, in layout order; empty: every column + std::size_t pinned = 0; + std::map widths; + [[nodiscard]] bool operator==(TableArrangement const&) const = default; +}; +/// The row a linked chart highlights: its key, and the view row the server has it at. +struct TableHighlight { + Key key; + std::size_t row = 0; + [[nodiscard]] bool operator==(TableHighlight const&) const = default; +}; +/// A cell by its row's key and its column's id. +struct CellRef { + Key key; + std::string column; + [[nodiscard]] bool operator==(CellRef const&) const = default; +}; +// Table (and TableOptions, cross-part decision 41) gains: +Prop arrangement; +/// Set by the lowering once a keyed reply has given the row's view index; the mount scrolls to `row`, marks it, and +/// follows `key` through later `ViewChange`s. Disengaged: no mark. +Prop> highlight; +/// A range gesture a backend cannot resolve itself, as two view rows (a `TableSource` table's only). +std::function onSelectRange; +/// The focused cell, and its report. Task 19 re-types both from `CellRef` to `GridFocus` (cross-part decision 52), +/// so that focus can rest on a row not fetched yet; until then a focus on an unfetched view row is the mount's own. +Prop> focus; +std::function)> onFocusCell; + +// mount.hpp +struct Windowing { bool rows = false; bool columns = false; }; +[[nodiscard]] Windowing windowingOf(Virtualization const& v, std::size_t rows, std::size_t visibleColumns, bool serverMode); +class ColumnExtents { +public: + void assign(std::span widths); // visible columns, layout order + bool grow(std::size_t column, int width); // only grows; false when unchanged + void set(std::size_t column, int width); // a width the user set + [[nodiscard]] std::pair columnsAt(int offset, int viewport) const; // [first, last) + [[nodiscard]] int offsetOf(std::size_t column) const; + [[nodiscard]] int widthOf(std::size_t column) const; + [[nodiscard]] int totalWidth() const noexcept; + [[nodiscard]] std::size_t columnReads() const noexcept; // F9 counter +}; +struct ColumnWindow { std::vector columns; int leading = 0; int trailing = 0; }; // pinned, then the range +[[nodiscard]] ColumnWindow columnWindow(ColumnExtents const& extents, std::size_t pinned, int scrollX, int viewport, + std::size_t overscan); +// MountStats (9d) gains: std::size_t placeholders = 0; // cells drawn blank for the frame budget + +// backend.hpp, TableWidget gains (defaults do nothing; a backend that windows columns overrides them) +virtual void setColumnWindow(std::span columns, std::span offsets, + std::span widths, int totalWidth, std::size_t pinned); // pinned: the leading columns shown pinned +virtual void setOnHorizontalRange(std::function handler); +virtual void setHorizontalOffset(int scrollX); // anchoring +virtual void setOnSelectRange(std::function handler); +virtual void setFocusCell(std::size_t viewRow, std::size_t column); // column: an index into Table::columns (decision 37) +/// The width a cell of @p column (an index into Table::columns) measured; the mount grows the column's extent by it. +virtual void setOnColumnMeasured(std::function handler); +virtual void setOnFocusMove(std::function handler); +virtual void setCounts(std::optional rows, std::size_t columns); // nullopt: unknown (AtLeast) +virtual void scrollToRow(std::size_t viewRow); // brings a view row into view +virtual void setHighlightedRow(std::optional viewRow); // marks one row; nullopt: none +/// Places a cell of a row in a column; nothing pools it (not drawn, no place, its column blank). A backend places cells +/// by this, not by their order in the row, so a placeholder of the frame budget needs no widget. +virtual void setCellColumn(Widget& row, Widget& cell, std::optional column); +enum class FocusMove : std::uint8_t { Up, Down, Left, Right, Home, End, First, Last, PageUp, PageDown }; +``` + +Decisions: +- `windowingOf`: rows when `serverMode` or `rows >= threshold` or `rows × visibleColumns > cellThreshold`; columns when `visibleColumns > columnThreshold` or `rows × visibleColumns > cellThreshold`. +- `ColumnExtents` keeps widths in a Fenwick tree (prefix sums in O(log n), `columnsAt` by binary descent on the tree), so a width change and a lookup read O(log n) nodes; `columnReads` counts per-column width reads only. +- Pools: the pooled unit is 9d's cell — its own `reactive::Signal row`, the `Node` `cellView` built over it once, and its widget — which owns the cell's scope, so its bindings live as long as the pooled cell. Cells of the default cell of one `TextRole` share a pool keyed by role; a column with its own `cell` template has a pool keyed by its column index. A cell leaving either window is detached and pooled, its signal left as it was. One entering takes a pooled cell and is rebound by setting its signal to the record of its new row (`cellsRebound`, and one `cellBinds` when the record differs) and, for a role pool, by the mount telling it its new column; `cellView` is not called again. Only an empty pool creates a cell (`cellsCreated`). +- As built, pools are per row slot, and row slots are pooled too: the backend has no reparenting, so a cell stays in the row stack it was built in. A row that enters takes the slot (stack and cells) of one that left, its cells rebound to the new row (`cellsRebound`); within a slot, a column that leaves parks its cell (`setCellColumn(row, cell, nullopt)`) in the slot's pool of its role or column, and a column that enters takes one from there. `TableSource` gains `defaultCellView(columnSignal, rowSignal)` and `ownCell` (which columns use `cellView`), so a default cell can follow its column, and `cellReads` (each column's cell's row reads, fetched while the column is in the window). Before the backend reports a horizontal viewport every visible column is in the window, so a backend that does not window columns draws as before. +- The frame: one pass of the windowing Effect realizes or rebinds at most `realizePerFrame` cells, nearest the viewport centre first; the rest are placeholders of their column's width (`placeholders`) and are realized in later turns posted with `_rt->owner().post`, one batch of `realizePerFrame` a turn. +- Anchoring: a growth of a column left of the first fully visible unpinned column calls `setHorizontalOffset(scrollX + growth)` in the same pass. The vertical rule is the same for rows above the first visible row; the mount holds no row heights, so it is 10b's, in `MorphTable`, which measures them. +- Pinned: the first `arrangement.pinned` visible columns are always in the window; while their widths exceed half the viewport, the last pinned columns scroll with the rest (display only; `pinned` is not changed). +- Focus is `(row key, column id)`, held by the mount, reported through `Table::onFocusCell` and set from `Table::focus` (both a `CellRef` here; Task 19 re-types them, cross-part decision 52); that row and column stay realized; a focused row that leaves the view moves focus to the row now at its view index, or the last row; a move onto an unfetched index focuses the placeholder (announced as loading) and the row takes focus when it arrives; `Last` with an `AtLeast` total goes to the last row known. +- `setCounts(rows, columns)`: `rows` the view's total when `Exact`, `nullopt` under `AtLeast`; `columns` the visible column count. +- `highlightKey` (a model-backed table's only; the loader already refuses it on `rows`, `document.cpp:3306`). The document's key is `highlightKey`; what the lowering hands the mount is `Table::highlight`, because only the lowering can learn the view index of a row the window does not hold. On each change to a non-null key the lowering cancels a keyed fetch still in flight for an earlier key and sends one `TableQuery{keys = {k}, columns = [], sort, filters}` (`Table.
`, as `keysOf`'s fetches go); the reply's `indices[0]` (Task 4) is the row's view index `i`, and the lowering sets `highlight` to `TableHighlight{k, i}`. The mount, on a change of `highlight` to an engaged value, calls `rows->visible(max(0, i − overscan), viewportRows + 2 × overscan, columns)`, `scrollToRow(i)` and `setHighlightedRow(i)`, and keeps the key: a `ViewChange` that moves the key moves the mark, one that removes it clears it. A reply with no row (the key is filtered out or gone) sets `highlight` to nothing, which clears the mark and scrolls nothing; a `null` key does the same. It never changes the selection or the keyboard focus. +- Range selection on a `TableSource`: the backend reports two view rows through `setOnSelectRange`, which the mount wires to `Table::onSelectRange`; the lowering's handler calls `keysOf(min, count)` and, when it completes, sets the selection as the gesture's `SelectionChange` says and runs `onSelectionChange`; more than `maxRangeRows` rows is refused with the message `"A range selects at most 10,000 rows"` (number grouped by the locale) and selects nothing. `WindowRows::keysOf` fetches pages naming no columns (`columns: []`) for what it does not hold. +- A hidden column has no header, width or cells; hiding returns its realized cells to their pool; moving a column inside the window creates nothing (D8). + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_mount.cpp`. `RecordingBackend` gains the drivers `scrollTableColumns(id, scrollX, viewport)`, `focusMove(id, FocusMove)`, `selectTableRange(id, anchor, focus)`, `measureColumn(id, column, width)` (calls the `setOnColumnMeasured` handler), and records `setColumnWindow` (`windowColumns(id)`: the column indices last given; `totalWidth(id)`), `setCounts` (`lastCounts(id)`), `setFocusCell` (`focusCell(id)`: the last view row and column), `setHorizontalOffset` (`horizontalOffset(id)`: the last one, `nullopt` when never called), `scrollToRow` and `setHighlightedRow` (the props `scrolledToRow` and `highlightedRow`, `none` when cleared). + +`test_ui_mount.cpp` holds `FakeRows` (`ui_table_support.hpp` pulls in the interpreter, which the mount tests do not need), a `TableRows` for mount tests: `FakeRows(rows, columns, owner, kind = Exact)` has every row present with the record `{id: i, c0: "rc0", …}`, key `i`; `holdFrom(index)` makes `row()` answer nothing at and after that view index until `arrive()`, which also fires a `Reset`; `setTotal(rows, kind)`; it counts `visibleCalls` and keeps `lastVisible` (first, count, columns). `WindowFixture` (in `test_ui_mount.cpp`) mounts one `Table` over a `FakeRows` on a `RecordingBackend`: `WindowFixture f{rows, columns, {.pinned = p, .custom = {indices}}}` gives every column a fixed width of 100 and the default text cell, except the `custom` ones, which have their own `cell`; the viewport is 30 rows by 2,000 (twenty columns); `f.table` is the widget id, `f.arrangement` the `Signal` the table's `arrangement` reads, `f.focus` the signal its `focus` reads; `f.scrollRows(first)` reports rows `[first, first + 30)` and settles; `f.scrollColumns(x)` reports `(x, 2000)` and settles; `f.flingRows(n)` scrolls down over `n` rows one viewport (30 rows) at a time, running the owner one turn at a time after each step and keeping `f.maxRebindsPerTurn` (the largest growth of `cellsRebound + cellsCreated` across one turn); `f.stats()` is `Mounted::stats()`; `f.cellsAlive()` and `f.headerCellsAlive()` count the backend's live cell and header-cell widgets of the table; `f.realizedRows()` its live row widgets; `f.cellOf(key, column)` the live cell widget of that row and column, or nothing; `f.extents()` the mount's `ColumnExtents` (a test accessor on `Mounted`). + +```cpp +// Mutation: `windowingOf` leaving `cellThreshold` out (the first line's `.columns` and `.rows` are false). +TEST_CASE("windowing: the three thresholds", "[ui][mount]") { + Virtualization const v{}; + CHECK(windowingOf(v, 1999, 300, false).rows); CHECK(windowingOf(v, 1999, 300, false).columns); + CHECK_FALSE(windowingOf(v, 1999, 10, false).rows); CHECK_FALSE(windowingOf(v, 1999, 10, false).columns); + CHECK(windowingOf(v, 2000, 10, false).rows); CHECK_FALSE(windowingOf(v, 2000, 10, false).columns); + CHECK(windowingOf(v, 100, 41, false).columns); CHECK_FALSE(windowingOf(v, 100, 41, false).rows); + CHECK(windowingOf(v, 100, 40, false).columns == false); + CHECK(windowingOf(v, 10, 10, true).rows); CHECK_FALSE(windowingOf(v, 10, 10, true).columns); +} +// Mutation: the column window never on (`windowColumns` is all 300). Ignoring `cellThreshold` alone cannot fail +// this case: 300 visible columns are over `columnThreshold` already. Gate F2. +TEST_CASE("table window: 1,999 × 300 realizes only the windows", "[ui][mount]") { + WindowFixture f{1'999, 300, {.pinned = 2}}; + f.scrollRows(500); f.scrollColumns(10'000); // columns 100 to 119 in view + CHECK(f.realizedRows() == 50); // 30 and overscan 10 each side + CHECK(f.backend.windowColumns(f.table).size() == 2 + 20 + 2 * 4); + CHECK(f.cellsAlive() == f.realizedRows() * f.backend.windowColumns(f.table).size()); + CHECK(f.headerCellsAlive() == f.backend.windowColumns(f.table).size()); + CHECK(f.backend.totalWidth(f.table) == 300 * 100); + CHECK(f.rows->lastVisible.columns.size() == 30); // the window's columns go to `visible` +} +// Mutations: a leaving row's slot not reused (cellsCreated grows on the second fling); no frame budget +// (maxRebindsPerTurn is 720: thirty rows entering, twenty-four cells each). Gate F8. +TEST_CASE("table window: a fling creates no cell once the pools are warm", "[ui][mount]") { + WindowFixture f{100'000, 300, {.pinned = 2}}; + f.flingRows(2'000); auto const created = f.stats().cellsCreated; + f.flingRows(2'000); + CHECK(f.stats().cellsCreated == created); + CHECK(f.maxRebindsPerTurn <= 240); + CHECK(f.stats().placeholders > 0); // the budget left cells blank for a turn +} +// Mutation: rebinding a pooled cell by calling cellView again (cellViewCalls grows on the second fling). +TEST_CASE("table window: a pooled cell is rebound by its row signal", "[ui][mount]") { + WindowFixture f{100'000, 300, {.pinned = 2, .custom = {5}}}; + f.flingRows(2'000); auto const views = f.cellViewCalls; auto const rebound = f.stats().cellsRebound; + f.flingRows(2'000); + CHECK(f.cellViewCalls == views); CHECK(f.stats().cellsRebound > rebound); + f.scrollRows(40'000); f.settle(); + CHECK(f.backend.prop(*f.cellOf(Key{std::int64_t{40'000}}, 5), "text") == "r40000c5"); // rebound to its new row +} +// Mutation: no anchoring (`horizontalOffset` is never set). +TEST_CASE("table window: a column growing left of the view keeps the columns in view where they are", "[ui][mount]") { + WindowFixture f{1'999, 300, {.pinned = 0}}; + f.scrollColumns(10'000); // column 100 is the first in view + f.backend.measureColumn(f.table, 98, 160); f.settle(); // an overscan column grows by 60 + CHECK(f.backend.horizontalOffset(f.table) == 10'060); + CHECK(f.extents().offsetOf(100) == 10'060); + f.backend.measureColumn(f.table, 98, 120); f.settle(); // narrower: a width only grows + CHECK(f.extents().widthOf(98) == 160); CHECK(f.backend.horizontalOffset(f.table) == 10'060); + f.backend.measureColumn(f.table, 110, 180); f.settle(); // inside the view: no anchoring + CHECK(f.backend.horizontalOffset(f.table) == 10'060); +} +// Mutations: pinned columns dropped from the window when scrolled away; no display unpinning (`pinnedShown` stays +// 12). The mount cannot change the fixture's signal, so "unpinning by changing `pinned`" cannot fail the case. +TEST_CASE("table window: pinned columns stay realized, and a narrow table unpins for display only", "[ui][mount]") { + WindowFixture f{1'999, 300, {.pinned = 2}}; + f.scrollColumns(20'000); + std::vector const window = f.backend.windowColumns(f.table); + CHECK(window.at(0) == 0); CHECK(window.at(1) == 1); // still the first two + CHECK(f.cellOf(Key{std::int64_t{0}}, 1).has_value()); + TableArrangement wide = f.arrangement.peek(); wide.pinned = 12; // 1,200 of a 2,000 viewport: over half + f.arrangement.set(wide); f.settle(); + CHECK(f.backend.pinnedShown(f.table) == 10); // the last two scroll with the rest + CHECK(f.arrangement.peek().pinned == 12); // display only +} +// Mutation: a pass that reads every column's width (columnReads grows by 300 a pass). Gate F9. +TEST_CASE("table window: a pass reads no width outside the column window", "[ui][mount]") { + WindowFixture f{1'999, 300, {.pinned = 2}}; + f.scrollColumns(10'000); + std::size_t const before = f.extents().columnReads(); + for (int x = 10'000; x < 12'000; x += 100) { f.scrollColumns(x); } // twenty passes, one column each + std::size_t const window = 2 + 20 + 2 * 4; + CHECK(f.extents().columnReads() - before <= 20 * window); // the window's columns, per pass +} +// Mutations: rebuild rows on a layout change (cellsCreated grows); a hide that pools nothing (the destroyed cell +// makes the next pass throw). Gate D8. +TEST_CASE("table window: hiding and moving a column create no cell widgets", "[ui][mount]") { + WindowFixture f{1'999, 300, {.pinned = 2}}; + auto const before = f.stats().cellsCreated; std::size_t const alive = f.cellsAlive(); + TableArrangement hidden = f.arrangement.peek(); + hidden.visible = allColumnsBut(300, 5); // column 5 was in the window + f.arrangement.set(hidden); f.settle(); + CHECK(f.stats().cellsCreated == before); + CHECK(f.cellsAlive() == alive); // column 26 entered with the pooled cells + CHECK_FALSE(f.cellOf(Key{std::int64_t{0}}, 5).has_value()); + CHECK(f.headerCellsAlive() == f.backend.windowColumns(f.table).size()); + TableArrangement moved = hidden; std::swap(moved.visible.at(3), moved.visible.at(4)); + f.arrangement.set(moved); f.settle(); + CHECK(f.stats().cellsCreated == before); + CHECK(f.backend.prop(*f.cellOf(Key{std::int64_t{0}}, 3), "text") == "r0c3"); // every cell still its own + CHECK(f.rows->lastVisible.first == 0); // rows and their order untouched +} +// Mutation: the focused row not kept realized (the focused cell is gone after the scroll). Gate F10. +TEST_CASE("table focus: the focused cell survives a scroll of 10,000 rows and 200 columns", "[ui][mount]") { + WindowFixture f{100'000, 300, {.pinned = 2}}; + f.focus.set(CellRef{.key = Key{std::int64_t{7}}, .column = "c5"}); f.settle(); + f.scrollRows(10'000); f.scrollColumns(20'000); + REQUIRE(f.cellOf(Key{std::int64_t{7}}, 5).has_value()); // its row and its column stay realized + CHECK(f.backend.focusCell(f.table) == std::pair{std::size_t{7}, std::size_t{5}}); + CHECK(f.realizedRows() == 51); // one row beyond the window at most + CHECK(f.backend.lastCounts(f.table) == std::pair{std::optional{100'000}, std::size_t{300}}); +} +// Mutation: `Last` clamped to the rows held (focus stays on row 199). +TEST_CASE("table focus: Ctrl+End over rows not fetched lands on the last row when it arrives", "[ui][mount]") { + WindowFixture f{100'000, 300, {.pinned = 0}}; + std::vector> reported; f.onFocusCell = [&](auto cell) { reported.push_back(cell); }; + f.focus.set(CellRef{.key = Key{std::int64_t{0}}, .column = "c0"}); f.settle(); + f.rows->holdFrom(200); + f.backend.focusMove(f.table, FocusMove::Last); f.settle(); + CHECK(f.backend.focusCell(f.table).first == 99'999); // the placeholder holds focus + CHECK(f.rows->lastVisible.first + f.rows->lastVisible.count >= 100'000); // and is asked for + f.rows->arrive(); f.settle(); + REQUIRE_FALSE(reported.empty()); + CHECK(reported.back() == CellRef{.key = Key{std::int64_t{99'999}}, .column = "c0"}); +} +// Mutation: the realized row count reported (50), or a lower bound reported as exact. +TEST_CASE("table focus: the reported row count is the total, or unknown for a lower bound", "[ui][mount]") { + WindowFixture f{9'093, 300, {.pinned = 0}}; + CHECK(f.backend.lastCounts(f.table) == std::pair{std::optional{9'093}, std::size_t{300}}); + f.rows->setTotal(100'000, table::TotalKind::AtLeast); f.settle(); + CHECK(f.backend.lastCounts(f.table) == std::pair{std::optional{}, std::size_t{300}}); + TableArrangement fewer = f.arrangement.peek(); fewer.visible = allColumnsBut(300, 5); + f.arrangement.set(fewer); f.settle(); + CHECK(f.backend.lastCounts(f.table).second == 299); // the visible columns + f.rows->holdFrom(200); f.focus.set(CellRef{.key = Key{std::int64_t{0}}, .column = "c0"}); f.settle(); + f.backend.focusMove(f.table, FocusMove::Last); f.settle(); + CHECK(f.backend.focusCell(f.table).first == 199); // AtLeast: the last row known +} +``` +`allColumnsBut(n, i)` is the indices `0 … n − 1` without `i`; `RecordingBackend::pinnedShown(id)` is how many leading columns of the last `setColumnWindow` the mount marked pinned (the call's first `pinned` entries; the driver reads the count the mount passes in a recorded prop `pinnedShown`). + +In `tests/test_ui_table_model.cpp`, over `TableHarness`. `selectTable()` is `kModelTable` with `"selectionMode":"multiple"` (a function: `withTableKey` uses Catch macros); `kHighlight` is `kModelTable` with `"state":{"hk":{"init":{"lit":null}}}`, `"highlightKey":{"ref":"hk"}` on the table and three buttons (test ids `to5012`, `to77`, `toNone`) whose `onClick` sets `hk` to `5012`, to `77`, and to `null`; `click(h, testId)` clicks one through the recording backend and settles; `replyKeyPages(h)` answers every unanswered `Table.samples` call with a page of keys alone at the offset and limit its query names (`pageJson(offset, limit, total, {})`), settling after each; `replyKeyed(h, {{key, viewRow}…})` answers the oldest open call whose query names `keys` with `keyedJson` (the page fetch the highlight causes is older and open); `stopped(h, index)` is whether a call was stopped. + +```cpp +// Mutation: `keysOf` fetching the visible columns (a call's body lacks `"columns":[]`). +TEST_CASE("model table: a range over rows not held resolves through pages that name no columns", "[ui][table]") { + TableHarness h; auto screen = mountShown(h, selectTable(), 100'000); // rows 0 to 199 held + std::size_t const sent = h.dispatcher.calls.size(); + h.backend.selectTableRange(tableOf(h), 500, 1'499); h.settle(); + REQUIRE(h.dispatcher.calls.size() > sent); + for (std::size_t call = sent; call < h.dispatcher.calls.size(); ++call) { + CHECK(h.dispatcher.calls.at(call).action == "Table.samples"); + CHECK(h.dispatcher.calls.at(call).body.contains(R"("columns":[])")); + } + replyKeyPages(h); + CHECK(elementValue(h, "list", "selectedCount") == "1000"); + CHECK(statusOf(h).counts == "1,000 of 100,000 selected"); +} +// Mutation: no bound (keysOf is called and the calls go out). +TEST_CASE("model table: a range over maxRangeRows is refused and selects nothing", "[ui][table]") { + TableHarness h; auto screen = mountShown(h, selectTable(), 100'000); + std::size_t const sent = h.dispatcher.calls.size(); + h.backend.selectTableRange(tableOf(h), 0, 10'000); h.settle(); // 10,001 rows + CHECK(h.dispatcher.calls.size() == sent); + CHECK(statusOf(h).message == "A range selects at most 10,000 rows"); + CHECK(elementValue(h, "list", "selectedCount") == "0"); + h.backend.selectTableRange(tableOf(h), 0, 9'999); h.settle(); // 10,000 rows: allowed + CHECK(h.dispatcher.calls.size() > sent); +} +// Mutations: the view index taken from the reply's position (0) instead of `indices`; the highlight written into +// the selection; no cancel of the earlier key's fetch. +TEST_CASE("model table: highlightKey scrolls to the row and marks it", "[ui][table]") { + TableHarness h; auto screen = mountShown(h, kHighlight, 9'093); + int const table = tableOf(h); + click(h, "to5012"); + REQUIRE(lastQuery(h).keys.has_value()); + CHECK(*lastQuery(h).keys == std::vector{std::int64_t{5012}}); + CHECK(h.dispatcher.calls.back().body.contains(R"("columns":[])")); + replyKeyed(h, {{5012, 5011}}); + CHECK(h.backend.prop(table, "scrolledToRow") == "5011"); + CHECK(h.backend.prop(table, "highlightedRow") == "5011"); + h.advance(80ms); + CHECK(lastQuery(h).page.offset == 5'000); // the page that holds view row 5,011 + CHECK(elementValue(h, "list", "selectedCount") == "0"); // never the selection + click(h, "to77"); + replyKeyed(h, {}); // filtered out or gone: no row + CHECK(h.backend.prop(table, "highlightedRow") == "none"); + CHECK(h.backend.prop(table, "scrolledToRow") == "5011"); // nothing scrolled + std::size_t const first = h.dispatcher.calls.size(); + click(h, "to5012"); click(h, "to77"); // two keys before a reply + CHECK(stopped(h, first)); // the first key's fetch is cancelled + click(h, "toNone"); CHECK(h.backend.prop(table, "highlightedRow") == "none"); +} +``` + +- [ ] **Step 2: Run to verify they fail** — `cmake --build --preset cl-debug --target morph_tests` → FAIL: `windowingOf`, `ColumnExtents` undeclared. +- [ ] **Step 3: Implement** the interfaces and decisions above. +- [ ] **Step 4: Run to verify they pass** — `ctest --test-dir build/cl-debug -R "windowing|table window|table focus|model table" --output-on-failure`; `morph_tests` green. +- [ ] **Step 5: Mutations**, as named. +- [ ] **Step 6: Commit** `feat(ui): the column window in the mount`. + +#### 10b — The column window in Qt Quick and the terminal + +**Files:** +- Modify: `src/qt_quick/table.cpp`, `src/qt_quick/qml/MorphTable.qml` (the column window, pinned columns, the header for windowed columns only, horizontal anchoring, focus cell, counts for assistive technology, the status line from `setStatus` with its "Retry" button), `src/tui/table_widget.cpp`, `src/tui/table_widget.hpp` (the column range, the status line) +- Test: `tests/qt_quick/test_qt_quick_table.cpp`, `tests/tui/test_tui_table.cpp` +- Docs: `docs/spec/qt_quick/backend.md` ("Containers and lists": the column window, cell pools, pinned columns, the status line; "Tests": the new cases). + +**Interfaces:** consumes 10a's `TableWidget` members; produces `TableWidget::setRowIndex(row, viewRow)`, which the mount calls for a realized row once it is realized and whenever its index changes: the focused row stays realized outside `setRealizedWindow`'s range, so a backend places each row by its index, not by its place among the children. Every backend places a source table's cells by `setCellColumn`, never by their order in the row. + +Decisions: +- MorphTable exposes, for tests, the QML properties `realizedColumnFirst`, `realizedColumnCount`, `pinnedShown`, `headerCellCount`, `statusText`, `rowMeasures` (cell height measurements made), the invokables `rowHeight(viewRow)` and `cellLoadAt(viewRow, column)` (`0` Loaded, `1` Unloaded, `2` Failed, as drawn), and keeps `rowScans`, `realizedFirst`, `realizedCount`, `totalRows`. +- The status line is one `Text` row under the rows, an accessible polite live region (`Accessible.role: Accessible.StaticText`, announced on change), with a "Retry" button while `TableStatus::retry`; it takes no space while `shown` is false. +- Both backends mark a table as over a source when the mount gives it a horizontal-range handler, never by `setRealizedWindow`, which a long `rows` table is told too. Both answer `tableMeasure` (pixels from the theme, with `table.cellPaddingX` a side as `TableMeasure::padding`; cells, with the gap as padding), so a windowed fixed column is as wide as an unwindowed one. Over a source, Shift with an arrow, a Shift-click and Ctrl+A go to `setOnSelectRange` as view rows (Ctrl+A over every row of the view, as `Extend`, which the mount refuses past `maxRangeRows` until the whole-view selection of "Acting on rows" exists); no range runs over the realized rows alone. A click does not move the mount's focused cell in either backend: no seam carries a pointer's cell. Qt Quick's counts reach `accessibleRowCount`/`accessibleColumnCount` only, and a row does not report its view row to assistive technology: `Accessible` has neither. A source table's natural height is all its rows in both backends, so it needs a bounded height to window its rows. +- The terminal table draws the cells of the columns in the window only, and the status line as its last line. Over a source it scrolls over every row of the view, one line each, draws each realized row on the line of its view index, and reports the columns and then the rows in view before the next frame's layout (and at once for the wheel); the arrows, Home, End, PageUp, PageDown, Ctrl+Home and Ctrl+End go to the mount, and Left and Right, keeping the focused cell in view, are how the user scrolls sideways. +- Cell load state (from 9d's `setCellLoad`). Qt Quick: an `Unloaded` cell draws a rounded bar of a fixed 3 em width in the column's alignment over the cell's content, which stays bound but invisible; a `Failed` cell draws an error mark of the same width whose tooltip and accessible name say "Could not be loaded". The terminal draws `···` for `Unloaded` and `!` for `Failed`, in the column's alignment. Neither is measured into the column's width, so a level arriving widens a column at most once (F7). +- Row height (table.md "Cells"), in `MorphTable`, which is what measures cells: a row's height is the tallest of its realized cells and only grows while the row is realized; a row that leaves the row window forgets its height; an unrealized row counts as the mean of the measured heights. When a row above the first visible row grows, the vertical offset grows by the same amount in the same frame; the mount holds no row heights, so this anchoring is `MorphTable`'s, here. A table whose columns are all `wrap: false` has one row height and measures no cell (`rowMeasures` stays 0). The terminal's rows are one line each, so none grows and the terminal needs no anchoring. + +- [ ] **Step 1: Write the failing tests** + +`QuickWindowFixture` (in `test_qt_quick_table.cpp`) is 10a's `WindowFixture` on the Qt Quick backend: the same constructor, `rows`, `arrangement`, `focus`, `scrollRows`, `scrollColumns`, `flingRows`, `stats()` and `settle()` (which also renders a frame), in an offscreen 1,280 × 800 window with a column width of 64, so twenty columns are in view; `item()` is the `MorphTable` item, `prop(name)` one of its QML properties, `cellItems()` the visible cell items under it, `call(name, args…)` one of its invokables. `WideScreen` is 9d's. `TuiWindowFixture` (in `test_tui_table.cpp`) is the same over the terminal backend through `tests/tui/tui_harness.hpp`, in a terminal of 120 × 32 with a column width of 12 (ten columns and thirty rows in view); `cellWidgetsAlive()` counts the table's live cell widgets and `screenLine(n)` is line `n` of the drawn screen. + +```cpp +// Mutation: MorphTable instantiating a cell per column of a realized row (cellItems is 50 × 300). Gate F2. +TEST_CASE("qt_quick table window: cells and header cells alive are the windows'", "[qt_quick]") { + QuickWindowFixture f{100'000, 300, {.pinned = 2}}; + f.scrollRows(500); f.scrollColumns(6'400); // columns 100 to 119 in view + int const window = 2 + 20 + 2 * 4; + CHECK(f.prop("realizedColumnCount").toInt() == window); + CHECK(f.prop("pinnedShown").toInt() == 2); + CHECK(f.cellItems() == f.prop("realizedCount").toInt() * window); + CHECK(f.prop("headerCellCount").toInt() == window); +} +// Mutation: a pool keyed by column for default cells (a column scrolling in creates 50 cells). Gate F8. +TEST_CASE("qt_quick table window: flings create no cell once the pools are warm", "[qt_quick]") { + QuickWindowFixture f{100'000, 300, {.pinned = 2}}; + f.flingRows(2'000); for (int x = 0; x < 12'800; x += 640) { f.scrollColumns(x); } // warm both ways + auto const created = f.stats().cellsCreated; + f.flingRows(2'000); for (int x = 12'800; x < 19'200; x += 640) { f.scrollColumns(x); } + CHECK(f.stats().cellsCreated == created); + CHECK(f.maxRebindsPerTurn <= 240); +} +// Mutation: MorphTable keeping focus on the delegate item, which a recycled row loses. Gate F10. +TEST_CASE("qt_quick table window: focus and counts after scrolling far away", "[qt_quick]") { + QuickWindowFixture f{100'000, 300, {.pinned = 2}}; + f.focus.set(CellRef{.key = Key{std::int64_t{7}}, .column = "c5"}); f.settle(); + f.scrollRows(10'000); f.scrollColumns(200 * 64); + CHECK(f.call("focusedRow").toInt() == 7); CHECK(f.call("focusedColumn").toInt() == 5); + CHECK(f.call("cellRealized", 7, 5).toBool()); + CHECK(f.prop("accessibleRowCount").toInt() == 100'000); + CHECK(f.prop("accessibleColumnCount").toInt() == 300); +} +// Mutation: MorphTable rebuilding its row delegates when the column window changes. Gate D8, Qt Quick half. +TEST_CASE("qt_quick table window: hiding and moving a column create no cell items", "[qt_quick]") { + QuickWindowFixture f{100'000, 300, {.pinned = 2}}; + auto const created = f.stats().cellsCreated; int const items = f.cellItems(); + TableArrangement hidden = f.arrangement.peek(); hidden.visible = allColumnsBut(300, 5); + f.arrangement.set(hidden); f.settle(); + CHECK(f.stats().cellsCreated == created); CHECK(f.cellItems() == items); + CHECK_FALSE(f.call("cellRealized", 0, 5).toBool()); + TableArrangement moved = hidden; std::swap(moved.visible.at(3), moved.visible.at(4)); + f.arrangement.set(moved); f.settle(); + CHECK(f.stats().cellsCreated == created); CHECK(f.cellItems() == items); +} +// Mutation: MorphTable ignoring setStatus (statusText is empty). +TEST_CASE("qt_quick table: the status line shows counts and Retry", "[qt_quick]") { + QuickWindowFixture f{100'000, 30}; // its status: "100,000 rows" + CHECK(f.prop("statusText").toString() == QStringLiteral("100,000 rows")); + CHECK_FALSE(f.prop("retryShown").toBool()); + f.status.set(ui::TableStatus{.counts = "100,000 rows", .state = "Recipe data could not be loaded.", + .retry = true, .shown = true}); f.settle(); + CHECK(f.prop("statusText").toString() == QStringLiteral("100,000 rows Recipe data could not be loaded.")); + REQUIRE(f.prop("retryShown").toBool()); + f.scene.click(*f.item()->findChild(QStringLiteral("retry"))); + CHECK(f.retries == 1); +} +// Mutation: MorphTable ignoring setCellLoad (an unloaded cell draws its empty content: cellLoadAt is 0). +TEST_CASE("qt_quick table: an unloaded cell is a placeholder and a failed one an error mark", "[qt_quick]") { + QuickWindowFixture f{100, 4, {.levels = {{.column = 1, .level = "recipe"}}}}; + int const widthBefore = f.call("columnWidth", 1).toInt(); + f.rows->unload(0, "recipe"); f.rows->fail(1, "recipe"); f.settle(); + CHECK(f.call("cellLoadAt", 0, 1).toInt() == 1); + CHECK(f.call("cellLoadAt", 1, 1).toInt() == 2); + CHECK(f.call("cellLoadAt", 2, 1).toInt() == 0); + CHECK(f.call("columnWidth", 1).toInt() == widthBefore); // a placeholder widens nothing +} +// Mutations: a row's height recomputed from its realized cells each pass (it shrinks when the tall cell leaves); +// measuring a table whose columns are all wrap:false (rowMeasures grows). +TEST_CASE("qt_quick table: a row's height only grows while it is realized", "[qt_quick]") { + QuickWindowFixture f{2'000, 300, {.pinned = 0, .wrapped = {{.row = 3, .column = 60, .lines = 2}}}}; + int const low = f.call("rowHeight", 3).toInt(); + f.scrollColumns(60 * 64); int const tall = f.call("rowHeight", 3).toInt(); + CHECK(tall > low); + f.scrollColumns(0); CHECK(f.call("rowHeight", 3).toInt() == tall); // scrolled out: not shorter + f.scrollRows(1'000); f.scrollRows(0); + CHECK(f.call("rowHeight", 3).toInt() == low); // it left the row window: forgotten + QuickWindowFixture flat{2'000, 300, {.pinned = 0, .wrap = false}}; + flat.flingRows(200); CHECK(flat.prop("rowMeasures").toInt() == 0); +} +// tests/tui/test_tui_table.cpp. +// Mutation: the terminal table ignoring the column range (300 cells a row). Gate U7. +TEST_CASE("tui table: cell widgets alive are rows in view times columns in view", "[tui]") { + TuiWindowFixture f{100'000, 300, {.pinned = 0}}; + f.scrollRows(5'000); f.scrollColumns(100 * 12); + CHECK(f.cellWidgetsAlive() == 30 * 10); // the terminal keeps no overscan + CHECK(f.screenLine(31).starts_with("100,000 rows")); // the status line, last +} +// Mutation: the terminal table ignoring setCellLoad (the lines show neither mark). +TEST_CASE("tui table: an unloaded cell draws its placeholder and a failed one its mark", "[tui]") { + TuiWindowFixture f{100, 4, {.pinned = 0, .levels = {{.column = 1, .level = "recipe"}}}}; + f.rows->unload(0, "recipe"); f.rows->fail(1, "recipe"); f.settle(); + CHECK(f.screenLine(1).contains("···")); CHECK(f.screenLine(2).contains("!")); + CHECK_FALSE(f.screenLine(3).contains("···")); +} +``` +`MorphTable` therefore also exposes, for tests, the properties `retryShown`, `accessibleRowCount`, `accessibleColumnCount` and the invokables `focusedRow()`, `focusedColumn()`, `cellRealized(viewRow, column)`, `columnWidth(column)`; `FakeRows` gains `unload(row, level)` and `fail(row, level)` (what `unloadedLevels` answers, with a `Changed` for the row); the status line and load state cases run on `QuickWindowFixture` (its `status` signal and `onRetry` count, and `FakeRows::unload`/`fail`) rather than on 9d's `WideScreen`, which 9d did not write: a fixture over a scripted interpreter cannot be written blind, and these cases test the backend's drawing, not the lowering; the fixtures' options gain `wrapped`, `wrap` and `levels`. The terminal's window has no overscan: its `Virtualization` is built with `overscan = 0` and `columnOverscan = 0` by `TuiWindowFixture`, which is what makes U7's count exact. + +Benchmarks, `[.benchmark][qt_quick]`, in `tests/qt_quick/bench_qt_quick_table.cpp` (Part A's, where the step 0 baselines of the same figures are): F3 (vertical at 20 rows/s, a fling at 2,000 rows/s, a thumb drag), F4 (horizontal at 10 and 100 columns/s), F5 (memory per realized row), each first asserting the table is windowed both ways, timed per step through `QQuickRenderControl` (`polishItems`, `sync`, `render`) under `offscreen` and the software scene graph. + +- [ ] **Step 2: Run to verify they fail** — `cmake --build --preset cl-qt-debug --target morph_qt_quick_tests morph_tui_tests` then `ctest --test-dir build/cl-qt-debug -L qt_quick -R "table window" --output-on-failure` → FAIL on `headerCellCount` being invalid. +- [ ] **Step 3: Implement** the backends' halves. +- [ ] **Step 4: Run to verify they pass** — `ctest --test-dir build/cl-qt-debug -L qt_quick --output-on-failure` and `ctest --test-dir build/cl-qt-debug -R "tui table" --output-on-failure`: all green, the existing virtualized-table cases included. +- [ ] **Step 5: Mutations**, as named. Record F1 to F5 from `build/cl-qt-release` (`cmake --preset cl-qt-release -DMORPH_BUILD_QT_QUICK=ON`, then `morph_qt_quick_tests "[.benchmark]"` with `QT_QPA_PLATFORM=offscreen`) into table.md's "The frontend at 300 columns" table, against step 0's baseline. +- [ ] **Step 6: Neighbouring spec** `docs/spec/qt_quick/backend.md` as listed; docs build green. +- [ ] **Step 7: Commit** `feat(qt_quick): the column window, cell pools and the status line`. + +#### 10c — Exit criterion U8 + +U8 is "U1 and U2 at 20,000 rows, and U6's scrolls, in the WebAssembly build in a browser … the frame budgets of F3 and F4 hold". What can be done without a person at a browser: + +- [ ] **Build**: the Qt WebAssembly build of `morph_qt_quick` already builds in `.github/workflows/wasm-demo.yml` (Qt `wasm_singlethread`, emsdk 4.0.7, `qt-cmake … -DMORPH_BUILD_QT=ON -DMORPH_BUILD_QT_QUICK=ON`). Confirm this branch still builds there (`cmake --build build-wasm --target morph_examples_client`) and that the count gates of the single-threaded path still run under Node in the WebAssembly job Task 0 adds. +- [ ] **Measure with Task 0's B5 harness.** Part A adds `tests/qt_quick/wasm/` (built only when `EMSCRIPTEN AND MORPH_BUILD_QT_QUICK`), run in a headless browser with `emrun --browser chrome --browser_args=--headless=new`, printing figures to the console. Add `tests/qt_quick/wasm/u8_scrolls.cpp` beside `wide_rows_baseline.cpp`: it mounts a 20,000-row `rows` table (U1: a header click on a text column; U2: one row changed) and a model-backed table over an in-process `bench::WideTableModel` at 100,000 × 300, scrolls both as F3 and F4 do, and prints U1, U2 and each scroll's p50/p99 frame time. Build it in the WebAssembly tree configured as `wasm-demo.yml` does (`qt-cmake … -DMORPH_BUILD_QT=ON -DMORPH_BUILD_QT_QUICK=ON -DMORPH_BUILD_TESTS=ON`), run it with the same `emrun` line, and record the figures beside the native ones. The exit criterion holds when every scroll's p50 ≤ 8 ms and p99 ≤ 16.6 ms. +- [ ] **What stays open.** The run is local: no CI job drives a browser, and on a machine without Chrome it cannot run. If it cannot be run, Task 10 lands with its native gates and the executor writes "U8 not measured" in the commit body and tells the user. No other command is invented for it. + +--- + +### Task 11: Tables over `rows` on the engine (table.md step 6) + +Three commits: 11a and 11b are step 6; 11c is the typed-list-action half of step 4's model-backed table, placed here because it reads its column kinds with 11a's inference. + +#### 11a — `ValueRowsSource` + +**Files:** +- Modify: `include/morph/ui/table_rows.hpp` +- Test: `tests/test_ui_table_model.cpp`, `tests/bench_interpreter.cpp` (U1 to U4) + +**Interfaces:** + +```cpp +/// The expression language's text order: the default collator's fold, then the text itself. +class ValueRowsCollator final : public table::TextCollator { +public: + [[nodiscard]] std::string sortKey(std::string_view text) const override; // fold(text) + '\0' + text + [[nodiscard]] std::string fold(std::string_view text) const override; // CodePointCollator's + [[nodiscard]] std::size_t folds() const noexcept; // U3 counter +}; +struct ValueColumn { + std::string id; + std::optional kind; // the column part's literal `kind`; empty: inferred + std::function sortBy; // the column's `sortBy` in the row's scope, tracked; empty: the field +}; +/// The hidden leading sort key of a grouped rows table: an Integer column of each row's run index. +inline constexpr std::string_view kGroupRunColumn = "\x1F" "group"; // U+001F, then "group": no document column can have this id +class ValueRowsSource final : public table::DataSource { +public: + ValueRowsSource(reactive::Runtime& runtime, std::vector columns, + std::function keyOf, + std::shared_ptr units = {}); // Quantity cells' units; null: none + void assign(ValueList rows); // a new list: match by key, then by cell + /// The `group` part's `by`, read per row; empty: no groups. Adds the hidden column `kGroupRunColumn`. + void setGroup(std::function by); + /// The run a source row belongs to: its index among the runs of adjacent rows with equal `by`, in source order. + [[nodiscard]] std::size_t runOf(std::size_t sourceRow) const; + /// Each run's heading record `{key, count, first, last, items}`, by run index, as `TableView::runs` holds them. + [[nodiscard]] std::span runRecords() const noexcept; + void use(std::string_view column); // a sort, a filter or a values list began + void unuse(std::string_view column); // its last use ended: its cells go + [[nodiscard]] RecordOf recordOf() const; // for EngineRows + [[nodiscard]] std::size_t cellsHeld() const noexcept; // U4 counter + [[nodiscard]] std::size_t cellsDerived() const noexcept; // U2 counter + /// Cells of @p column, a column in use, that are not of its kind; 0 for a column not in use. + [[nodiscard]] std::size_t invalidCells(std::string_view column) const; +}; +``` + +Decisions: +- A cell of a column in use is a `reactive::Computed` over the row's signal and what `sortBy` reads; when one changes, the source notifies `Updated` for that row alone; a change every row's cell reads derives the column again and notifies `Reset`. +- `assign`: a row whose `Value` shares storage with the held one is kept unread; another object derives the in-use cells and compares them with the held cells, `Updated` only on a difference; new keys `Inserted`, missing keys `Removed`. A later duplicate of a key is dropped and reported through `site::kDuplicateKey`, once per duplicate, as the mount reports it today. +- Kind inference, by `ui::ValueKind` (`value.hpp:132`). A `Value` has no floating-point kind: a fractional number that reaches a document through the query cache is the `Decimal` its shortest text spells, or its text where that does not fit one (cross-part decision 46), so a `rows` column of fractional numbers infers as `Decimal` and no `rows` column is ever inferred `Number`; `Number` comes only from a column part's literal `kind: "number"`, under which a `Decimal` or `Int` cell is converted to the nearest `double`. A column with no non-null cell (an empty list, or all `null`) is `Text` until a cell votes, and the first vote that makes it another kind is a `Reset` of that column like any other change of kind. Each non-null cell votes; the column's kind and each cell: + + | `ValueKind` | Votes for | Cell | + |---|---|---| + | `Null` | nothing | empty (`std::monostate`) | + | `Bool` | `Bool` | `bool` | + | `Int` | `Integer` | `int64`; in a `Decimal` column a `Rational` of 0 places | + | `Decimal` | `Decimal` | its `math::Rational`, places kept | + | `String` | `Text` | the text | + | `Timestamp` | `DateTime` | UTC **seconds**: `floor(ms / 1000)` (toward −∞, so −1 ms is −1 s) | + | `Quantity` | `Measure` | `Measure{value, units->find(unit)}`; a unit the registry lacks, or no registry, is an invalid cell (the "unknown unit" case) | + | `List`, `Record` | nothing of its own | invalid, except a `Record` of exactly `num`, `den`, `unit` (cross-part decision 22), read as a `Quantity` | + + All votes alike → that kind; only `Int` and `Decimal` → `Decimal`; any other mix takes the first non-null cell's kind, `Decimal` when that is an `Int` and a `Decimal` voted too (table.md's "integers with decimals are one `Decimal` column and a text among them is one invalid cell"), and a cell not of it is invalid (sorts last, reported once at the `sort` path). A literal `kind` on the column part wins over inference, and a cell not of it is invalid. A change of the inferred kind is a `Reset` of that column. A `DateTime` cell holds seconds (`data_source.hpp:56`), so two timestamps in one second tie and keep their source order, where the expression language's `sort` orders to the millisecond; table.md ("A document's rows as a source", "Timestamps to the second") states this. A rows table orders as a model's `DateTime` column does, which is what "One order on every surface" compares. +- Groups. `kGroupRunColumn` begins with the control character U+001F, written as the escape `"\x1F" "group"` and never as the raw character: a column id is a document name (`[A-Za-z_][A-Za-z0-9_]*`, `document.cpp:770`), so no column a document declares, `group` included, can collide with it. With `setGroup`, the source holds the column `kGroupRunColumn` (`ColumnKind::Integer`, not in `ColumnInfo`s the lowering lays out): row `r`'s cell is `runOf(r)`, runs counted over the rows in source order, a new run starting where `by` is not the same element as the run's first row's: `ui::detail::sameElement` with the unit table `setGroup` is given, the rule of the interpreter's `group` (`Evaluator::sameRun`) and of `runs`, so `1`, `1.0` and `1.00` are one run, and the run's key is its first row's `by`. The lowering puts `{kGroupRunColumn, Ascending}` before every sort chain it passes to the engine, so groups keep their places and rows sort within them; `assign` recomputes the runs and notifies `Reset` of that column only when a run boundary moved. `runRecords()` are the heading records the interpreter builds today (`TableView::runs`), placed by the lowering after paging (11b). +- The source keeps each row's `Value` beside its cells; `recordOf` returns its key and that value. + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_model.cpp`. Helpers, in the file: `rec({{"id", 1}, {"name", "a"}})` is a record `Value`; `sourceOf(h, columns, units = {})` a `std::shared_ptr` on `h.runtime` whose `keyOf` reads `id`; `col(id)` a `ValueColumn` with that id, `col(id, kind)` one with a literal kind; `RecordingListener listener{*src}` subscribes and keeps every `RowChange` in `changes` (`clear()` empties it); `freshDecodeOf(list)` is the list written to JSON and read back (no storage shared); `withField(list, row, name, value)` a copy with one row's field replaced, the other rows sharing storage; `cellAt(src, row, column)` is `src.snapshot()->cell(row, )`; `kindOf(src, column)` its `ColumnInfo::kind`; `engineOver(h, src, collator = {})` a `table::Engine` with `EngineOptions{.owner = &h.owner, .services.collator = collator}`; `keysInView(engine)` the `int64` keys of its view rows in order; `sampleRows(n)` is `n` rows `{id: i, name: "n", notes: "x", amount: i}`. + +```cpp +// Mutation: a diff by row value (the fresh decode notifies, or `cellsDerived` counts every field). +TEST_CASE("value rows source: a document's rows as a source", "[ui][table]") { + RowsFixture h; auto const src = sourceOf(h, {col("name"), col("notes"), col("amount")}); + RecordingListener listener{*src}; + ValueList const rows = sampleRows(100); + src->use("name"); src->assign(rows); h.settle(); listener.clear(); + std::size_t const derived = src->cellsDerived(); + src->assign(freshDecodeOf(rows)); h.settle(); + CHECK(listener.changes.empty()); // the same cells: nothing notified + CHECK(src->cellsDerived() - derived == 100); // one column in use, not three fields + src->assign(withField(freshDecodeOf(rows), 7, "name", Value{std::string{"zeta"}})); h.settle(); + REQUIRE(listener.changes.size() == 1); + CHECK(listener.changes.front().kind == table::ChangeKind::Updated); + CHECK(listener.changes.front().rows == std::vector{7}); + CHECK(src->cellsHeld() == 100); // "notes" and "amount" hold no cells + src->use("amount"); h.settle(); CHECK(src->cellsHeld() == 200); + src->unuse("amount"); CHECK(src->cellsHeld() == 100); // its last use ended: its cells go +} +// Mutations: `sortBy` read outside a tracked computation (no change is notified); a per-row change notified as Reset. +TEST_CASE("value rows source: a change to what one row's sortBy reads updates that row", "[ui][table]") { + RowsFixture h; + std::vector>> rank; + for (int i = 0; i < 10; ++i) { rank.push_back(std::make_unique>(h.runtime, i)); } + reactive::Signal scale{h.runtime, 1}; + ValueColumn ranked = col("name"); + ranked.sortBy = [&](Value const& row) { return Value{rank.at(*row.field("id")->asInt())->get() * scale.get()}; }; + auto const src = sourceOf(h, {ranked}); RecordingListener listener{*src}; + src->use("name"); src->assign(sampleRows(10)); h.settle(); listener.clear(); + rank.at(3)->set(99); h.settle(); + REQUIRE(listener.changes.size() == 1); + CHECK(listener.changes.front().kind == table::ChangeKind::Updated); + CHECK(listener.changes.front().rows == std::vector{3}); + CHECK(cellAt(*src, 3, "name") == table::Cell{std::int64_t{99}}); + listener.clear(); scale.set(2); h.settle(); // what every row's cell reads + REQUIRE(listener.changes.size() == 1); + CHECK(listener.changes.front().kind == table::ChangeKind::Reset); +} +// Review Focus 5. Mutation: keep the last duplicate (the view holds "c" and not "a"). +TEST_CASE("value rows source: a duplicate key keeps its first row", "[ui][table]") { + RowsFixture h; auto const src = sourceOf(h, {col("name")}); + std::size_t const reports = h.reported(ui::detail::site::kDuplicateKey); + src->use("name"); + src->assign(ValueList{rec({{"id", 1}, {"name", "a"}}), rec({{"id", 2}, {"name", "b"}}), rec({{"id", 1}, {"name", "c"}})}); + h.settle(); + CHECK(src->snapshot()->rowCount() == 2); + CHECK(h.reported(ui::detail::site::kDuplicateKey) - reports == 1); // once per duplicate + auto engine = engineOver(h, src); + REQUIRE(engine->setSort({{.column = "name", .dir = table::SortDirection::Descending}})); h.settle(); + CHECK(keysInView(*engine) == std::vector{2, 1}); // "b", then the first "a"; never "c" + CHECK(cellAt(*src, 0, "name") == table::Cell{std::string{"a"}}); +} +// Mutation: Timestamp cells kept in milliseconds (row 2 reads 1'700'000'000'500 and sorts apart from row 1). +TEST_CASE("value rows source: a timestamp is a DateTime of whole seconds", "[ui][table]") { + RowsFixture h; auto const src = sourceOf(h, {col("at")}); src->use("at"); + src->assign(ValueList{rec({{"id", 1}, {"at", ts(1'700'000'000'000)}}), rec({{"id", 2}, {"at", ts(1'700'000'000'500)}}), + rec({{"id", 3}, {"at", ts(-1)}})}); + h.settle(); + CHECK(kindOf(*src, "at") == table::ColumnKind::DateTime); + CHECK(cellAt(*src, 0, "at") == table::Cell{std::int64_t{1'700'000'000}}); + CHECK(cellAt(*src, 1, "at") == table::Cell{std::int64_t{1'700'000'000}}); // the same second: they tie + CHECK(cellAt(*src, 2, "at") == table::Cell{std::int64_t{-1}}); // floor, not truncation toward 0 + auto engine = engineOver(h, src); + REQUIRE(engine->setSort({{.column = "at", .dir = table::SortDirection::Descending}})); h.settle(); + CHECK(keysInView(*engine) == std::vector{1, 2, 3}); // the tie keeps source order +} +// Mutations: a missing case in the inference (a kind differs); an empty column given no kind (the "e" entry); +// a mixed Int and Decimal column inferred from its first cell (Integer, with one invalid cell). +TEST_CASE("value rows source: every value kind infers its column kind", "[ui][table]") { + using enum table::ColumnKind; + RowsFixture h; + auto const src = sourceOf(h, {col("b"), col("i"), col("d"), col("s"), col("t"), col("q"), col("l"), col("id_d"), + col("e"), col("n", Number)}, testUnits()); // testUnits(): kg and g of mass + for (auto const* id : {"b", "i", "d", "s", "t", "q", "l", "id_d", "e", "n"}) { src->use(id); } + src->assign(ValueList{ + rec({{"id", 1}, {"b", true}, {"i", 4}, {"d", dec("2.50")}, {"s", "x"}, {"t", ts(1'000)}, {"q", qty("3", "kg")}, + {"l", 7}, {"id_d", 4}, {"e", Value{}}, {"n", dec("0.5")}}), + rec({{"id", 2}, {"b", false}, {"i", 5}, {"d", dec("0.125")}, {"s", "y"}, {"t", ts(2'000)}, {"q", qty("3", "zz")}, + {"l", ValueList{}}, {"id_d", dec("0.5")}, {"e", Value{}}, {"n", 2}})}); + h.settle(); + std::map kinds; + for (table::ColumnInfo const& column : src->columns()) { kinds.emplace(column.id, column.kind); } + CHECK(kinds == std::map{{"b", Bool}, {"i", Integer}, {"d", Decimal}, {"s", Text}, + {"t", DateTime}, {"q", Measure}, {"l", Integer}, {"id_d", Decimal}, {"e", Text}, {"n", Number}}); + CHECK(src->invalidCells("q") == 1); // the second row's unit "zz" is unknown + CHECK(src->invalidCells("l") == 1); // the list cell + CHECK(src->invalidCells("id_d") == 0); // an integer is an exact decimal + CHECK(cellAt(*src, 0, "n") == table::Cell{0.5}); CHECK(cellAt(*src, 1, "n") == table::Cell{2.0}); + RecordingListener listener{*src}; + src->assign(ValueList{rec({{"id", 1}, {"e", 9}})}); h.settle(); // the empty column's first vote + CHECK(kindOf(*src, "e") == Integer); + CHECK(listener.changes.back().kind == table::ChangeKind::Reset); +} +// Mutations: every row given run 0, as an index computed after the sort would leave it (groups split: 2, 3, 1); +// the run column named plain "group" (the source has two columns of that id, and the count CHECK reads 2). +TEST_CASE("value rows source: a grouped table sorts within its runs", "[ui][table]") { + RowsFixture h; auto const src = sourceOf(h, {col("name"), col("group")}); // a document column named "group" + src->setGroup([](Value const& row) { return *row.field("site"); }); + src->use("name"); src->use("group"); + src->assign(ValueList{rec({{"id", 1}, {"site", "A"}, {"name", "z"}, {"group", "q"}}), + rec({{"id", 2}, {"site", "A"}, {"name", "a"}, {"group", "r"}}), + rec({{"id", 3}, {"site", "B"}, {"name", "m"}, {"group", "p"}})}); + h.settle(); + CHECK(std::ranges::count(src->columns(), std::string{"group"}, &table::ColumnInfo::id) == 1); + CHECK(std::ranges::count(src->columns(), std::string{kGroupRunColumn}, &table::ColumnInfo::id) == 1); + auto engine = engineOver(h, src); + REQUIRE(engine->setSort({{.column = std::string{kGroupRunColumn}}, {.column = "name"}})); h.settle(); + CHECK(keysInView(*engine) == std::vector{2, 1, 3}); + REQUIRE(engine->setSort({{.column = std::string{kGroupRunColumn}}, {.column = "group"}})); h.settle(); + CHECK(keysInView(*engine) == std::vector{1, 2, 3}); // by the document's "group", in runs + CHECK(src->runRecords().size() == 2); CHECK(src->runOf(2) == 1); +} +// Mutation: fold inside the comparison (about 3.4 million folds). Gate U3. +TEST_CASE("value rows source: a sort of 100,000 rows folds each text once", "[ui][table]") { + RowsFixture h; auto const collator = std::make_shared(); + auto const src = sourceOf(h, {col("name")}); src->use("name"); src->assign(sampleRows(100'000)); h.settle(); + auto engine = engineOver(h, src, collator); + REQUIRE(engine->setSort({{.column = "name"}})); h.settle(); + CHECK(collator->folds() == 100'000); + CHECK(engine->stats().fullSorts == 1); +} +// Mutations: a fresh decode deriving every column (cellsDerived is 300,000); the changed row sorting the list +// (fullSorts grows). Gates U2 and U4, as counts. +TEST_CASE("value rows source: one changed row derives one column and repairs", "[ui][table]") { + RowsFixture h; auto const src = sourceOf(h, {col("name"), col("notes"), col("amount")}); + ValueList const rows = sampleRows(10'000); + src->use("name"); src->assign(rows); h.settle(); + auto engine = engineOver(h, src); REQUIRE(engine->setSort({{.column = "name"}})); h.settle(); + CHECK(src->cellsHeld() == 10'000); // U4: one column's cells + table::EngineStats const before = engine->stats(); std::size_t const derived = src->cellsDerived(); + src->assign(withField(freshDecodeOf(rows), 42, "name", Value{std::string{"zzz"}})); h.settle(); + CHECK(src->cellsDerived() - derived == 10'000); // U2: the column in use only + CHECK(engine->stats().repairs - before.repairs == 1); + CHECK(engine->stats().fullSorts == before.fullSorts); + CHECK(keysInView(*engine).back() == 42); +} +``` +`ts(ms)`, `dec(text)` and `qty(amount, unit)` build a `Timestamp`, a `Decimal` and a `Quantity` value; `h.reported(site)` counts the runtime's reports of that site (`RowsFixture` installs a report handler on its runtime). Benchmarks `[.benchmark][interpreter]` in `bench_interpreter.cpp` are timings only: U1 (a header click on a text column of 100,000 rows), U2 (one row changed, shared and fresh decode) and U4 (memory of 10,000 × 300 with one column sorted); their count gates are the ordinary case above, not assertions inside a hidden benchmark. + +- [ ] **Step 2: Run to verify they fail** — `cmake --build --preset cl-debug --target morph_tests` → FAIL: `ValueRowsSource` undeclared. +- [ ] **Step 3: Implement** as above. +- [ ] **Step 4: Run to verify they pass** — `ctest --test-dir build/cl-debug -R "value rows source" --output-on-failure`. +- [ ] **Step 5: Mutations**, as named. +- [ ] **Step 6: Commit** `feat(ui): a document's rows as a table source`. + +#### 11b — The interpreter's tables on the engine + +**Files:** +- Modify: `src/ui/document.cpp` (the loader, cross-part decision 44: a column part's `kind`, and the `persist`-without-`id` refusal), `tests/test_ui_document.cpp` (their cases), `include/morph/ui/interpreter.hpp` (`TableView` stays as the shape element values read; `ElementState::tableRows` (`std::shared_ptr`) replaces `sortBound`'s use for ordering), `src/ui/interpreter.cpp` (`sortedRows` and the ordering half of `tableView` removed; the lowering of a `rows` table onto `ValueRowsSource` → `Engine` → `EngineRows`; `pageSize`/`page` as a slice of the engine's view; `group` as a hidden leading sort key `ValueRowsSource` computes, headings placed after paging; `rowSpans` on the page's rows, drawn only unsorted and below the windowing thresholds; select-all through `table::Selection::selectAll`) +- Test: `tests/test_ui_table_model.cpp`, `tests/test_ui_table.cpp`, `tests/bench_interpreter.cpp` (B1) +- Docs: `docs/spec/ui/interpreter.md` ("Lowering", **The rows' pipeline** and **Groups** describe the engine's order and what the lowering does around it), `docs/spec/ui/document.md` (a column's `kind`; the client-mode bound warning), `docs/spec/table/engine.md` ("Not here yet": the single-threaded steps entry). + +**Interfaces:** +- Consumes: 11a; `table::Engine` with `EngineOptions{owner = &runtime.owner(), worker = nullptr, frameBudget = 4 ms, services.collator = ValueRowsCollator}`. +- Produces: `void EngineRows::setRestoring(bool restoring)` (while `true`, `total().known` is `false` and `row()` answers nothing, so the mount draws placeholder rows; the engine still runs); otherwise nothing new in the API, and every existing table element value keeps its name and shape. + +Decisions: +- A plain list over 20,000 rows or 1,000,000 cells (rows × the node's columns) is reported once as a warning naming the table: `"table holds rows; a table over rows is ordered on the client up to 20,000 rows or 1,000,000 cells — serve it as a model's table"`. +- The loader (`src/ui/document.cpp`). `kColumnKeys` (`:322`) gains `{"kind", Shape::Text}`, a literal among `text`, `integer`, `decimal`, `number`, `date`, `dateTime`, `bool` (`"`kind` is one of text, integer, decimal, number, date, dateTime, bool"`). A table over `rows` with no `id` gets no state key: a `persist` it writes that is not `false` is refused when the document loads (`"a table over `rows` needs an `id` to persist its arrangement"`); with no `persist` key such a table simply persists nothing. `status` and `persist` are accepted on a `rows` table as 9d added them. +- The status line of a `rows` table (table.md "The status line"): `TableStatus::shown` is true while `state` or `message` is not empty and false otherwise, so the line takes no space on a table with nothing to say; `status: true` shows it always (with its counts), `status: false` never, a message then going to `InterpreterHost::notify` as in 9d. Its counts are `countsText(counts(), selectedCount, formatting)` whenever it shows. +- What the screen shows of a row comes from `EngineRows`' record of it, which is read again only for a row a change names. `ValueRowsSource` (11a) notifies `Updated` for a row whose value changed even when no column in use reads the change, and for the first source row of a run whose heading record changed while the runs kept their places; the engine repairs such a row in place. The lowering re-reads `runRecords()` on every `onChange`, and calls `setGroup` again, with the screen's unit table, when what `by` reads besides the row changes, since the source reads `by` untracked. Test: a refetch that changes only a displayed field redraws that row's cell (mutation: `EngineRows` keeping its record of an `Updated` row), and a heading's `count` follows a row that joins its run. A rows table's mount realizes every row below `Virtualization::threshold` (`TableSource::alwaysWindowed = false`), as table.md's "When a table is windowed" has it, while a model-backed table is always windowed: the "one order" case scrolls the model table over its 200 rows before comparing. +- An invalid cell in a column of the sort chain is reported once per table at the node's `sort` path, as the interpreter reports a sort value of a mixed kind today: the lowering reads `ValueRowsSource::invalidCells(column)` for each key after a view change and reports when it first is not 0. +- The mount: a `rows` table lowers onto `Table::source` as a model-backed one does (9d's `TableSource`), `cellView` over each cell's signal, `rowView` giving `rowTone`, `rowLabel`, `rowSpans` and, for a group heading's key, `heading` (the lowered `heading` content), so the two kinds share one mount path. +- Persisted state for a `rows` table (table.md "Persisted state": "a client-mode table draws placeholder rows"). With a session store, an `id` and `persist` not `false`, the key is `{application = SessionOptions::application, model = "" (a table over a document's rows has none; 9c's bounds allow it), table = the node's id, qualifier = the persist string or the screen's id, part = "state"}`. The lowering calls `setRestoring(true)` before the first `assign`, starts the load through `Session::tableStates()`, and on completion within `tableStateTimeout` applies the fitted sort and filters (bound ones are the document's, as in 9d) and calls `setRestoring(false)`: the first rows drawn are in the stored order. Past the timeout it calls `setRestoring(false)` with the defaults, and a later state is applied unless the user touched the table, as in 9d. Sort and filter changes go to `TableStates::changed` with the same debounce and unmount flush as 9d's; the description passed to `fitState` is built from the node's columns and the inferred kinds (`TableDescription{id, columns, key}` with each `TableColumn{info, label, sortable, filterable}`). + +- [ ] **Step 1: Write the failing tests.** `tests/ui_table_support.hpp` gains `rowsDoc(itemsLiteral, tableExtra = "")`: a `ui/1` document whose state `items` is initialised to that literal list and whose view is a column of a table `list` (test id `list`) over `{"ref":"items"}`, `"key":{"row":"id"}`, columns `id`, `name` and `weight`, each `sortable`, with `tableExtra` appended to the table node, and a button `rename` whose `onClick` sets `items` to the same list with the row of id `"b"` renamed `"zz"`, or the first row when no row has that id, so the list always changes; `rowsDocNoId` is the same with no `id` on the table; `rowOrder(h)` is the keys of the table's realized rows in child order, joined by spaces; `engineOf(screen, id)` the `table::Engine` of that table's `EngineRows` (through `ScreenProbe`); `kThree` is `[{"id":"a","name":"a"},{"id":"b","name":"b"},{"id":"c","name":"c"}]`; `mixedRows()` is 200 rows whose names mix accents and case (`"Émile"`, `"emil"`, `"Zoë"`, `"zoe"`, …), with decimal weights and every tenth name and weight `null`, as a JSON list; `kRowsSamples` is `kModelTable`; `pagesOf(rows, query)` answers a `TableQuery` over those rows through `table::apply` with `ValueRowsCollator` as the served collator, as a generic page. + +In `tests/test_ui_table_model.cpp` (not `test_ui_document.cpp`: `ui_table_support.hpp` there clashes with the Windows `Concurrency` namespace that file names; `loads` and `refusalOf` move into `ui_table_support.hpp`): + +```cpp +// Mutations: `kind` not in kColumnKeys (the bad kind loads); no `persist` check on a rows table without an id. +TEST_CASE("ui document: a rows table's column kind and its persist need what they name", "[ui][document]") { + CHECK(loads(rowsDoc(kThree, R"(,"persist":"mine")"), tableCatalog())); + CHECK(refusalOf(withColumnKey(rowsDoc(kThree), "name", R"("kind":"money")")) == + "`kind` is one of text, integer, decimal, number, date, dateTime, bool"); + CHECK(loads(withColumnKey(rowsDoc(kThree), "name", R"("kind":"text")"), tableCatalog())); + CHECK(refusalOf(rowsDocNoId(kThree, R"(,"persist":true)")) == + "a table over `rows` needs an `id` to persist its arrangement"); + CHECK(loads(rowsDocNoId(kThree, R"(,"persist":false)"), tableCatalog())); + CHECK(loads(rowsDocNoId(kThree), tableCatalog())); +} +``` + +In `tests/test_ui_table_model.cpp`: + +```cpp +// Mutation: the interpreter's pipeline left in place for `rows` tables (the accented names order apart). +TEST_CASE("one order on every surface: a rows table and a model table order alike", "[ui][table]") { + std::string const rows = mixedRows(); + for (std::vector const& clicks : {std::vector{1}, // by name + std::vector{1, 1}, // by name, descending + std::vector{2}}) { // by weight + TableHarness asRows; auto rowsScreen = asRows.mount(rowsDoc(rows)); + TableHarness asModel; auto modelScreen = asModel.mount(kRowsSamples); + replyDescribe(asModel, describedFrom(rows)); + replyPage(asModel, pagesOf(rows, lastQuery(asModel))); + for (std::size_t column : clicks) { + asRows.backend.clickHeader(tableOf(asRows), column); asRows.settle(); + asModel.backend.clickHeader(tableOf(asModel), column); asModel.settle(); + replyPage(asModel, pagesOf(rows, lastQuery(asModel))); + } + asModel.backend.scrollTable(tableOf(asModel), 0, 200); asModel.settle(); // a model table is windowed + CHECK(rowOrder(asRows) == rowOrder(asModel)); + CHECK_FALSE(rowOrder(asRows).empty()); + } +} +// Mutation: sorting the whole list on a row change (fullSorts grows). Gate U2 counts, on a screen. +TEST_CASE("rows table: one changed row is one repair", "[ui][table]") { + TableHarness h; auto screen = h.mount(rowsDoc(kThree)); + h.backend.clickHeader(tableOf(h), 1); h.settle(); + REQUIRE(rowOrder(h) == "a b c"); + table::EngineStats const before = engineOf(*screen, "list").stats(); + h.backend.click(h.byTestId("Button", "rename")); h.settle(); + CHECK(engineOf(*screen, "list").stats().repairs - before.repairs == 1); + CHECK(engineOf(*screen, "list").stats().fullSorts == before.fullSorts); + CHECK(rowOrder(h) == "a c b"); // "zz" moved last +} +// Mutations: no bound check (no warning); the bound read as `>=` (a warning at 20,000). A warning per change of the +// list is not observable here: the screen reports a repeated path and reason once. +TEST_CASE("rows table: a list over 20,000 rows is reported once", "[ui][table]") { + TableHarness h; auto screen = h.mount(rowsDoc(idRows(20'001))); + std::string const warning = "table list holds 20,001 rows; a table over rows is ordered on the client up to " + "20,000 rows or 1,000,000 cells — serve it as a model's table"; + CHECK(diagnosticsMentioning(h, warning) == 1); + h.backend.click(h.byTestId("Button", "rename")); h.settle(); // the list changes: no second report + CHECK(diagnosticsMentioning(h, warning) == 1); + TableHarness under; auto small = under.mount(rowsDoc(idRows(20'000))); + CHECK(diagnosticsMentioning(under, "serve it as a model's table") == 0); // at the bound: nothing +} +// Mutation: drawing the rows before the load settles (the first CHECK reads "a b c"). +TEST_CASE("rows table: persisted state before the first rows", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), + R"({"version":1,"sort":[{"column":"name","direction":"desc"}]})"); + TableHarness h{store}; auto screen = h.mount(rowsDoc(kThree)); + CHECK(rowOrder(h).empty()); // placeholders only while restoring + CHECK(store->lastLoadKey() == table::TableStateKey{.application = "lims", .model = "", .table = "list", + .qualifier = "samples", .part = "state"}); + store->release(); h.settle(); + CHECK(rowOrder(h) == "c b a"); // first drawn: the stored order + h.backend.clickHeader(tableOf(h), 1); h.advance(500ms); CHECK(store->saves() == 1); +} +// Mutation: a rows table without `id` given a key (a load goes out with table ""). +TEST_CASE("rows table: a table without an id persists nothing", "[ui][table][state]") { + auto store = std::make_shared(storeExecutor(), R"({"version":1})"); + TableHarness h{store}; auto screen = h.mount(rowsDocNoId(kThree)); + CHECK(rowOrder(h) == "a b c"); // no restoring state + h.backend.clickHeader(h.backend.all("Table").front(), 1); h.advance(500ms); + CHECK(store->loads() == 0); CHECK(store->saves() == 0); +} +// Mutations: `shown` always true for a rows table; a message under `status: false` kept in the line. +TEST_CASE("rows table: the status line takes space only while it has something to say", "[ui][table]") { + TableHarness h; auto screen = h.mount(rowsDoc(kThree)); + CHECK_FALSE(statusOf(h).shown); + coreOf(*screen).tableMessage(elementOf(*screen, "list"), "Refused"); h.settle(); + CHECK(statusOf(h).shown); CHECK(statusOf(h).message == "Refused"); CHECK(statusOf(h).counts == "3 rows"); + h.advance(6'000ms); CHECK_FALSE(statusOf(h).shown); + TableHarness always; auto shown = always.mount(rowsDoc(kThree, R"(,"status":true)")); + CHECK(statusOf(always).shown); CHECK(statusOf(always).counts == "3 rows"); +} +// Mutation: no report of an invalid sort cell (the count is 0). One report per view change is not observable here: +// the screen reports a repeated path and reason once. +TEST_CASE("rows table: a cell not of its column's kind is reported once at the sort path", "[ui][table]") { + TableHarness h; + auto screen = h.mount(rowsDoc(R"([{"id":"a","weight":1},{"id":"b","weight":"heavy"},{"id":"c","weight":2}])")); + auto const sortReports = [&h] { + return std::ranges::count_if(h.diagnostics, [](Refusal const& r) { return r.path.ends_with("/sort"); }); + }; + h.backend.clickHeader(tableOf(h), 2); h.settle(); + CHECK(rowOrder(h) == "a c b"); // the invalid cell sorts last + CHECK(sortReports() == 1); + h.backend.clickHeader(tableOf(h), 2); h.settle(); + CHECK(rowOrder(h) == "c a b"); CHECK(sortReports() == 1); // last in either direction, once +} +// Invariant 17: the existing `rows` table suites (test_ui_table.cpp, test_ui_interpreter_table.cpp, +// test_ui_table_row_span.cpp) stay green with no expectation changed. +``` +`idRows(n)` is `n` rows `{"id": i, "name": "n"}` as a JSON list; `describedFrom(rows)` the `TableDescription` of `id` (key), `name` and `weight` with the kinds 11a infers from those rows; `withColumnKey(text, column, member)` adds a member to that column part. +The collection half of "One order on every surface" is Task 13's (step 8): this case covers the `rows` and model-backed surfaces and Task 13 adds the collection. B1 at 20,000 rows is a `[.benchmark]` case in `bench_interpreter.cpp` reading `EngineStats::maxOwnerStepMicros` after a three-key sort and a text filter, asserting first that the engine ran in more than one owner step. + +- [ ] **Step 2: Run to verify they fail** — `cmake --build --preset cl-debug --target morph_tests` → FAIL: `EngineRows::setRestoring` undeclared; with it stubbed, `ctest --test-dir build/cl-debug -R "one order on every surface|rows table" --output-on-failure` → FAIL: orders differ (the interpreter's `Evaluator::sortRows` is still in use) and no load is made. +- [ ] **Step 3: Implement** as above; delete `ScreenCore::sortedRows` and the ordering part of `tableView`. +- [ ] **Step 4: Run to verify they pass** — the new cases and the whole `morph_tests` target green, then `morph_qt_quick_tests` and `morph_tui_tests` on `cl-qt-debug` green (their table cases mount through the interpreter). +- [ ] **Step 5: Mutations**, as named. Record U1 to U4 and B1 (10,000, 20,000 and 100,000 rows) from `cl-release` into table.md's Performance tables. +- [ ] **Step 6: Neighbouring specs** as listed; docs build green. +- [ ] **Step 7: Commit** `feat(ui): tables over rows on the engine`. + +#### 11c — A typed list action as a model-backed table + +table.md "The document `table` node on the engine": a node with `model` and `action` names a typed list action; "its description is derived from the action's schema, and the reader turns each row object into cells; it returns whole rows whatever `columns` says". + +**What the code gives, and the position taken.** The client's catalog holds an action's **request** schema only (`Catalog::schema`, `document.hpp`: `forms::schemaJson()`, as `RemoteServer`'s `schemas` envelope serves it, `registry.hpp:657`); no reply schema reaches a client. The reply's row type reaches one only through a `v-*` view document (`Catalog::view`, whose `v-columns` `views.hpp:476` derives from the query's row type). So the description is built from, in order: the node's `columns` parts (ids required), else `Catalog::view(action)`'s `v-columns` (ids and labels) and `v-rowKey`; the key from the node's `key`, else `v-rowKey`, else `"id"`; each column's kind from the node part's literal `kind`, else the `kind` its `v-columns` entry carries (a view document writes one where the row type gives it, such as `"kind":"integer"`), else inferred from the first reply's rows by the JSON-level table below and then fixed for the window's life (a later cell not of it is invalid). The request schema must have one top-level member marked `x-table` (`TableQuery::schemaMarker()`, `query.hpp:77`): the query is written into that member of `body`. A node whose action has no such member, or which has neither `columns` nor a view document, is refused when the document loads (`"a table over an action needs a query member marked x-table"`, `"a table over an action needs its columns, or a view document for the action"`). table.md ("The client table model") states this same order and both refusals, because a catalog carries no reply schema. + +**Files:** +- Modify: `include/morph/ui/table_rows.hpp` (`WindowRowsOptions::{action, queryMember}`; `readTypedPage`), `src/ui/interpreter.cpp` (the `model` + `action` lowering), `src/ui/document.cpp` (the two refusals) +- Test: `tests/test_ui_table_model.cpp` +- Docs: `docs/spec/ui/document.md` (the `table` kind with `model` and `action`), `docs/spec/ui/interpreter.md` ("Lowering"). + +**Interfaces:** + +```cpp +// WindowRowsOptions gains +std::string action; // non-empty: a typed list action's id, sent in place of "Table.
"; `table` empty +std::string queryMember; // with `action`: the body member the query is written into (the x-table member) +std::vector inferKinds; // with `action`: the columns the first reply with rows gives a kind +std::vector records; // replaces `record`: every record watched (an action's catalog records; none + // for an action without one) +/// A typed list action's reply (`Page`'s JSON: `rows`, `total`, `totalKind`, `offset`, `indices`) as a generic +/// page over @p description's columns: each row object's member of a column's id read by its kind. +[[nodiscard]] std::expected readTypedPage(std::string_view json, + table::TableDescription const& description, + table::UnitRegistry const* units = nullptr); +// document.hpp: the members a request schema marks `x-table`, which the loader and the lowering both read +[[nodiscard]] std::vector tableQueryMembers(std::string_view schemaJson); +``` + +Decisions: +- Kinds of a typed reply. 11a's table reads `Value`s, which hold no JSON number with a fraction, so it cannot be used on a reply's text. A typed reply is inferred at the JSON level, each non-null member of a column's id voting: + + | JSON member | Votes for | Cell | + |---|---|---| + | `null`, absent | nothing | empty | + | `true`, `false` | `Bool` | `bool` | + | an integer | `Integer` | `int64`; in a `Decimal` column a `Rational` of 0 places, in a `Number` column a `double` | + | a number with a fraction or an exponent | `Number` | `double` | + | `{num, den, dp}` | `Decimal` | the `Rational`, places kept | + | `{num, den, dp, unit}` | `Measure` | `Measure` through `units->find`, the units being the view document's (each `v-columns` entry's `ExtUnits` and `x-unitAlternatives`); a unit no one lists is its own canonical unit in a dimension of its own, added to the description, so the cell is valid | + | a string | `Text` | the text | + | an array, any other object | nothing of its own | its JSON text, invalid outside `Text` | + + All votes alike → that kind; only integers and `Decimal`s → `Decimal`; integers with fractional numbers, with or without `Decimal`s → `Number`; any other mix takes the first non-null member's kind and a member not of it is invalid; no vote → `Text`. This is where a typed table and a `rows` table differ, as cross-part decision 46 has it: a fractional number in a reply's text is a `double` and its column `Number`, while the same number reaching a document's `rows` through the query cache is already a `Decimal`. A string is never inferred as `Date` or `DateTime`: those need a literal `kind` or the view document's. +- Two passes over the first reply. `WindowRows` with `action` and at least one column of no known kind holds the first reply's text until it has parsed it once as a `glz::generic_u64` DOM, run the table above over the rows for those columns, and completed its description (`setDescription`); it then reads the same DOM with `readTypedPage`. Later replies are read in one pass against the fixed description. A first reply with no rows fixes nothing: the next reply that has rows is the one inferred from. +- `readTypedPage` reads the text with a `glz::generic_u64` DOM (as `buildActionDescription` does, `registry.hpp:688`, so int64 bounds survive): a member absent or `null` → empty; an integer → `int64` (a `double` in a `Number` column); a number with a fraction → `double`; a string → text, or under `Date` `YYYY-MM-DD` → days, under `DateTime` ISO-8601 → floor seconds; `true`/`false` → `bool`; `{num, den, dp}` → `Rational`; with `unit` under `Measure` → `Measure` through `units->find` (a window lists an unknown unit first, as its own canonical unit, so it is found; `readTypedPage` alone, given a registry without it, leaves it invalid); anything else → the member's JSON text, invalid outside `Text`. The key is the row's member named by the description's `key`, read as a `RowId`. `columns` is every description column, `revision` empty (so `onStaleDescription` never fires). +- `WindowRows` with `action` sends `session.read(options.channel, action, body with body[queryMember] = the query, token)` and decodes the text with `readTypedPage`; the reply holds whole rows, so `visible`'s columns name what the record converts (K8 holds) but not what is fetched. Keyed refetches and `highlightKey` send `keys` in the query member; an action whose reply has no `indices` for a keyed query invalidates the window (`PageWindow::patch`'s rule), which costs a page refetch and not a wrong row. +- The record watched is each `ActionInfo::records` entry of the action (`document.hpp:56`); with none, the window refetches only on `invalidate` (reconnect). + +- [ ] **Step 1: Write the failing tests.** `kActionTable` is `{"vocab":"ui/1","id":"samples","models":{"lab":{"type":"Lims_SampleModel"}},"view":{"kind":"table","id":"list","testId":"list","model":"lab","action":"Lims_PageSamples","key":{"row":"id"},"columns":[{"id":"id"},{"id":"name"},{"id":"weight"},{"id":"ratio"},{"id":"day","kind":"date"}]}}`; the test adds `Lims_PageSamples` to the harness with `addAction(h, "Lims_PageSamples", R"({"type":"object","properties":{"query":{"type":"object","x-table":true},"site":{"type":"string"}}})", ActionInfo{.modelType = "Lims_SampleModel"})`; `kActionTableNoQuery` names `Lims_ListSamples`, whose schema (the corpus catalog's) has no `x-table` member; `kActionTableNoColumns` is `kActionTable` without `columns` (and `Lims_PageSamples` has no view document); `kindOfColumn(screen, column)` reads the window's description through `ScreenProbe`; `cellOf(screen, row, column)` the window's `cell(row, column)`. + +```cpp +// Mutations: `{num, den, dp}` read as text (weight is Integer, from 3 alone, and not a Rational); a fractional number voted +// Decimal (ratio is Decimal); the query written at the body's top level (no "query" member in the body). +TEST_CASE("model table over an action: a typed list action's rows read into the window", "[ui][table]") { + TableHarness h; addPageSamples(h); + auto screen = h.mount(kActionTable); + REQUIRE(h.dispatcher.count("Lims_PageSamples") == 1); // no describe call: none exists + CHECK(h.dispatcher.calls.back().body.contains(R"("query":{)")); // the query in the x-table member + h.reply(h.dispatcher.last("Lims_PageSamples"), + R"({"rows":[{"id":1,"name":"a","weight":{"num":5,"den":2,"dp":1},"ratio":0.5,"day":"2026-11-17"}, + {"id":2,"name":"b","weight":3,"ratio":2,"day":null}],"total":2})"); + using enum table::ColumnKind; + CHECK(kindOfColumn(*screen, "id") == Integer); CHECK(kindOfColumn(*screen, "name") == Text); + CHECK(kindOfColumn(*screen, "weight") == Decimal); // {num,den,dp} with an integer + CHECK(kindOfColumn(*screen, "ratio") == Number); // a fraction with an integer + CHECK(kindOfColumn(*screen, "day") == Date); // the literal kind + CHECK(*cellOf(*screen, 0, "ratio") == table::Cell{0.5}); CHECK(*cellOf(*screen, 1, "ratio") == table::Cell{2.0}); + CHECK(std::holds_alternative(*cellOf(*screen, 1, "weight"))); + CHECK(*cellOf(*screen, 0, "day") == table::Cell{std::int64_t{20'774}}); // days since 1970-01-01 + CHECK(std::holds_alternative(*cellOf(*screen, 1, "day"))); + CHECK(statusOf(h).counts == "2 rows"); + h.backend.clickHeader(tableOf(h), 1); h.settle(); + CHECK(h.dispatcher.calls.back().body.contains(R"("sort":[{"column":"name")")); + h.reply(h.dispatcher.last("Lims_PageSamples"), R"({"rows":[{"id":3,"name":"c","weight":"heavy","ratio":1}],"total":1})"); + CHECK(kindOfColumn(*screen, "weight") == Decimal); // fixed by the first reply +} +// Mutation: the view document's `kind` ignored (id is inferred Text from a reply whose ids are strings). +TEST_CASE("model table over an action: columns and kinds come from the action's view document", "[ui][table]") { + TableHarness h; // Lims_ListSamples has a v-columns view + addAction(h, "Lims_ListSamples", R"({"type":"object","properties":{"query":{"type":"object","x-table":true}}})", + ActionInfo{.modelType = "Lims_SampleModel"}); + auto screen = h.mount(withTableKey(kActionTableNoColumns, R"("action":"Lims_ListSamples")")); + h.reply(h.dispatcher.last("Lims_ListSamples"), R"({"rows":[{"id":"7","name":"a"}],"total":1})"); + CHECK(headerLabels(h) == std::vector{"Name"}); // v-columns' label; `id` is v-hidden + CHECK(kindOfColumn(*screen, "id") == table::ColumnKind::Integer); // v-columns' kind, not the reply's +} +// Mutations: the loader accepting an action with no x-table member (the first fetch sends a bare body); accepting +// one with neither `columns` nor a view document. +TEST_CASE("model table over an action: an action the table cannot page is refused at load", "[ui][table]") { + TableHarness h; addPageSamples(h); + CHECK(refusalOf(h, kActionTableNoQuery) == "a table over an action needs a query member marked x-table"); + CHECK(refusalOf(h, kActionTableNoColumns) == + "a table over an action needs its columns, or a view document for the action"); +} +``` +`addPageSamples(h)` is the `addAction` call above; `refusalOf(h, text)` loads against the harness's catalog and returns the refusal's message. + +- [ ] **Step 2: Run to verify they fail** — `cmake --build --preset cl-debug --target morph_tests` → FAIL: `readTypedPage` undeclared. +- [ ] **Step 3: Implement** as above. +- [ ] **Step 4: Run to verify they pass** — `ctest --test-dir build/cl-debug -R "model table over an action" --output-on-failure`; `morph_tests` green. +- [ ] **Step 5: Mutations**, as named. +- [ ] **Step 6: Neighbouring specs** as listed; docs build green. +- [ ] **Step 7: Commit** `feat(ui): a typed list action as a model-backed table`. + +--- + +## Decisions the spec now states + +Each was taken by this plan and is now stated in table.md, so no task of this part edits table.md for it. + +1. **An empty `model` in a table-state key** (9c): `model` is 0 to 256 bytes, the other key members 1 to 256 ("Persisted state", "Bounds"). +2. **Pages are read from the reply's text** (9a, cross-part decision 30). A `Value` cannot hold a JSON number with a fraction, so `Session::read` resolves with the reply's JSON text, and `WindowRows` decodes it with `readGenericPage` (or `readTypedPage`). The description still comes through the query cache, losslessly ("The client's caches"). +3. **A `rows` table orders timestamps to the second** (11a), as a `DateTime` column holds them; the expression language's `sort` orders to the millisecond ("A document's rows as a source"). +4. **A typed list action's description** (11c) comes from the node's `columns` or the action's view document, with kinds from the node, then the view document, then inferred from the first reply's JSON, because no client catalog carries a reply schema ("The client table model"). A fractional number there is a `Number`, while in a document's `rows` it is a `Decimal` (cross-part decision 46). +5. **The quota spans applications** (9c): one usage entry per person, under the model's own id ("Bounds": "across one person's stored state, in every application"); two model instances can overshoot it by one document. +6. **`kind: "number"` is the only way to a `Number` column over `rows`** (11a): a document value has no `double` ("A document's rows as a source"). +7. **A new description revision mounts the table again** (9d): `Table::columns` is set once, so the columns of a new revision are a new `Table` under the same element state; the window, sort, filters and selection survive, realized cells and the scroll offset do not ("Rows on the wire"). +8. **The names table state keeps are refused by the preferences model** (9c): an `app` of `morph.tableState` and a scope starting `morph.table` ("Persisted state", "Reserved names"); `docs/spec/ui/preferences.md` gains the rule in 9d's docs step. + +## Self-review notes + +- Spec coverage: "The pipeline" and "Sources" — 9a (`EngineRows`, `WindowRows`), 11a (`ValueRowsSource`); `VectorSource` is Task 13's. "The client table model" — 9a, 9d. "The renderer" — 10a, 10b; its "Range selection in server mode" lands in 10a (cross-part decision 13), as Delivery order step 5 lists it. "The document `table` node" — model-backed rows in 9d, `rows` rows in 11b; `cellMenu`, `headerMenu`, `layout`, `configurable`, `locked`, display parts and `maxSortKeys` are Tasks 12, 15, 16, 17. "Where sort and filter run" — the client-mode bound warning in 11b; the refusal of a client-mode sort on a column with a level needs a `rows` column with a level, which a document cannot declare yet, so it has no task here. "Persisted state" (sort and filters, both stores, load before rows) — 9b to 9d; saved and shared views are Task 14's. +- Cross-part decisions 11 (`tableMessage`, `kStatusMessageHold`: 9d), 28 (`TableSource::cellView`/`rowView`/`alwaysFetched`, cells owning a row signal, `RecordOf` → `RowRecord`: 9a, 9d, 10a) and 29 (`CellLoad`, `setCellLoad`: 9d, 10b). `highlightKey` and `model` + `action` are 10a and 11c. +- Cross-part decisions 37 (a `column` is an index into `Table::columns`: 9d, 10a), 38 (`CarriedState::Column`'s equality here, the filter types' from 8b), 39 (`TableRowLook` is extended, not replaced), 40 (`onChange` is one slot), 41 (`TableOptions` mirrors `Table`), 42 (`RowsFixture`, `TableHarness`, the catalog seam `addAction`), 44 (the loader: 9d, 11b, 11c), 46 (a fractional `rows` column is `Decimal`: 11a, 11c) and 52 (`Table::focus` and `onFocusCell` are `CellRef` here and re-typed by Task 19). +- Every test case in this part has a body and names the mutation it fails on; a helper a case uses is defined in the step that first uses it, in `tests/ui_table_support.hpp` unless the step names another file. +- Gates: U1–U4 (11a/11b), U6 and F1, F6, F7, K5, K8, T1, T3–T5, W6 (9), F1–F5, F8–F10, U7, D8 (10), U8 (10c, measured locally in a headless browser), B1 (11b). diff --git a/docs/superpowers/plans/2026-11-17-one-table-e-configure.md b/docs/superpowers/plans/2026-11-17-one-table-e-configure.md new file mode 100644 index 000000000..1118d156d --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-one-table-e-configure.md @@ -0,0 +1,1406 @@ +# The One Table, Part E: Configuring, Collections, Saved Views, the Sort Bound — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Let a user arrange any table from its header and its table menu (column order, visibility, pinning, width, sort chains, filters by values and conditions, column groups, display units, copy, range selection in server mode, a status line that shows every refusal), put collections on the same lowering, keep saved and shared views, and raise the sort bound to 32 keys. + +**Architecture:** The gestures are pure functions in a new UI header (`include/morph/ui/table_config.hpp`) over `table::ColumnLayout`, `ui::SortChain` and `table::FilterSpec`, tested without a backend. The backend contract grows header menus, sort chains, column moves and resizes, filter buttons, group headers, the status line and the clipboard; both backends and `RecordingBackend` implement them and one set of conformance cases holds all three to it. The interpreter's table lowering (built by Tasks 9 and 11) reads the new document keys and wires gestures to `TableRows`; the filter menu, the column chooser and the sort dialog are view trees the lowering mounts in dialogs, so both backends draw them with widgets they already have. Collections lower through the same table surface; saved views are the `views` part of persisted state, with an operation-and-conflict rule and a `publish` action for shared views. + +**Tech Stack:** C++23, header-only morph plus `src/ui`, `src/qt_quick`, `src/tui`; glaze; Catch2; Qt 6 Quick (offscreen `morph_qt_quick_tests` only); the terminal backend (`morph_tui_tests`). + +**Spec:** `docs/spec/table/table.md` — "Configuring a table" (all subsections: "Columns: order, visibility, pinning, width", "Sort chains", "Filters from the header", "Column groups" (the menu), "The status line", "Copy", "Persisted state" with "The framework's stores", "Saved views"), "Keyboard, focus and assistive technology" (range selection in server mode), "Collections and master-detail", "Values with units" ("The values list and the menu", "Display"), the matching rows of "Tests", invariants 21, 26, 31, gates D7, D9, B3, B4, U5, T2, and the step 7, 8, 9 and 9c rows of "Neighbouring specs" and "Delivery order". Roadmap: `docs/superpowers/plans/2026-11-17-one-table.md` (Tasks 12, 13, 14, 16). + +Part E of 7; index: 2026-11-17-one-table.md + +## Global Constraints + +Everything in the roadmap's Global Constraints and its standard task loop applies to every task here. In addition: + +- Limits, verbatim from the spec: a chain holds at most `maxSortKeys` keys, 8 by default and up to 32 (`TableCapabilities::maxSortKeys`, a `rows` table's literal `maxSortKeys`); `SessionOptions::maxRangeRows = 10'000`, `maxCopyRows = 10'000`; `QueryLimits::maxKeys = 1000` (rows per keyed copy request), `maxSetValues = 10'000`, `maxGroupColumns = 16`; `DistinctRequest::limit = 200`; a text filter and a values search are debounced 250 ms; a status message holds for six seconds or until the user's next gesture on the table; `tableStateDebounce = 500 ms`; `segmentBytes = 12 KiB`. +- Status line and menu copy is exact, English, with counts grouped by `ui::groupedCount` with the session's numeric grouping separator (`FormatContext`; "10,000" in English): + - `A table sorts by at most {n} columns` · `A range selects at most {n} rows` · `A copy holds at most {n} rows` + - `Copied {n} rows` (`Copied 1 row`), and with unloaded cells `Copied {n} rows, {m} cells were not loaded` (`1 cell was not loaded`) + - `{label} is locked` · `At least one column stays visible` · `This table's columns cannot be moved` (`hidden`, `pinned`, `resized`) + - `A group has 2 to 16 columns` · `A group's columns hold one kind of value` · `{label} is already in {group}` + - `Too many values to list; filter with a condition` · `Too many dates to list; filter with a condition` · `The list may grow while data loads` · `{n} cells could not be read` (`1 cell could not be read`) + - header accessible description, lower case as the spec writes it: `sorted ascending` / `sorted descending`, and with two or more keys `sorted ascending, key 2 of 3`; header mark ` ▲` / ` ▼`, and with two or more keys ` ▲2`; a filtered header's accessible name `{label}, filtered` + - menus and dialogs: `Sort ascending`, `Sort descending`, `Add to sort`, `Remove from sort`, `Filter…`, `Filter {group}, {k} columns…`, `Move left`, `Move right`, `Pin column`, `Unpin`, `Hide column`, `Display unit`; `Columns…`, `Sort…`, `Clear all filters`, `Reset columns`, `Copy`, `Copy with headers`; `(Select all)`, `(Blanks)`, `Group columns…`, `Remove group`, `Add key`; views (Task 14): `Views`, `Save view…`, `Rename view…`, `Remove view`, `Set as default`, `Start from the default view`, `Shared views`, `Publish view…`, `Save as my view`, `{name} (modified)`, `Saved view {name}`, `A view named {name} exists`, `Views could not be saved: another window changed them at the same time`, `Published view {name}`, `This view could not be published: {reason}` +- Test trees. `morph_tests` and `morph_table_tests` build in `cl-debug`. `morph_qt_quick_tests` and `morph_tui_tests` need Qt Quick and the terminal backend, which no checked-in Windows preset turns on: configure once with `cmake --preset cl-qt-debug -DMORPH_BUILD_QT_QUICK=ON -DMORPH_BUILD_TUI=ON`, build with `cmake --build build/cl-qt-debug --target `, run with `ctest --test-dir build/cl-qt-debug -R "" --output-on-failure` (Qt Quick cases run with `QT_QPA_PLATFORM=offscreen`, set by their `catch_discover_tests`). `morph_net_tests` is POSIX-only (`MORPH_BUILD_NET` is ignored on Windows): its cases build and run on the `linux-everything` preset, `ctest --test-dir build/linux-everything -R ""`. Every case that can run in `morph_tests` is placed there, so a Windows tree runs it. +- Timings marked (P) or (M) in the spec are recorded into `docs/spec/table/table.md` "Performance" with the date and the machine, from a `cl-release` (or `linux-everything` for `tests/net`) build; a gate is an ordinary test. +- No GUI application is launched. The one step that grabs screens (Task 12f) runs the example client offscreen through the repository's grab scripts and is run by the user, not by an agent. + +## Review Focus + +1. **Hiding a column the view is sorted or filtered by.** Arranging is not ordering (invariant 21): the sort and the filter keep applying, the next query still sorts and filters by the hidden column while no longer naming it in `columns`, the header mark and the filtered state reappear when it is shown, and the chooser lists it unticked. Test goes to Task 12c ("hiding a sorted and filtered column changes no row"). +2. **A chain at its bound.** With `maxSortKeys` keys held, `Shift`+click on a column already in the chain flips its direction and is not refused; on any other column it is refused and the chain is unchanged; "Add to sort" is disabled and "Remove from sort" frees a place. Tests go to Task 12a (the gesture) and Task 12c (the message). +3. **Exactly at a row bound.** A range of exactly `maxRangeRows` (10,000) rows selects them all; 10,001 is refused and selects nothing (Part D's Task 10a rule, held here at its edge). A copy of exactly 10,000 rows copies; 10,001 is refused. Test goes to Task 12f ("range and copy at their bounds"). +4. **Cell text that breaks a line or a column.** A cell holding `a\tb\r\nc`, a lone `\r` and a label with a tab copy as one line of tab-separated fields: each tab, `\r\n`, `\r` and `\n` is one space, headers included. Test goes to Task 12a ("copy text: tabs and line breaks become one space"). +5. **A view name already taken.** Saving a view under a name the user already has replaces that view (one `replace` operation, still one view of that name); renaming a view onto a taken name is refused with `A view named {name} exists` and changes nothing; the same holds when the taken name arrived from another window between load and save (the operation is applied to what is stored now). Test goes to Task 14b ("views: a taken name is replaced on save and refused on rename"). + +--- + +## Interfaces this part consumes from Parts A–D + +Names the roadmap pins are used as it gives them. Where the roadmap leaves a name open, this plan uses the one below; the executor of each consuming task checks it against the landed code first and, if it differs, uses the landed name and corrects this plan. + +| From | Pinned by the roadmap | Assumed here (not pinned) | +|---|---|---| +| Task 1 | `table::TableColumn{info, label, group, sortable, filterable, shown}`, `ColumnGroupInfo{id, label, columns}`, `TableCapabilities{keys, distinct, maxSortKeys = 8}`, `TableDescription`, `GenericRow`, `GenericPage` | — | +| Task 2 | `ServedTable{description, source, levels, mayRead, scope, services, limits}`, `BRIDGE_REGISTER_TABLE` with `Table.` and `Table..describe` | the index's answer path `table::detail::answerQuery(ServedTable const&, TableQuery const&, AnswerContext const& = {})` in `description.hpp`; Task 16 makes it and the `describe` handler take their description from `table::servedDescription` | +| Tasks 3–5 | `struct Unloaded`, `TableQuery::{columns, keys}`, `Page::indices` | `TableQuery::retry` (bool), from the level cache's rule 11 | +| Task 8a | `FilterEntry::oneOf`, `DistinctRequest`, `DistinctValue`, `DistinctValues`, `DateBucket`, `Engine::distinctValues`, `TableQuery::distinct`, `Page::distinct` | — | +| Task 8b | `GroupMode`, `ColumnCount{Kind, n}`, `GroupFilter{group, columns, mode, match, combine, include, exclude}` | — | +| Task 8c | `ColumnKind::Measure`, `UnitInfo`, `DistinctValue::{dimension, unit}` | — | +| Task 8d | `ColumnLayout::setWidth(id, std::optional)`, `widths()`, `setPinned(n)`, `pinned()`, `value()`, `apply(value)` | as Part C writes it: `table::ColumnLayoutValue{order, hidden, pinned, widths, groups, units}` (`groups` a `std::vector` of user-formed groups, `units` column → dimension → unit id), `std::size_t pinned()` counting the first visible columns, `widths()` a `std::map const&`; `apply` and `rebuild` fit groups and units | +| Task 9 (Part D) | `ui::SortChain`, `TableCountsView`, `TableRows` (`total`, `row`, `unloadedLevels`, `visible`, `keysOf`, `setSort`, `setFilter`, `counts`, `onChange`), `EngineRows`, `WindowRows`, `TableStateKey`, `StoredTableState`, `SaveOutcome`, `SaveResult`, `ITableStateStore`, `MemoryTableStateStore`, `PreferencesTableStateStore`, `TableStateModel` (`morph.tableState`), `SessionOptions::tableState` | as Part D writes them: `EngineRows(std::shared_ptr, RecordOf, table::EngineOptions)`; `WindowRows::retry()`, `WindowRows::description()`; `ui::countsText(TableCountsView const&, std::int64_t selected, FormatContext const&)`; `ui::detail::standInCellText(Cell const&, table::TableColumn const&)`; `ui::TableStatus{counts, state, retry, message, shown}`, `Table::status`, `Table::onRetry`, `TableWidget::setStatus`, `setOnRetry` (the status line, its counts, Retry and the `status` key are Part D's); the status line's message channel, Task 9d's per index decision 11: `void ScreenCore::tableMessage(ElementState& table, std::string text)` in `src/ui/interpreter.cpp` and `inline constexpr std::chrono::seconds kStatusMessageHold{6}` (sets `TableStatus::message` and restarts the hold on the session's scheduler; under `status: false` sends `text` once to `InterpreterHost::notify(text, "warning")`; an empty `text` clears the message and notifies nothing — this part's gestures clear it that way); `ui::TableStates` (`include/morph/ui/table_state.hpp`, 9c: `kept`, `load`, `changed`, `flush`, `onSaveFailed`, and, per index decision 32, `store() -> table::ITableStateStore&` and `keep(key, state)`, which 14b saves views through; loads made in one turn of the owner go out as one `TableStateLoad`) and `Session::tableStates() -> TableStates*`; `SessionOptions::application`; `table::StateDocument{version, layout, sort, filters, view, carried}`, `readState`, `writeState`, `fitState(StateDocument, TableDescription const&, FitReport&)`; `MemoryTableStateStore(exec::IExecutor&)` with revisions `"1"`, `"2"`, …; `ui::TableStateLoad{keys}`, `TableStateSave{key, expected, upload, offset, text, last}` → `TableStateSaved{result}`, `registerTableState(std::shared_ptr, dispatcher, registry, TableStateOptions)`; `PreferencesTableStateStore(Dispatcher&, exec::IExecutor& owner)`; test support `tests/ui_table_support.hpp`: `tableCatalog()` (the corpus catalog plus `Table.samples` and `.describe` on `Lims_SampleModel`), `samplesDescription(int columns)` (`id` Integer key, `name` Text, then `c3…` Decimal), `describeJson`, `pageJson(offset, count, total, columns, kind, undecided, awaiting)`, `GatedTableStateStore`, the harness `ui::testing::TableHarness` (9d, index decision 42; its constructor taking a `std::shared_ptr` sets `tableState` and `application = "lims"`), `elementValue(h, id, name)` (an element value as JSON text), `h.replyDescribe()`, `h.replyPage(json)`, `lastQuery(h)`, `statusOf(h)` | +| Task 10 (Part D) | the column window; `TableWidget`'s range report by view rows | as Part D writes them: `ui::TableColumn::id`, `ui::TableArrangement{visible, pinned, widths}`, `Table::arrangement` (applied without rebuilding rows, gate D8), `TableWidget::setOnSelectRange(std::function)`, `RecordingBackend::selectTableRange(id, anchor, focus)`, `SessionOptions::maxRangeRows`; range selection through `keysOf` and its refusal are Task 10a's | +| Task 11 (Part D) | `ValueRowsSource`, rows tables on `EngineRows`; the internal lowering of a table node onto `TableRows` | a column part's `kind` (`ValueColumn::kind`) and the refusal of `persist` on a table with no `id` are Task 11's | + +--- + +## Task 12: The configuration interface (table.md step 7) + +**Spec:** "Configuring a table" (all), "Values with units" ("The values list and the menu", "Display"), "Keyboard, focus and assistive technology" (range selection in server mode), "The document `table` node on the engine" (rows for `layout`, `status`, `persist`, `filters`, a column's `kind`, `locked`, `filterable`). Gates D7, D9, B3, B4. Six commits, each its own reviewer gate. + +### Task 12a: Gestures, menus, value filters and copy text, without a backend + +**Files:** +- Create: `include/morph/ui/table_config.hpp`, `tests/test_ui_table_config.cpp` (add to `morph_tests` in `tests/CMakeLists.txt`, beside `test_ui_table.cpp`) +- Modify: `include/morph/table/engine.hpp` (`ColumnLayout`, as Task 8d leaves it: the mutators for user-formed groups and display units), `tests/table/test_table_columns.cpp`, `CMakeLists.txt` (list the new header in the `morph` header set) +- Docs: `docs/spec/table/engine.md` ("`ColumnLayout`": the group and unit mutators) + +**Interfaces:** +- Consumes: Task 8d's `ColumnLayout` and `ColumnLayoutValue`; Task 8a's `FilterEntry::oneOf`; Task 8b's `GroupFilter`, `GroupMode`, `ColumnCount`; `table::SortKey{column, dir}`, `table::SortDirection`, `table::ColumnKind`. +- Produces (namespace `morph::table`, `engine.hpp`; the stored shape and its fitting are Task 8d's): + - `ColumnLayout::formGroup(std::string label, std::vector columns) -> std::expected` (returns the new id `g1`, `g2`, … the first unused; `InvalidSpec` for fewer than 2 or more than 16 columns, an unknown column, or a column already in a user-formed group), `removeGroup(std::string const& id) -> bool`, `groups() -> std::span`, `setUnit(std::string const& column, std::string const& dimension, std::optional unit) -> bool` (`nullopt` removes it), `units() -> std::map> const&`; all of them read and write the same members `value()` and `apply` carry. +- Produces (namespace `morph::ui`, `table_config.hpp`): + - `enum class SortGesture : std::uint8_t { Click, Extend, Ascending, Descending, Add, Remove }`; `struct SortChange { SortChain chain; std::optional refusal; }`; `[[nodiscard]] SortChange applySortGesture(SortChain const& chain, std::string const& column, SortGesture gesture, std::size_t maxSortKeys)` + - `enum class Configure : std::uint8_t { None = 0, Reorder = 1, Hide = 2, Pin = 4, Resize = 8, All = 15 }` with `operator|`, `operator&` and `[[nodiscard]] constexpr bool allows(Configure set, Configure what)` + - `struct LayoutColumn { std::string id; std::string label; bool locked = false; table::ColumnKind kind = table::ColumnKind::Text; }` + - gestures `MoveColumn{id, int by}`, `MoveColumnTo{id, std::size_t position}`, `HideColumn{id}`, `ShowColumn{id}`, `PinColumn{id}`, `UnpinColumn{id}`, `ResizeColumn{id, std::optional units}`, `ResetColumns{}`, `SetDisplayUnit{id, dimension, std::optional unit}`, `FormGroup{label, columns}`, `RemoveGroup{id}`, as `using LayoutGesture = std::variant<…>`; `struct LayoutResult { bool changed = false; std::optional refusal; }`; `[[nodiscard]] LayoutResult applyLayoutGesture(table::ColumnLayout& layout, std::span columns, Configure allowed, LayoutGesture const& gesture)` + - The tick model. Under a search, "(Select all)" means the values the search shows (spec 1766-1767), which the menu does not hold when they pass a page, so a tick is recorded as an operation and resolved only at Apply: + - `struct TickOp { std::string search; std::optional operand; bool ticked = true; }` — `operand` set: one value's box; unset: "(Select all)" under `search` (empty `search`: every value) + - `struct ValueTicks { bool ticked = true; std::vector ops; std::optional blanks; }` — `ticked` is every value's state before the first operation (true with no filter on the column); later operations win + - `struct ResolvedTicks { bool ticked = true; std::map covered; std::optional blanks; }` — `covered`: the final state of every value an operation reached, by operand + - `[[nodiscard]] ResolvedTicks resolveTicks(ValueTicks const& ticks, std::function(std::string const& search)> const& valuesUnder)` — `valuesUnder` returns the operands a search shows; it is synchronous, and `distinctValues` on a `WindowRows` is not: at Apply the menu first awaits, for each distinct non-empty `search` among the operand-less ops, every page of `distinctValues` at `limit = QueryLimits::maxLimit` (1000) into a `std::map>`, and only then calls `resolveTicks` with a `valuesUnder` that reads the map; an op with an empty search and no operand clears `covered` and sets `ticked`. A menu reopened on a stored values filter seeds its `ValueTicks` from it: an `include` `oneOf` is `ticked = false` plus one `TickOp{.search = "", .operand = member, .ticked = true}` per member, an `exclude` `oneOf` is `ticked = true` plus one such op with `ticked = false` per member, and `blanks` is `true` for an included `isEmpty`, `false` for an excluded one + - `struct ValueFilterPlan { enum class Side : std::uint8_t { All, Include, Exclude, Nothing, Disabled } side = Side::All; std::size_t members = 0; bool needsComplement = false; }`; `[[nodiscard]] ValueFilterPlan planValueFilter(std::int64_t distinct, ResolvedTicks const& ticks, std::size_t maxSetValues)` + - `enum class ValueForm : std::uint8_t { Set, Ranges }` (`Ranges` for date buckets, whose operand is `a..b`); `[[nodiscard]] std::optional valueFilter(ValueFilterPlan::Side side, std::vector members, std::optional blanks, ValueForm form = ValueForm::Set)` + - Values and conditions are exclusive per column: one `ColumnFilter` has one `combine` (`filter.hpp:86-93`), so `[oneOf, isEmpty, condition]` under `All` would match nothing. `enum class FilterPart : std::uint8_t { None, Values, Conditions }`; `[[nodiscard]] FilterPart classifyFilter(table::ColumnFilter const& filter, table::ColumnKind kind)` — `Values` when the filter is a values shape: `combine = Any` and `include` is `{oneOf}`, `{oneOf, isEmpty}`, one or more `between` entries (a date column's buckets) with or without `isEmpty`, or a lone `{isEmpty}` on a column that is not `Custom`, and `exclude` the same shapes with `include` empty; a lone `isEmpty`/`notEmpty` on a `Custom` column is `Conditions` (it has no values list); anything else not empty is `Conditions` + - `[[nodiscard]] std::optional canonicalOperand(std::string_view typed, table::ColumnKind kind, LocaleFacts const& locale)` — the wire form of a typed operand: a number in the locale's form (`"1.234,5"` under a comma locale) becomes a decimal with a point and no grouping (`"1234.5"`), through `render::normalizeLocaleNumber`; a date is the picker's ISO text; text is unchanged; `nullopt` when it does not read. 12a landed before 8c, so it ships without the `Measure` branch; Part C's Task 8c, Step 8a, adds the units parameters, the branch, `Measure` in `conditionOps` and their tests. `ui::SortChain` is declared here (`using SortChain = table::SortChain;`), and Part D's Task 9a reuses it + - `enum class GroupMatch : std::uint8_t { AnyColumn, EveryColumn, AtLeast, Exactly, Together }`; `[[nodiscard]] std::expected groupValueFilter(std::string group, std::size_t groupColumns, std::vector ticked, std::optional blanks, GroupMatch match, std::int64_t n)` + - `enum class ConditionOp : std::uint8_t { Equals, NotEquals, Contains, BeginsWith, EndsWith, Less, LessOrEqual, Greater, GreaterOrEqual, Between, IsEmpty, IsNotEmpty }`; `[[nodiscard]] std::vector conditionOps(table::ColumnKind kind)`; `[[nodiscard]] std::string_view conditionLabel(ConditionOp op, table::ColumnKind kind)`; `[[nodiscard]] table::FilterEntry conditionEntry(ConditionOp op, std::string operand, std::string second, bool matchCase)` + - `enum class MenuCommand : std::uint8_t { SortAscending, SortDescending, AddToSort, RemoveFromSort, Filter, FilterGroup, MoveLeft, MoveRight, PinColumn, UnpinColumn, HideColumn, DisplayUnit, Columns, SortDialog, ClearAllFilters, ResetColumns, Copy, CopyWithHeaders }` (Task 14 appends its view commands); `struct TableMenuEntry { MenuEntry entry; MenuCommand command; std::string argument; std::vector items; }`; `struct MenuGroup { std::string id; std::string label; std::size_t columns = 0; }`; `struct HeaderMenuInput { LayoutColumn column; bool sortable, filterable; std::optional sortPlace; std::size_t chainSize, maxSortKeys, visibleIndex, visibleCount, pinned; std::vector dimensions; std::vector groups; Configure allowed; }` with `struct MenuDimension { std::string dimension; std::vector units; std::string chosen; }` (`units`: unit ids in the description's order; `chosen`: the layout's display unit for the dimension, empty when the cells show their own). A column with a non-empty `dimensions` gets, last in its header menu, `Display unit` with a submenu: per dimension and unit one checkable entry labelled `{dimension}: {unit}` (`mass: g`), checked when it is `chosen`, with `command = DisplayUnit` and `argument = "{dimension}\x1F{unit}"`; choosing the checked entry clears the display unit (`SetDisplayUnit{id, dimension, nullopt}`). `FilterGroup`'s `argument` is the group's id; every other command's is empty; `struct TableMenuInput { bool anyFilter; std::vector groups; Configure allowed; }`; `[[nodiscard]] std::vector headerMenu(HeaderMenuInput const&)`; `[[nodiscard]] std::vector tableMenu(TableMenuInput const&)`; `[[nodiscard]] std::vector menuEntries(std::span)`; `[[nodiscard]] TableMenuEntry const* chosen(std::span, std::span path)` + - `struct CopiedText { std::string text; std::size_t unloaded = 0; }`; `[[nodiscard]] CopiedText copyText(std::span labels, std::span> const> rows)` (empty `labels`: no header line; `nullopt`: an unloaded cell) + - `[[nodiscard]] std::string groupedCount(std::int64_t n, std::string_view separator = ",")` + - `namespace tableText`: `sortBound(std::size_t)`, `rangeBound(std::size_t, std::string_view separator = ",")`, `copyBound(std::size_t, std::string_view separator = ",")`, `copied(std::size_t rows, std::size_t unloaded, std::string_view separator = ",")`, `locked(std::string_view label)`, `notConfigurable(Configure what)`, `lastVisible()`, `tooManyValues()`, `tooManyDates()`, `mayGrow()`, `unreadable(std::size_t, std::string_view separator = ",")` (its count is grouped as the others are), each `-> std::string`, the exact copy of Global Constraints + - (The six-second hold, `kStatusMessageHold`, is Part D's Task 9d's, with the channel that uses it; this header does not declare it.) + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_config.cpp` (tag `[ui][table][config]`), each preceded by its mutation comment: + +```cpp +// Mutation: Extend treated as Click (Shift ignored). +TEST_CASE("sort gesture: a click replaces the chain; Shift adds a key or flips one in place", "[ui][table][config]") { + using table::SortDirection::Ascending; using table::SortDirection::Descending; + ui::SortChain const two{{"name", Ascending}, {"mass", Descending}}; + CHECK(ui::applySortGesture(two, "name", ui::SortGesture::Click, 8).chain == ui::SortChain{{"name", Descending}}); + CHECK(ui::applySortGesture(two, "mass", ui::SortGesture::Click, 8).chain == ui::SortChain{{"mass", Ascending}}); + CHECK(ui::applySortGesture({{"name", Descending}}, "name", ui::SortGesture::Click, 8).chain == + ui::SortChain{{"name", Ascending}}); + CHECK(ui::applySortGesture(two, "site", ui::SortGesture::Extend, 8).chain == + ui::SortChain{{"name", Ascending}, {"mass", Descending}, {"site", Ascending}}); + CHECK(ui::applySortGesture(two, "name", ui::SortGesture::Extend, 8).chain == + ui::SortChain{{"name", Descending}, {"mass", Descending}}); + CHECK(ui::applySortGesture(two, "mass", ui::SortGesture::Remove, 8).chain == ui::SortChain{{"name", Ascending}}); + CHECK(ui::applySortGesture(two, "site", ui::SortGesture::Descending, 8).chain == ui::SortChain{{"site", Descending}}); +} + +// Mutation: the bound checked before the "already in the chain" case (the flip at the bound is refused). +TEST_CASE("sort gesture: at the bound a new key is refused and a key in the chain still flips", "[ui][table][config]") { + using table::SortDirection::Ascending; using table::SortDirection::Descending; + ui::SortChain const full{{"a", Ascending}, {"b", Ascending}}; + ui::SortChange const added = ui::applySortGesture(full, "c", ui::SortGesture::Extend, 2); + CHECK(added.chain == full); + CHECK(added.refusal == "A table sorts by at most 2 columns"); + CHECK(ui::applySortGesture(full, "c", ui::SortGesture::Add, 2).refusal == "A table sorts by at most 2 columns"); + ui::SortChange const flipped = ui::applySortGesture(full, "b", ui::SortGesture::Extend, 2); + CHECK(flipped.chain == ui::SortChain{{"a", Ascending}, {"b", Descending}}); + CHECK_FALSE(flipped.refusal); +} + +// Mutation: applyLayoutGesture ignoring `locked`. +TEST_CASE("layout gesture: moves, hides, pins and resets, refusing a locked column and the last visible one", + "[ui][table][config]") { + table::ColumnLayout layout{{"id", "name", "mass", "site"}}; + std::vector const columns{{"id", "ID", true}, {"name", "Name"}, {"mass", "Mass"}, {"site", "Site"}}; + CHECK(ui::applyLayoutGesture(layout, columns, ui::Configure::All, ui::MoveColumn{"mass", -1}).changed); + CHECK(std::ranges::equal(layout.order(), std::vector{"id", "mass", "name", "site"})); + CHECK(ui::applyLayoutGesture(layout, columns, ui::Configure::All, ui::MoveColumn{"id", 1}).refusal == "ID is locked"); + CHECK(ui::applyLayoutGesture(layout, columns, ui::Configure::All, ui::PinColumn{"name"}).changed); + CHECK(layout.pinned() == 1); + CHECK(layout.visible().front() == "name"); + CHECK(ui::applyLayoutGesture(layout, columns, ui::Configure::All, ui::ResizeColumn{"mass", 14}).changed); + CHECK(layout.widths().at("mass") == 14); + for (std::string const id : {"name", "mass", "site"}) { + CHECK(ui::applyLayoutGesture(layout, columns, ui::Configure::All, ui::HideColumn{id}).changed); + } + CHECK(layout.visible() == std::vector{"id"}); + CHECK(ui::applyLayoutGesture(layout, columns, ui::Configure::All, ui::HideColumn{"id"}).refusal == + "ID is locked"); + table::ColumnLayout lone{{"a", "b"}}; + std::vector const ab{{"a", "A"}, {"b", "B"}}; + CHECK(ui::applyLayoutGesture(lone, ab, ui::Configure::All, ui::HideColumn{"a"}).changed); + CHECK(ui::applyLayoutGesture(lone, ab, ui::Configure::All, ui::HideColumn{"b"}).refusal == + "At least one column stays visible"); + CHECK(ui::applyLayoutGesture(lone, ab, ui::Configure::Hide, ui::MoveColumn{"b", -1}).refusal == + "This table's columns cannot be moved"); + CHECK(ui::applyLayoutGesture(layout, columns, ui::Configure::All, ui::ResetColumns{}).changed); + CHECK(std::ranges::equal(layout.order(), std::vector{"id", "name", "mass", "site"})); + CHECK(layout.pinned() == 0); + CHECK(layout.widths().empty()); +} + +// Mutation: formGroup accepting a column already in a user-formed group. +TEST_CASE("column layout: the user forms and removes groups and sets display units", "[table][columns]") { + table::ColumnLayout layout{{"companyA", "companyB", "companyC", "weight"}}; + auto const id = layout.formGroup("Company", {"companyA", "companyB"}); + REQUIRE(id == "g1"); + CHECK_FALSE(layout.formGroup("Again", {"companyB", "companyC"})); + CHECK_FALSE(layout.formGroup("One", {"companyC"})); + CHECK_FALSE(layout.formGroup("Ghost", {"companyC", "ghost"})); + CHECK(layout.formGroup("Pair", {"companyC", "weight"}) == "g2"); + CHECK(layout.removeGroup("g2")); + CHECK(layout.setUnit("weight", "mass", "g")); + CHECK_FALSE(layout.setUnit("ghost", "mass", "g")); + table::ColumnLayoutValue const value = layout.value(); + REQUIRE(value.groups.size() == 1); + CHECK(value.groups.at(0).columns == std::vector{"companyA", "companyB"}); + CHECK(value.units == std::map>{{"weight", {{"mass", "g"}}}}); + CHECK(layout.setUnit("weight", "mass", std::nullopt)); + CHECK(layout.units().empty()); +} + +// Mutation: planValueFilter always sending the side the operations reached. +TEST_CASE("value filter: the smaller side is sent, and both sides over the bound disable the list", "[ui][table][config]") { + using Side = ui::ValueFilterPlan::Side; + auto const covering = [](int count, bool ticked) { + std::map covered; + for (int i = 0; i < count; ++i) { covered.emplace("v" + std::to_string(i), ticked); } + return covered; + }; + auto const one = ui::planValueFilter(50'000, ui::ResolvedTicks{.ticked = true, .covered = {{"v00007", false}}}, 10'000); + CHECK(one.side == Side::Exclude); + CHECK(one.members == 1); + CHECK_FALSE(one.needsComplement); + CHECK(ui::planValueFilter(25'000, ui::ResolvedTicks{.ticked = true}, 10'000).side == Side::All); + CHECK(ui::planValueFilter(25'000, ui::ResolvedTicks{.ticked = false, .covered = covering(12'000, true)}, 10'000).side == + Side::Disabled); + auto const complement = ui::planValueFilter(25'000, ui::ResolvedTicks{.ticked = true, .covered = covering(20'000, false)}, 10'000); + CHECK(complement.side == Side::Include); + CHECK(complement.members == 5'000); + CHECK(complement.needsComplement); + CHECK(ui::planValueFilter(3, ui::ResolvedTicks{.ticked = false, .blanks = false}, 10'000).side == Side::Nothing); + // Mutation: the tie decided as Include (`T <= U`): one of two values unticked sends the other as an include. + auto const tie = ui::planValueFilter(2, ui::ResolvedTicks{.ticked = true, .covered = {{"Open", false}}, .blanks = true}, 10'000); + CHECK(tie.side == Side::Exclude); + CHECK(tie.members == 1); + // Mutation: an empty `oneOf` written beside `isEmpty` when only "(Blanks)" is ticked. + auto const blanksOnly = ui::planValueFilter(2, ui::ResolvedTicks{.ticked = false, .blanks = true}, 10'000); + CHECK(blanksOnly.side == Side::Include); + CHECK(blanksOnly.members == 0); + auto const onlyBlanks = ui::valueFilter(Side::Include, {}, true); + REQUIRE(onlyBlanks); + REQUIRE(onlyBlanks->include.size() == 1); + CHECK(onlyBlanks->include.at(0).isEmpty == true); + CHECK_FALSE(ui::valueFilter(Side::Exclude, {}, std::nullopt)); + auto const include = ui::valueFilter(Side::Include, {"F", "S"}, true); + REQUIRE(include); + CHECK(include->combine == table::Combine::Any); + REQUIRE(include->include.size() == 2); + CHECK(include->include.at(0).oneOf == std::vector{"F", "S"}); + CHECK(include->include.at(1).isEmpty == true); + auto const exclude = ui::valueFilter(Side::Exclude, {"X"}, false); + REQUIRE(exclude); + REQUIRE(exclude->exclude.size() == 2); + CHECK(exclude->exclude.at(1).isEmpty == true); + auto const ranges = ui::valueFilter(Side::Include, {"2026-03-01..2026-03-31", "2026-05-14..2026-05-14"}, std::nullopt, + ui::ValueForm::Ranges); + REQUIRE(ranges); + REQUIRE(ranges->include.size() == 2); + CHECK(ranges->include.at(0).between == std::array{"2026-03-01", "2026-03-31"}); +} + +// Mutation: resolveTicks applying the operations in reverse order. +TEST_CASE("value ticks: operations under searches resolve in order, the last one winning", "[ui][table][config]") { + std::map> const shows{{"ab", {"ab1", "xab"}}, {"x", {"xab", "xy"}}}; + auto const under = [&](std::string const& search) { return shows.at(search); }; + ui::ValueTicks const ticks{.ticked = true, + .ops = {{.search = "", .operand = std::nullopt, .ticked = false}, + {.search = "ab", .operand = std::nullopt, .ticked = true}, + {.search = "x", .operand = std::nullopt, .ticked = false}, + {.search = "", .operand = "xab", .ticked = true}}}; + ui::ResolvedTicks const resolved = ui::resolveTicks(ticks, under); + CHECK_FALSE(resolved.ticked); + CHECK(resolved.covered == std::map{{"ab1", true}, {"xab", true}, {"xy", false}}); +} + +// Mutation: classifyFilter reading a Custom column's lone isEmpty as "(Blanks)". +TEST_CASE("filter parts: a column's filter is values or conditions, never both", "[ui][table][config]") { + using table::ColumnKind; + auto const entry = [](auto set) { table::FilterEntry e; set(e); return e; }; + table::ColumnFilter values{.combine = table::Combine::Any, + .include = {entry([](auto& e) { e.oneOf = std::vector{"F"}; }), + entry([](auto& e) { e.isEmpty = true; })}}; + CHECK(ui::classifyFilter(values, ColumnKind::Text) == ui::FilterPart::Values); + table::ColumnFilter blanks{.combine = table::Combine::Any, .include = {entry([](auto& e) { e.isEmpty = true; })}}; + CHECK(ui::classifyFilter(blanks, ColumnKind::Text) == ui::FilterPart::Values); + CHECK(ui::classifyFilter(blanks, ColumnKind::Custom) == ui::FilterPart::Conditions); + table::ColumnFilter conditions{.combine = table::Combine::All, + .include = {entry([](auto& e) { e.gt = "2"; }), entry([](auto& e) { e.lt = "5"; })}}; + CHECK(ui::classifyFilter(conditions, ColumnKind::Integer) == ui::FilterPart::Conditions); + CHECK(ui::classifyFilter({}, ColumnKind::Integer) == ui::FilterPart::None); +} + +// Mutation: canonicalOperand passing typed text through unchanged. +TEST_CASE("typed operands: numbers and measures reach the wire with a point and a unit id", "[ui][table][config]") { + ui::LocaleFacts const de = ui::localeFacts("de"); + CHECK(ui::canonicalOperand("1.234,5", table::ColumnKind::Decimal, de) == "1234.5"); + CHECK(ui::canonicalOperand("12,5", table::ColumnKind::Integer, de) == std::nullopt); + CHECK(ui::canonicalOperand("0,3 kg", table::ColumnKind::Measure, de, massUnits()) == "0.3 kg"); + CHECK(ui::canonicalOperand("250", table::ColumnKind::Measure, de, massUnits(), "g") == "250 g"); + CHECK(ui::canonicalOperand("abc", table::ColumnKind::Text, de) == "abc"); +} + +// Mutation: Together built as one oneOf entry (the row F, F, X would pass). +TEST_CASE("group filter from ticks: the match line chooses the quantifier, together takes one eq per value", + "[ui][table][config]") { + auto const atLeast = ui::groupValueFilter("company", 3, {"F", "S"}, std::nullopt, ui::GroupMatch::AtLeast, 2); + REQUIRE(atLeast); + CHECK(atLeast->match.kind == table::ColumnCount::Kind::AtLeast); + CHECK(atLeast->match.n == 2); + CHECK(atLeast->include.at(0).oneOf == std::vector{"F", "S"}); + auto const together = ui::groupValueFilter("company", 3, {"F", "S"}, std::nullopt, ui::GroupMatch::Together, 0); + REQUIRE(together); + CHECK(together->mode == table::GroupMode::Together); + REQUIRE(together->include.size() == 2); + CHECK(together->include.at(0).eq == "F"); + CHECK(together->include.at(1).eq == "S"); + CHECK_FALSE(ui::groupValueFilter("company", 3, {"F"}, std::nullopt, ui::GroupMatch::Together, 0)); + CHECK_FALSE(ui::groupValueFilter("company", 3, {"F", "S", "T", "U"}, std::nullopt, ui::GroupMatch::Together, 0)); + auto const blanks = ui::groupValueFilter("company", 3, {"F"}, true, ui::GroupMatch::AnyColumn, 0); + REQUIRE(blanks); + CHECK(blanks->include.at(1).isEmpty == true); +} + +// Mutation: conditionOps returning the numeric list for every kind. +TEST_CASE("conditions follow the column's kind", "[ui][table][config]") { + using enum ui::ConditionOp; + CHECK(ui::conditionOps(table::ColumnKind::Text) == + std::vector{Equals, NotEquals, Contains, BeginsWith, EndsWith}); + auto const numeric = std::vector{Equals, NotEquals, Less, LessOrEqual, Greater, GreaterOrEqual, Between}; + for (auto const kind : {table::ColumnKind::Integer, table::ColumnKind::Key, table::ColumnKind::Decimal, + table::ColumnKind::Quantity, table::ColumnKind::Number, table::ColumnKind::Measure, + table::ColumnKind::Date, table::ColumnKind::DateTime}) { + CHECK(ui::conditionOps(kind) == numeric); + } + CHECK(ui::conditionOps(table::ColumnKind::Bool).empty()); + CHECK(ui::conditionOps(table::ColumnKind::Custom) == std::vector{IsEmpty, IsNotEmpty}); + CHECK(ui::conditionLabel(NotEquals, table::ColumnKind::Text) == "does not equal"); + CHECK(ui::conditionLabel(NotEquals, table::ColumnKind::Integer) == "≠"); + table::FilterEntry const between = ui::conditionEntry(Between, "1", "5", false); + CHECK(between.between == std::array{"1", "5"}); + CHECK(ui::conditionEntry(Contains, "ab", {}, true).caseSensitive == true); +} + +// Mutation: headerMenu leaving "Add to sort" enabled for a column already in the chain. +TEST_CASE("header menu: entries, order and enablement", "[ui][table][config]") { + ui::HeaderMenuInput const input{ + .column = {"name", "Name"}, .sortable = true, .filterable = true, .sortPlace = 0, .chainSize = 1, + .maxSortKeys = 8, .visibleIndex = 1, .visibleCount = 3, .pinned = 0, .dimensions = {}, + .groups = {{"company", "Company", 3}}, .allowed = ui::Configure::All}; + std::vector const entries = ui::menuEntries(ui::headerMenu(input)); + std::vector labels; + for (ui::MenuEntry const& entry : entries) { labels.push_back(entry.separator ? "-" : entry.label); } + CHECK(labels == std::vector{"Sort ascending", "Sort descending", "Add to sort", "Remove from sort", "-", + "Filter…", "Filter Company, 3 columns…", "-", "Move left", "Move right", + "Pin column", "Hide column"}); + CHECK_FALSE(entries.at(2).enabled); + CHECK(entries.at(3).enabled); + CHECK(entries.at(8).keys == "Ctrl+Shift+Left"); + ui::HeaderMenuInput locked = input; + locked.column.locked = true; + std::vector const lockedEntries = ui::menuEntries(ui::headerMenu(locked)); + CHECK_FALSE(lockedEntries.at(8).enabled); + CHECK_FALSE(lockedEntries.at(11).enabled); + ui::HeaderMenuInput hideOnly = input; + hideOnly.allowed = ui::Configure::Hide; + CHECK(ui::menuEntries(ui::headerMenu(hideOnly)).back().label == "Hide column"); + CHECK(ui::menuEntries(ui::headerMenu(hideOnly)).size() == 9); + // Mutation: the Display unit submenu drawn with no check on the chosen unit. + ui::HeaderMenuInput measure = input; + measure.column = {"weight", "Weight", false, table::ColumnKind::Measure}; + measure.dimensions = {{.dimension = "mass", .units = {"g", "kg"}, .chosen = "g"}}; + std::vector const measureMenu = ui::headerMenu(measure); + REQUIRE(measureMenu.back().entry.label == "Display unit"); + REQUIRE(measureMenu.back().items.size() == 2); + CHECK(measureMenu.back().items.at(0).entry.label == "mass: g"); + CHECK(measureMenu.back().items.at(0).entry.checked == true); + CHECK(measureMenu.back().items.at(1).entry.checked == false); + CHECK(measureMenu.back().items.at(1).command == ui::MenuCommand::DisplayUnit); + CHECK(measureMenu.back().items.at(1).argument == "mass\x1Fkg"); + std::vector const table = ui::menuEntries(ui::tableMenu({.anyFilter = false, .groups = {}, .allowed = ui::Configure::All})); + std::vector tableLabels; + for (ui::MenuEntry const& entry : table) { tableLabels.push_back(entry.separator ? "-" : entry.label); } + CHECK(tableLabels == std::vector{"Columns…", "Sort…", "Clear all filters", "Reset columns", "-", "Copy", + "Copy with headers"}); + CHECK_FALSE(table.at(2).enabled); + CHECK(table.at(5).keys == "Ctrl+C"); +} + +// Mutation: copyText replacing "\r\n" with two spaces. +TEST_CASE("copy text: tabs and line breaks become one space; unloaded cells are empty and counted", "[ui][table][config]") { + std::vector const labels{"Na\tme", "N"}; + std::vector>> const rows{{"a\tb\r\nc", "1"}, {std::nullopt, "x\ry\nz"}}; + ui::CopiedText const plain = ui::copyText({}, rows); + CHECK(plain.text == "a b c\t1\n\tx y z"); + CHECK(plain.unloaded == 1); + CHECK(ui::copyText(labels, rows).text == "Na me\tN\na b c\t1\n\tx y z"); +} + +// Mutations: groupedCount writing the digits ungrouped; `copied` using the plural for one row or one cell. +TEST_CASE("status copy: counts are grouped and messages are exact", "[ui][table][config]") { + CHECK(ui::tableText::tooManyDates() == "Too many dates to list; filter with a condition"); + CHECK(ui::groupedCount(999) == "999"); + CHECK(ui::groupedCount(10'000) == "10,000"); + CHECK(ui::groupedCount(-1'234'567) == "-1,234,567"); + CHECK(ui::groupedCount(10'000, ".") == "10.000"); + CHECK(ui::tableText::sortBound(32) == "A table sorts by at most 32 columns"); + CHECK(ui::tableText::rangeBound(10'000) == "A range selects at most 10,000 rows"); + CHECK(ui::tableText::copyBound(10'000) == "A copy holds at most 10,000 rows"); + CHECK(ui::tableText::copied(200, 12) == "Copied 200 rows, 12 cells were not loaded"); + CHECK(ui::tableText::copied(1, 1) == "Copied 1 row, 1 cell was not loaded"); + CHECK(ui::tableText::copied(3, 0) == "Copied 3 rows"); + CHECK(ui::tableText::unreadable(1) == "1 cell could not be read"); +} +``` + +(`massUnits()` is a file-local helper returning the `UnitInfo`s `kg` and `g` of dimension mass, as Part C's measure tests build them; `ui::LocaleFacts` and `ui::localeFacts` are the existing locale table's.) + +- [ ] **Step 2: Run them to see them fail** + +Run: `cmake --build --preset cl-debug --target morph_tests morph_table_tests` +Expected: compile errors naming `morph/ui/table_config.hpp` (missing) and `ColumnLayout::formGroup`. + +- [ ] **Step 3: Implement** the interfaces above in `include/morph/ui/table_config.hpp` and `include/morph/table/engine.hpp`. + - `groupedCount` groups by three with `separator`; the lowering passes the session's numeric grouping separator, as Part D's `countsText` does; the status copy is English, as the framework's other defaults (`Select all`) are. + - `applySortGesture`: `Click` makes `{column, Descending}` when `chain[0]` is `{column, Ascending}`, else `{column, Ascending}`; `Ascending`/`Descending` make that one key; `Extend` flips a key already in the chain in place, else appends ascending; `Add` appends only a column not in the chain; `Remove` erases it. The "in the chain" case is decided before the bound; a new key past `maxSortKeys` returns the chain unchanged with `tableText::sortBound(maxSortKeys)`. + - The rule that pinned columns take at most half the table's width is the renderer's (Task 10), for display only; no gesture here changes the stored count for it. + - `applyLayoutGesture`: a gesture on a locked column refuses with `tableText::locked(label)` before anything else, a gesture the `allowed` set lacks with `notConfigurable` (`Reset` is allowed while any capability is); `MoveColumn` moves among visible columns, `PinColumn` places the column right after the last pinned visible column and adds one, `UnpinColumn` places it right after the pinned ones less one; `ResetColumns` restores the declared order and `shown`, `pinned = 0`, no widths; a hide that would leave none visible refuses with `lastVisible()`. + - `planValueFilter`: with D = `distinct`, C = `covered`, T = `(ticked ? D − |C| : 0) + |{c in C : c ticked}|`, U = D − T: `All` when T = D and `blanks` is not `false`; `Nothing` when T = 0 and `blanks` is not `true`; otherwise `Include` when T < U, else `Exclude` (a tie sends the unticked side, so unticking one of two values is one excluded value), with `members = min(T, U)`, `Disabled` when that exceeds `maxSetValues`, and `needsComplement` when the side's members include values outside C (then the menu pages every value at `maxLimit` to name them). + - `valueFilter`: `Set` → `Include`: `include = {oneOf members} + {isEmpty} if blanks == true`, `combine = Any`; `Exclude`: `exclude = {oneOf members} + {isEmpty} if blanks == false`. On both sides the `oneOf` entry is left out when `members` is empty (ticking only "(Blanks)" is `include = [{isEmpty}]`), and a side left with no entry at all is `nullopt`. `Ranges` → the same with one `between` entry per member, its two ends the member split at `..`. `All`, `Nothing`, `Disabled` → `nullopt`. + - `canonicalOperand` reads the locale's decimal and grouping separators from `LocaleFacts` (`ui::localeFacts`), never assuming a point. + - `groupValueFilter`: `AnyColumn`, `EveryColumn`, `AtLeast n`, `Exactly n` → one `oneOf` entry (plus `isEmpty` under `AnyColumn` when `blanks == true`) with `match` `Any`, `All`, `AtLeast`, `Exactly`; `Together` → one `eq` per ticked value, `mode = Together`, refused unless 2 ≤ ticked ≤ `groupColumns`. + - Every public symbol gets complete Doxygen. + +- [ ] **Step 4: Run them to see them pass** + +Run: `cmake --build --preset cl-debug --target morph_tests morph_table_tests && ctest --test-dir build/cl-debug -R "sort gesture|layout gesture|column layout|value filter|group filter from ticks|conditions follow|header menu|copy text|status copy" --output-on-failure` +Expected: all pass; then the whole of `morph_table_tests` and the `[ui]` cases of `morph_tests` pass. + +- [ ] **Step 5: Mutations, docs, commit.** Apply each mutation named above, see its case fail, revert; paste the failing lines into the commit body. Update `docs/spec/table/engine.md` ("`ColumnLayout`": user-formed groups and display units, and that `apply` and `rebuild` fit them). Run the docs build. Commit: `feat(ui): table gestures, menus and value filters as functions`. + +### Task 12b: The backend contract for configuring, in every backend + +**Files:** +- Modify: `include/morph/ui/view.hpp:364-374` (`TableSort`), `:1217-1283` (`TableColumn`, `Table`), `:2026-2049` (`TableOptions`); `include/morph/ui/backend.hpp:764-879` (`TableWidget`), `:1293-1510` (`IViewBackend::copyText`); `include/morph/ui/mount.hpp:1622-1645` (binding the new members); `include/morph/ui/testing/recording_backend.hpp:290-298` (`formatSort`), `:1986-2240` (`FakeTable`), `:3015-3040` (drivers); `include/morph/ui/testing/backend_conformance.hpp:60-225` (probe operations) and its cases +- Modify: `src/qt_quick/kinds.hpp:614-695`, `src/qt_quick/table.cpp`, `src/qt_quick/qml/MorphTable.qml`, `src/qt_quick/qml/MorphMenu.qml` (as the header and table menus' popup), `src/qt_quick/backend.cpp` (`copyText` through `QGuiApplication::clipboard()`); `src/tui/table_widget.hpp`, `src/tui/table_widget.cpp` (and the TUI backend's `copyText`: OSC 52) +- Modify: `include/morph/forms/engine/collection_view.hpp:143-227` (the `sort` and `onSort` members it leaves unset keep compiling) +- Modify, so this commit builds and stays green on its own: `src/ui/interpreter.cpp` (the table lowering's `options.sort` and `options.onSort`, today at `:7655-7673`: `sort` becomes a `std::vector` of the one key it holds, or empty, and `onSort` takes `(std::size_t, HeaderClick)` and ignores the click — the chain is 12c's); `tests/test_ui_table_row_span.cpp:52,79,170-198` (its `Signal>` becomes a `Signal>`, `std::nullopt` an empty vector); the existing `setSort(ui::TableSort{…})` and `setSort(std::nullopt)` calls at `tests/qt_quick/test_qt_quick_table.cpp:1148,1163` and `tests/tui/test_tui_table.cpp:910` (a one-key vector, an empty one); `tests/test_ui_conformance.cpp` (`REQUIRE(cases.size() == 56)` becomes `64`, and the faults below) +- Test: `tests/test_ui_conformance.cpp`, `tests/test_ui_table_config.cpp` (the `sort marks` case), `tests/qt_quick/test_qt_quick_conformance.cpp`, `tests/qt_quick/test_qt_quick_table.cpp`, `tests/tui/test_tui_conformance.cpp`, `tests/tui/test_tui_table.cpp` +- Docs: `docs/spec/ui/backend_contract.md` ("Widgets" table entry, "The probe", "The cases", "RecordingBackend"), `docs/spec/ui/view_tree.md` ("ForEach and Table rows"), `docs/spec/qt_quick/backend.md` (header menus, the table menu button, header drag and resize, the group header), the TUI table's header comment in `src/tui/table_widget.hpp`. + +**Interfaces:** +- Consumes: Part D's `ui::TableColumn::id`, `Table::arrangement` (`TableArrangement`, whose visible places `onColumnMove` positions and `TableColumnGroup::first` count in) and `Table::status`. +- **Column indices (index decision 37).** The `column` argument of every handler, `TableWidget` call, probe operation and `RecordingBackend` driver below is the index into `Table::columns`, which holds every column, hidden ones included, and does not change when the layout does. Only a `position` argument (`onColumnMove`, `moveColumn`) and `TableColumnGroup::first` are visible places of the arrangement. A driver given a hidden column's index throws `std::logic_error`: a user cannot reach its header. +- **Parallel structs (index decision 41).** Every member below is added to both `ui::Table` and `TableOptions`, and `ui::table()` copies each across. +- Produces (namespace `morph::ui`): + - `enum class HeaderClick : std::uint8_t { Plain, Shift }` + - `[[nodiscard]] std::string sortMarkText(SortDirection direction, std::size_t place, std::size_t count)` and `[[nodiscard]] std::string sortDescription(SortDirection direction, std::size_t place, std::size_t count)` in `view.hpp` (`place` from 1): `sortMarkText` is `" ▲"`/`" ▼"` when `count == 1`, else `" ▲"`/`" ▼"`; `sortDescription` is exactly `"sorted ascending"`/`"sorted descending"` when `count == 1`, else `"sorted ascending, key of "` (lower case, as table.md "Sort chains" writes it); both backends set the header's accessible description from it and nothing else + - `struct TableColumnGroup { std::string label; std::size_t first = 0; std::size_t count = 0; bool filtered = false; }` + - `ui::TableColumn::filterable` (`bool`, default `false`) + - `ui::Table` and `TableOptions`: `Prop> sort` (replacing `Prop>`, chain order), `std::function onSort` (replacing the one-argument handler), `std::function(std::optional)> menu` and `std::function, std::vector)> onMenu` (no column: the table's menu), `std::function onColumnMove`, `std::function units)> onColumnResize`, `std::function onFilter`, `Prop> filtered`, `Prop> columnGroups`, `std::function onGroupFilter`, `Action onCopy` + - `TableWidget`: `virtual void setSort(std::vector const& chain) = 0;` and `virtual void setOnSort(std::function onSort) = 0;` (replacing both), and with default empty bodies `setMenu(std::function(std::optional)> entries, std::function, std::vector)> onChoose)`, `setOnColumnMove(…)`, `setOnColumnResize(…)`, `setOnFilter(…)`, `setFiltered(std::vector const&)`, `setColumnGroups(std::vector const&)`, `setOnGroupFilter(…)`, `setOnCopy(Action)` (the status line's `setStatus` and `setOnRetry` are Part D's) + - `IViewBackend::copyText(std::string_view text) -> bool` (default `false`: no clipboard) + - `RecordingBackend` drivers: the existing `clickHeader(int table, std::size_t column)` gains a defaulted third parameter, `HeaderClick click = HeaderClick::Plain` (index decision 42), so its callers in `tests/test_ui_interpreter_table.cpp`, `tests/test_ui_conformance.cpp` and `examples/lims_gallery/tests/test_samples.cpp` compile unchanged; `menuOf(int table, std::optional column) -> std::vector`, `chooseMenu(int table, std::optional column, std::vector const& labels)` (labels from the top, resolved to the entry path), `moveColumn(int table, std::size_t column, std::size_t position)`, `resizeColumn(int table, std::size_t column, std::optional units)`, `clickFilter(int table, std::size_t column)`, `clickGroupFilter(int table, std::size_t group)`, `pressCopy(int table)`, `clipboardText() -> std::string` (the last text `copyText` was given; empty before any — index decision 27); properties `sort` (`"0:Ascending,2:Descending"`, `none` when empty), `filtered` (`[0,2]`), `columnGroups` (`[Company:0+3]`, label, first visible place, count) + - `ConformanceProbe`: the existing pure `clickHeader(Widget& table, std::size_t column)` gains the same defaulted `HeaderClick click = HeaderClick::Plain` (one virtual, three parameters; the probes' overrides take the third parameter, the existing cases' calls are unchanged). The operations added here are virtual with default bodies that do nothing and return an empty value, as `descriptionOf` and `boundsOf` are, so the null probe of `tests/test_ui_conformance.cpp` needs no override and fails the new cases by observing nothing; the three real probes (`RecordingProbe` in `tests/test_ui_conformance.cpp`, the Qt Quick probe, the terminal probe) override every one: `headerMenu(Widget& table, std::optional column) -> std::vector`, `chooseHeaderMenuEntry(Widget& table, std::optional column, std::vector const& path)`, `moveColumn(Widget& table, std::size_t column, std::size_t position)`, `headerText(Widget const& table, std::size_t column) -> std::string`, `headerName(Widget const& table, std::size_t column) -> std::string`, `headerDescription(Widget const& table, std::size_t column) -> std::string`, `clipboardText() -> std::string` +- Backend behaviour both backends implement: a header's menu opens on a right click on the header, on `Shift+F10` or the context-menu key with the header focused, and from a `⋯` button at the header row's trailing end for the table's menu (accessible name `Table options`); `Shift`+click, `Shift+Enter` and `Shift+Space` report `HeaderClick::Shift`; `Ctrl+Shift+Left` and `Ctrl+Shift+Right` on a focused header report `onColumnMove(column, position ∓ 1)` among the arrangement's visible columns; on Qt Quick dragging a header onto another reports the move, dragging a header's trailing edge reports `onColumnResize` in units, a double click on the edge reports `nullopt`; a filterable header draws a filter button, filled while `setFiltered` names it; a group header row is drawn over side-by-side group columns with its own filter button; `Ctrl+C` on a focused table reports `onCopy`. The terminal header becomes focusable: `Up` on the first row focuses the header at the sorted column (else the first), `Left`/`Right` move along it, `Enter`/`Space` sort, `Shift+Enter` extends, `Ctrl+Shift+Left/Right` move, `Shift+F10` opens its menu, `Down` returns to the rows; the terminal draws no drag or resize handle. + +- [ ] **Step 1: Write the failing conformance cases** in `include/morph/ui/testing/backend_conformance.hpp`, appended to `conformanceCases()` in this order (the `std::array` becomes `64`, as does the count `tests/test_ui_conformance.cpp` requires), each with its control comment. A control is a `Fault` of `tests/test_ui_conformance.cpp`'s `RecordingProbe`, the repository's way to show that a conformance case fails on a broken backend. This task adds `PlainHeaderClicks` (every header click reported as `Plain`), `FirstSortKeyOnly` (`headerText` and `headerDescription` answer for the chain's first key only), `MenuColumnOffByOne` (`chooseHeaderMenuEntry` chooses on `column + 1`), `MoveTargetIsSource` (`moveColumn` reports the column's own place), `UnnamedFilter` (`headerName` answers the bare label) and `SilentClipboard` (`clipboardText` answers empty), and extends `"ui conformance: the suite flags a backend that breaks the contract"` to assert, per fault, that `failingCases(fault)` contains the case its control stands beside below. The existing `DeadInput` covers the table-menu and `Ctrl+C` cases, whose probe operations go through it: + +```cpp +// Control: report every header click as Plain. +{"table: a Shift-click on a sortable header reports Shift, a plain click Plain", /* mount a Table of columns + {Name sortable, Mass sortable}, onSort recording (column, click); probe.clickHeader(table, 1, HeaderClick::Shift); + probe.clickHeader(table, 0, HeaderClick::Plain); expect {(1, Shift), (0, Plain)} */}, +// Control: draw only the chain's first key. +{"table: a chain of three keys marks every header with its place", /* columns {Name, Mass, Site} all sortable; + sort = {{1, Descending}, {0, Ascending}, {2, Ascending}}: headerText(table, 0) == "Name ▲2", + headerText(table, 1) == "Mass ▼1", headerText(table, 2) == "Site ▲3"; + headerDescription(table, 0) == "sorted ascending, key 2 of 3" (compared whole, lower case); + with sort = {{0, Descending}}: headerText(table, 0) == "Name ▼", headerDescription(table, 0) == "sorted descending", + headerDescription(table, 1) == "" */}, +// Control: pass the clicked header's index plus one to onMenu. +{"table: a header's menu shows its entries and choosing one reports the column and the path", /* menu returns + {Sort ascending, separator, Hide column} for column 1; headerMenu(table, 1) labels == those three; + chooseHeaderMenuEntry(table, 1, {2}) reports (1, {2}) */}, +{"table: the table's menu is the menu with no column", /* chooseHeaderMenuEntry(table, nullopt, {0}) reports (nullopt, {0}) */}, +// Control: report the move's target as the source. +{"table: a column moved by the user reports its column and new place", /* moveColumn(table, 0, 1) reports (0, 1) */}, +// Control: name a filtered header as an unfiltered one. +{"table: a filtered column's header is named so", /* columns filterable; filtered = {0}: headerName(table, 0) == + "Name, filtered", headerName(table, 1) == "Mass" */}, +{"table: Ctrl+C on a focused table reports a copy", /* press(table, "Ctrl+C") calls onCopy once */}, +// Control: copyText returning true without writing. +{"backend: copyText puts its text on the clipboard", /* backend().copyText("a\tb") == true; clipboardText() == "a\tb" */}, +``` + +The accessible description is also held by a unit case in `tests/test_ui_table_config.cpp` (it needs no backend): + +```cpp +// Mutation: sortDescription capitalised ("Sorted ascending, …"), or the count written as the place. +TEST_CASE("sort marks: the header's mark and accessible description", "[ui][table][config]") { + CHECK(ui::sortDescription(ui::SortDirection::Ascending, 2, 3) == "sorted ascending, key 2 of 3"); + CHECK(ui::sortDescription(ui::SortDirection::Descending, 1, 1) == "sorted descending"); + CHECK(ui::sortMarkText(ui::SortDirection::Ascending, 2, 3) == " ▲2"); + CHECK(ui::sortMarkText(ui::SortDirection::Descending, 1, 1) == " ▼"); +} +``` + +Write each case's body with the assertions in its comment. Add to `tests/qt_quick/test_qt_quick_table.cpp`: + +```cpp +// Control: report the edge drag's width in pixels instead of units. +TEST_CASE("qt_quick table: dragging a header's trailing edge reports units, a double click on it none", "[qt_quick][table]") +// header 0 fixed(12); drag its trailing edge right by 4 units (theme unit width × 4): onColumnResize == (0, 16); +// double-click the edge: onColumnResize == (0, nullopt). +// Control: ignore a drag that ends on another header. +TEST_CASE("qt_quick table: dragging a header onto another reports the move", "[qt_quick][table]") +// drag header 0 onto header 2 of three: onColumnMove == (0, 2). +``` + +and to `tests/tui/test_tui_table.cpp`: + +```cpp +// Control: leave the header unfocusable. +TEST_CASE("tui table: Up on the first row focuses the header; Left, Right, Shift+Enter and Ctrl+Shift+Right act on it", "[tui]") +// three sortable columns, sort {{1, Ascending}}: Up on row 0 focuses header 1; Right focuses header 2; +// Shift+Enter reports (2, Shift); Ctrl+Shift+Left reports onColumnMove(2, 1); Down returns to row 0. +``` + +- [ ] **Step 2: Run them to see them fail** + +Run: `cmake --build --preset cl-debug --target morph_tests` then `cmake --build build/cl-qt-debug --target morph_qt_quick_tests morph_tui_tests` +Expected: compile errors for `HeaderClick`, `TableColumnGroup`, the probe operations and the new `Fault` enumerators. + +- [ ] **Step 3: Implement** the interfaces and behaviour above in every listed file. `mount.hpp` binds `sort`, `filtered` and `columnGroups` as it binds `sort` today, wires each handler with `event(...)`, calls `setMenu` only when `menu` is set and `setOnColumnResize` only when `onColumnResize` is set, and keeps calling `setSort` only for a table with a sortable column. The row-span rule reads the chain where it read the optional: `spans.sorted = sortable && sortValue == nullptr && !spec.sort.constant().empty()` (`mount.hpp:1646` tests `has_value()` today), and inside the rows Effect a bound chain counts as sorted while it is not empty. `copyText` writes `QGuiApplication::clipboard()` on Qt Quick, an OSC 52 sequence on the terminal, and a record on `RecordingBackend`; each backend's conformance probe reads back what its `copyText` wrote. + +- [ ] **Step 4: Run them to see them pass** + +Run: `ctest --test-dir build/cl-debug -R "conformance|sort marks" --output-on-failure`; `ctest --test-dir build/cl-qt-debug -R "qt_quick table|tui table|conformance" --output-on-failure` +Expected: all pass, the existing table cases included. + +- [ ] **Step 5: Mutations, docs, commit.** Run each control; paste the failures. Update the docs listed. Run the docs build. Commit: `feat(ui): header menus, sort chains, column moves and the status line in every backend`. + +### Task 12c: Lowering sort chains, the layout, the menus and the status line's messages + +**Files:** +- Modify: `src/ui/document.cpp:292-334` (keys), `:3209-3290` (load checks); `src/ui/interpreter.cpp` (the table lowering Part D built: its `sort`, `onSort`, columns, element values and `TableStatus::message`), `include/morph/ui/interpreter.hpp:371-395` (`SessionOptions::maxCopyRows`) +- Test: `tests/test_ui_table_model.cpp`, `tests/test_ui_document.cpp`, `tests/bench_interpreter.cpp`, `tests/ui_table_support.hpp` (the helpers and documents of Step 1) +- Docs: `docs/spec/ui/document.md` (the `table` row: `layout`, `onLayoutChange`, `configurable`, `onFiltersChange`, a column's `locked` and `filterable`; element values `layout`, `visibleColumns`, `hiddenCount`), `docs/spec/ui/interpreter.md` (the lowering's menus and messages), `docs/spec/table/table.md` (D7 figure) + +**Interfaces:** +- Consumes: 12a, 12b; Part D's `TableRows`, `TableStatus`, the state store's load and save, `Table::arrangement`, the lowering of both table kinds, and Task 9d's message channel `ScreenCore::tableMessage(ElementState&, std::string)` with its `kStatusMessageHold` and its `status: false` routing (index decision 11). Every refusal this part makes is posted through it; this part adds no second channel. +- Produces: + - document keys on `table`: `layout` (Expr; bound, it is controlled), `onLayoutChange` (Commands, `event` the new layout), `configurable` (a literal `true`, `false` or a list of `"reorder"`, `"hide"`, `"pin"`, `"resize"`; anything else is refused at load), `onFiltersChange` (Commands, `event` the new `filters`); on a column part: `locked` (Flag), `filterable` (a literal boolean, default `true`; a column without `id` is never filterable) + - element values `layout` (the stored shape), `visibleColumns` (ids in order), `hiddenCount` + - `SessionOptions::maxCopyRows = 10'000` (used by 12f) + - the clearing half of the message rule for the gestures this part adds: each one the lowering receives (a header click, a menu choice, a column move or resize, a filter button, a copy) calls `tableMessage(table, "")` before it acts, so the user's next gesture on the table clears a message; a refusal it then makes posts its own +- The lowering's rules: `onSort(column, click)` maps `Plain` to `SortGesture::Click` and `Shift` to `Extend`, applies `applySortGesture` with the table's bound (on a model-backed table `description.capabilities.maxSortKeys`, which Task 16's `servedDescription` fills from the server's `limits`; on a `rows` table the node's literal `maxSortKeys`, which Task 16's load check already accepts as an integer 1 to 32; else 8), and on success calls `TableRows::setSort`, sets the held `sort` (when not bound) and runs `onSortChange`; a refusal goes to `tableMessage`. Menu commands map to the same gestures and to 12d, 12e and 12f's openers; `menu` and `onMenu` are set unless `configurable` is `false`. A layout change updates `Table::arrangement`, calls `TableRows::visible` with the new visible columns, sets the held `layout` (when not bound), runs `onLayoutChange` and marks the state unsaved; the stored state's `layout` member is applied before the first rows, as `sort` and `filters` are, and a bound `layout` is neither applied nor saved. A `rows` table's `TableStatus::shown` holds while its `state` or `message` is not empty (a model-backed table's is always shown, Part D); a literal `status: true` shows it always. Every refusal is shown (invariant 31). + + +- **Carried from Task 16** (its server half and the document key landed before this lowering existed; this task owns the client half): + - The bound above is read by the lowering: Task 16 left `maxSortKeys` checked at load and read by nothing. When this lands, `docs/spec/ui/document.md`'s `maxSortKeys` entry changes from "checked at load; it takes effect when the table's sort gestures are lowered" to the bound the header and menu gestures are held to. + - The test, verbatim from Task 16's brief, in `tests/test_ui_table_model.cpp`: + +```cpp +// Mutation: the client holding 8 whatever the description says. +TEST_CASE("sort chains: a table whose limits set 32 accepts 32 keys from the header and refuses the 33rd", "[ui][table][config]") +// kConfigModelTable over samplesDescription(40) whose capabilities.maxSortKeys is 32: Shift-click 33 sortable headers: t.sort +// has 32 keys, the last page request's sort has 32 keys, status message "A table sorts by at most 32 columns". +// A rows table with "maxSortKeys": 12 over 13 sortable columns: 12 keys, the 13th refused with "…at most 12 columns". +``` + - Run the mutation "the client holding 8 whatever the description says" (the lowering passing 8 on both kinds) once and record its failing output in this task's commit, as the spec's Tests row "A raised sort bound" names it. + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_model.cpp` (tag `[ui][table][config]`). Every test of this part runs on `ui::testing::TableHarness` (9d, index decision 42) and mounts a whole document. + +Helpers, added to `tests/ui_table_support.hpp` by this task (index decisions 20 and 42): free functions over `ui::testing::TableHarness&` that call 12b's `RecordingBackend` driver of the same name on `h.backend` and then `h.settle()` — `menuOf(h, table, column) -> std::vector`, `chooseMenu(h, table, column, labels)`, `moveColumn(h, table, column, position)`, `resizeColumn(h, table, column, units)`, `clickFilter(h, table, column)`, `clickGroupFilter(h, table, group)`, `pressCopy(h, table)`, `clipboardText(h) -> std::string`; `table` is the widget id, `column` an index into `Table::columns` (index decision 37). A header click is `h.backend.clickHeader(table, column, click)`. In the sketches of this part a helper written without `h` (`chooseMenu(table, …)`) is that helper with `h` first, `` in angle brackets (``) is that column's index, and `t.` is `elementValue(h, "t", "")`, the element value as JSON text. + +The documents, in `tests/ui_table_support.hpp` (a sketch that says "with …" mounts the document with that one key added to its `table` node or column): + +```cpp +/// A rows table `t`: nine sortable columns c1…c9 labelled C1…C9, three rows keyed by `id`. +inline constexpr std::string_view kNine = R"({ + "vocab": "ui/1", "id": "nine", + "state": { "items": { "init": { "lit": [ + { "id": 1, "c1": 3, "c2": 1, "c3": 2, "c4": 1, "c5": 2, "c6": 3, "c7": 1, "c8": 2, "c9": 3 }, + { "id": 2, "c1": 1, "c2": 2, "c3": 3, "c4": 2, "c5": 3, "c6": 1, "c7": 2, "c8": 3, "c9": 1 }, + { "id": 3, "c1": 2, "c2": 3, "c3": 1, "c4": 3, "c5": 1, "c6": 2, "c7": 3, "c8": 1, "c9": 2 } ] } } }, + "view": { "kind": "table", "id": "t", "rows": { "ref": "items" }, + "columns": [ { "id": "c1", "label": "C1", "sortable": true }, { "id": "c2", "label": "C2", "sortable": true }, + { "id": "c3", "label": "C3", "sortable": true }, { "id": "c4", "label": "C4", "sortable": true }, + { "id": "c5", "label": "C5", "sortable": true }, { "id": "c6", "label": "C6", "sortable": true }, + { "id": "c7", "label": "C7", "sortable": true }, { "id": "c8", "label": "C8", "sortable": true }, + { "id": "c9", "label": "C9", "sortable": true } ] } })"; + +/// The model-backed table `t` over `Table.samples`; its description is what the test replies (`h.replyDescribe`). +inline constexpr std::string_view kConfigModelTable = R"({ + "vocab": "ui/1", "id": "samples", + "models": { "sample": { "type": "Lims_SampleModel" } }, + "view": { "kind": "table", "id": "t", "model": "sample", "table": "samples" } })"; +``` + +The cases: + +```cpp +// Mutation: the lowering mapping HeaderClick::Shift to Click. +TEST_CASE("sort chains: a plain click replaces, Shift adds and flips, a key past the bound is refused", "[ui][table][config]") { + ui::testing::TableHarness h; + auto screen = h.mount(kNine); + int const table = h.backend.all("Table").front(); + h.backend.clickHeader(table, 0, ui::HeaderClick::Plain); + h.backend.clickHeader(table, 1, ui::HeaderClick::Shift); + h.backend.clickHeader(table, 0, ui::HeaderClick::Shift); + h.settle(); + CHECK(elementValue(h, "t", "sort") == R"([{"column":"c1","direction":"desc"},{"column":"c2","direction":"asc"}])"); + CHECK(h.backend.prop(table, "sort") == "0:Descending,1:Ascending"); + for (std::size_t column = 2; column < 9; ++column) { h.backend.clickHeader(table, column, ui::HeaderClick::Shift); } + h.settle(); + CHECK(h.backend.prop(table, "sort") == + "0:Descending,1:Ascending,2:Ascending,3:Ascending,4:Ascending,5:Ascending,6:Ascending,7:Ascending"); + CHECK(statusOf(h).message == "A table sorts by at most 8 columns"); + CHECK(statusOf(h).shown); + h.backend.clickHeader(table, 4, ui::HeaderClick::Plain); + h.settle(); + CHECK(elementValue(h, "t", "sort") == R"([{"column":"c5","direction":"asc"}])"); + CHECK(statusOf(h).message.empty()); + CHECK_FALSE(statusOf(h).shown); +} + +// Mutation: "Add to sort" mapped to SortGesture::Click. +TEST_CASE("sort chains: the header menu builds a chain without a modifier", "[ui][table][config]") +// chooseMenu(table, 0, {"Sort descending"}); chooseMenu(table, 2, {"Add to sort"}); chooseMenu(table, 0, {"Remove from sort"}): +// sort == [{"column":"c3","direction":"asc"}]; onSortChange ran three times. + +// Mutations: the lowering applying a menu gesture without updating `visibleColumns`; a driver's column read as a +// visible place (the resize after the move lands on c1). +TEST_CASE("column layout: hiding, moving, pinning and resetting from the menus change the layout and the visible columns", + "[ui][table][config]") +// chooseMenu(table, 2, {"Hide column"}); chooseMenu(table, 1, {"Move left"}); chooseMenu(table, 1, {"Pin column"}); +// t.visibleColumns == ["c2","c1","c4",…,"c9"]; t.hiddenCount == 1; +// t.layout == {"order":["c2","c1","c3",…],"hidden":["c3"],"pinned":1,"widths":{}}; +// resizeColumn(table, 1, 20) (index 1 is c2 wherever it stands): t.layout.widths == {"c2":20}; +// resizeColumn(table, 1, nullopt): widths == {}; +// chooseMenu(table, nullopt, {"Reset columns"}): t.layout == the declared order, nothing hidden, pinned 0; +// onLayoutChange ran six times with `event` the new layout. + +// Mutation: `configurable` ignored for menus (the hide entry is present). +TEST_CASE("column layout: configurable and locked limit what the user can do, and each refusal is shown", "[ui][table][config]") +// "configurable": ["hide"], c1 "locked": true: menuOf(table, 1) has no "Move left"; moveColumn(table, 1, 0) leaves +// visibleColumns unchanged and status message "This table's columns cannot be moved"; menuOf(table, 0)'s "Hide column" +// is disabled and moveColumn(table, 0, 1) shows "C1 is locked"; "configurable": false: menuOf(table, 1) is empty and no +// "⋯" table menu is offered (menuOf(table, nullopt) empty). + +// Mutation: a header click lowered without `tableMessage(table, "")` (the message outlives the gesture). +// (The hold and the `status: false` routing are 9d's; this case holds them through this part's refusals.) +TEST_CASE("status line: a refusal is shown once, until the next gesture or six seconds", "[ui][table][config]") +// refusal at the bound shows the message; h.advance(5'999ms): still shown; h.advance(1ms): message empty and +// statusOf(h).shown false (a rows table with nothing else to say takes no room); refuse again then +// clickHeader(table, 0, Plain): message gone. "status": false: the harness's record of `notify` calls (9d's +// `h.host.notified`) holds exactly one entry, the text "A table sorts by at most 8 columns" with the role "warning", and +// statusOf(h).shown stays false. + +// Mutation: the lowering applying a stored layout after the first query. +TEST_CASE("persisted layout: a stored layout applies before the first query, a change saves once after the debounce", + "[ui][table][config]") +// TableHarness(store) over a MemoryTableStateStore holding, under the table's key, part "state", +// {"version":1,"layout":{"order":["c2","c1"],"hidden":["c3"],"pinned":0,"widths":{"c2":20}}}: before any rows, +// t.visibleColumns starts with "c2","c1" and lacks "c3"; chooseMenu(table, 0, {"Hide column"}), chooseMenu(table, 3, +// {"Hide column"}) and chooseMenu(table, 4, {"Hide column"}) (c1, c4, c5: indices into Table::columns) inside 500 ms, then +// h.advance(500ms): the store received exactly one save, whose layout's `hidden` is c1, c3, c4 and c5. With `layout` bound to +// state `lay`, the stored layout is neither applied nor saved and the sort part still is. + +// Review Focus 1. Mutation: hiding a column removing it from the query's sort. +TEST_CASE("hiding a sorted and filtered column changes no row", "[ui][table][config]") +// kConfigModelTable over samplesDescription(5), sorted by `name`, filter `{"columns":{"name":{"include":[{"contains":"a"}]}}}`: +// h.replyPage(pageJson(0, 50, 50, cols)) holds rows R; chooseMenu(table, 1, {"Hide column"}): no new Table.samples call +// whose sort or filters differ (any call sent is a column fetch of held rows: lastQuery(h)'s `sort` and `filters` equal +// the previous ones and its `columns` lacks "name"); +// the view's row keys equal R; showing it again restores the header mark ("sort" prop names its index) and `filtered`. + +// Review Focus 2 (message half). Mutation: refusing Shift on a column already in the chain at the bound. +TEST_CASE("sort chains: at the bound a key in the chain still flips, with no message", "[ui][table][config]") +// eight keys held; clickHeader(table, 3, Shift): sort's 4th key flips to desc; status message empty. +``` + +In `tests/test_ui_document.cpp`: + +```cpp +// Mutation: the loader accepting any `configurable` literal. +TEST_CASE("table: configurable, locked and filterable are literals the loader checks", "[ui][document]") +// "configurable": ["reorder","sort"] is refused naming `sort`; "configurable": {"ref":"x"} refused; a column +// "filterable": {"ref":"x"} refused; "locked": true and "filterable": false accepted; "onLayoutChange" and +// "onFiltersChange" take commands. +``` + +In `tests/bench_interpreter.cpp`: + +```cpp +TEST_CASE("interpreter bench: a third sort key on 100,000 rows", "[.benchmark][interpreter]") +// a rows table of 100,000 rows sorted by two keys; BENCHMARK the Shift-click that adds a third key to the settled +// view (D7, budget ≤ 50 ms). +``` + +**From Task 15 (Part F), which landed first.** A companion column (a column of +`table::companionColumns(description)`: a `tone`, `tooltip`, `rowTone` or `rowLock` companion) is never one of the +table's columns, so it is neither visible nor hidden: the layout, `visibleColumns`, `hiddenCount` and the header +menus' hide, show and pin entries never name one. Task 15's lowering already leaves companions out of the table's +columns; the risk is this task's layout, which a description's `shown: false` columns enter as hidden. In Step 1, +**extend the existing case** "table display: companion columns are not arranged" in `tests/test_ui_table_model.cpp` +(do not add a second case of that name, which Catch2 refuses): over `companionDescription()`, whose companions are +`shown: false`, `t.visibleColumns` is `["id","mass","name","count"]`, `t.hiddenCount` is 0, and no entry of any +column's header menu names `massTone`, `massTip` or `lockedBy`. It fails first because neither element value exists +before this task; its mutation is the layout built from every column of the description, which counts the three +companions hidden (`hiddenCount` 3, and the menus offer to show them). + +- [ ] **Step 2: Run them to see them fail** + +Run: `cmake --build --preset cl-debug --target morph_tests && ctest --test-dir build/cl-debug -R "sort chains|column layout|status line|persisted layout|hiding a sorted|configurable, locked|companion columns are not arranged" --output-on-failure` +Expected: FAIL — unknown keys `configurable` and `locked` refused at load, and no `layout` element value. + +- [ ] **Step 3: Implement** the keys, the checks, the element values, `maxCopyRows` and the lowering's rules above, posting every refusal through Part D's `tableMessage`. + +- [ ] **Step 4: Run them to see them pass** + +Run: the Step 2 command, then `ctest --test-dir build/cl-debug -R "ui" --output-on-failure` +Expected: all pass, the existing `test_ui_table.cpp` and `test_ui_interpreter_table.cpp` cases included. + +- [ ] **Step 5: Record D7.** Run: `cmake --preset cl-release && cmake --build --preset cl-release --target morph_tests && build/cl-release/tests/morph_tests.exe "interpreter bench: a third sort key on 100,000 rows"`. Expected: a mean ≤ 50 ms; record it, dated, in table.md's D7 row. + +- [ ] **Step 6: Mutations, docs, commit.** Commit: `feat(ui): configure a table from its header`. + +### Task 12d: The filter menu + +**Files:** +- Create: `include/morph/ui/table_filter_menu.hpp` (the menu's view tree and its state, built by the lowering) +- Modify: `include/morph/ui/table_rows.hpp` (`TableRows::distinctValues`), `src/ui/interpreter.cpp`, `src/ui/document.cpp` (a `rows` table's `groups` parts `{id, label, columns}`), `include/morph/ui/interpreter.hpp` (`SessionOptions::tableFilterDebounce`) +- Test: `tests/test_ui_table_model.cpp`, `tests/net/test_push_tables.cpp` +- Docs: `docs/spec/ui/document.md` (a `rows` table's `groups`), `docs/spec/qt_quick/backend.md` (the filter menu), table.md (B3 and D9 figures) + +**Interfaces:** +- Consumes: 12e's column chooser (`table_columns_group`, `table_group_create`, `table_group_remove_`), through which the user-formed-group case forms and removes its group, so 12e lands first; 12a's tick model, `planValueFilter`, `valueFilter`, `classifyFilter`, `canonicalOperand`, `groupValueFilter`, `conditionOps`, `conditionEntry`; 12b's `onFilter`, `onGroupFilter`, `filtered`, `columnGroups`; Task 8a's `DistinctRequest`/`DistinctValues` and `DateBucket` (a bucket's `text` is its ISO form, `2026`, `2026-03`, `2026-03-14`, and its operand `a..b`, as Part C's tests pin them); Task 8c's `DistinctValue::{dimension, unit}`, `ui::parseMeasure`, `ui::measureOperand`; Part D's `ScreenCore::tableMessage`. +- Produces: + - `TableRows::distinctValues(table::DistinctRequest request) -> async::Completion>` (pure virtual; `EngineRows` answers at once through `Engine::distinctValues`; `WindowRows` sends a query carrying `distinct` through the session's query cache, so reopening a menu sends nothing; `TableCapabilities::distinct == false` → `Unavailable`, and the menu shows conditions only) + - `SessionOptions::tableFilterDebounce = std::chrono::milliseconds{250}` + - the menu, a `ui::Dialog` (test id `table_filter`, title the column's or group's label) the lowering mounts beside the table, with test ids: `table_filter_search` (TextInput), `table_filter_all` (`(Select all)` Checkbox), `table_filter_blanks` (`(Blanks)`, only while `blanks > 0`), `table_filter_value_` (Checkbox, label `{text} ({count})`, in the reply's order, `i` from 0), `table_filter_heading_` (Text, a `Measure` column's dimension heading before its first value), `table_filter_open_` (Button `▸`, a date bucket that opens to its months or days), `table_filter_more` (Button, the next 200), `table_filter_note` (Text: `mayGrow()` while `partial`, `unreadable(invalid)` while `invalid > 0`, `tooManyValues()` after an Apply whose plan is `Disabled`), `table_filter_op_1` / `_2` (Select of `conditionLabel`s), `table_filter_operand_1` / `_2` and `table_filter_second_1` / `_2` (a TextInput, or on a `Date`/`DateTime` column a `DateTimeInput` in `Date`/`DateTime` mode — the date picker; the second only for `between`), `table_filter_case` (Checkbox `match case`, Text columns), `table_filter_combine` (Select `and`/`or`), `table_filter_unit_1` / `_2` (Select of the column's units, `Measure` only), `table_filter_match` and `table_filter_count` (group menus: `in any column`, `in every column`, `in at least N columns`, `in exactly N columns`, `all of them, each in a column`; the last only while 2 to k values are ticked), `table_filter_apply` (Button, disabled while nothing is ticked), `table_filter_clear` (Button `Clear filter`) + - the `Display unit` header submenu (Measure columns) is 12a's (`HeaderMenuInput::dimensions`, entries `{dimension}: {unit}`); the lowering fills `dimensions` from the description's `units` and each `chosen` from `layout.units[column][dimension]`; choosing an entry sets `layout.units[column][dimension]`, and choosing the checked one removes it +- Rules: + - **Values or conditions.** A column's filter is either its values part or its conditions part (12a's `classifyFilter`). Reopening the menu shows the part the stored filter is, the other part empty; editing one part clears the other's draft. A user who wants both writes conditions only. + - **When it applies.** Ticks and "(Select all)" are recorded as `TickOp`s and applied only by Apply, which resolves them (paging each search's values at `maxLimit`), plans the side, and sets the filter; a `Disabled` plan applies nothing and puts `tooManyValues()` in the note. Conditions apply live: an edit of an operator, an operand, the unit, `match case` or `and`/`or` is sent `tableFilterDebounce` after the last such edit, provided every operand canonicalises (`canonicalOperand`) and a `between` has both ends; otherwise nothing is sent and the operand shows its error. Apply on the conditions part sends a pending edit at once. A sent filter calls `TableRows::setFilter`, sets the held `filters` and runs `onFiltersChange`. + - **The values list** asks `DistinctRequest{column, search, offset, limit = 200}`, the search sent `tableFilterDebounce` after the last keystroke; a group menu asks with `group`. A `Measure` column's list draws `table_filter_heading_` before each dimension's first value. + - **Dates.** A `Date`/`DateTime` column's list is a tree: it asks `bucket = Year`; opening a year asks `bucket = Month, search = "-"`; opening a month asks `bucket = Day, search = "--"`, each paged at 200 like any list. Its ticks are a set of buckets, not `TickOp`s, and its filter is include-only (`planValueFilter` is not used), as table.md's "Distinct values" bullet **Dates.** states: + - with no values filter on the column the tree opens with every box unticked and draws no `(Select all)`; with one, the buckets whose range a stored `between` covers are ticked; + - ticking a year or a month covers the buckets under it, whose boxes then show ticked and disabled; + - Apply writes `valueFilter(Side::Include, members, blanks, ValueForm::Ranges)`: one `between` per ticked bucket (a covered child adds none), in ascending order of its first end whatever the order of ticking, `combine = Any`, `isEmpty` beside them when `(Blanks)` is ticked; with no box ticked it clears the column's values filter; + - one column's entries are bounded by `QueryLimits::maxEntries` (32, `query.hpp:112`), which the server's `validate` enforces. Before sending, buckets that touch (the next begins the day, or the second, after the previous ends) are merged into one `between`; a selection still over 32 entries applies nothing and puts `tableText::tooManyDates()` in `table_filter_note`. + The conditions take dates from the picker. + - **Groups.** A declared group's menu pools its values (`DistinctRequest::group`). A user-formed group (a layout group, index decision #26) has no values list: its menu sends no `DistinctRequest`, shows no search, `(Select all)` or value boxes, and offers the conditions of its columns' kind (a user-formed group is of one kind, 12e) and the match line's four quantifiers (`all of them, each in a column` takes ticked values, so it is not offered). Its filter is a `GroupFilter` with `group` empty and `columns` the layout group's columns in group order (Part C's `compileGroup` takes exactly one of `group` and `columns`), `match` from the match line, `combine` from `and`/`or`, `include` the condition entries; that one object is what the held `filters`, the stored state and the query carry. The lowering finds a layout group's filter as the `GroupFilter` whose `columns` equal the group's columns; removing the group (`RemoveGroup`) removes that filter with it. + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_model.cpp`: + +```cpp +// Mutation: the menu counting over the view (the column's own filter applied). +TEST_CASE("filter menu: values are counted over what the other filters leave, and ticks build the smaller side", + "[ui][table][config]") +// rows table `t` over 7 rows, status: Open×3, Closed×2, Held×1, empty×1; site: A×5, B×2; filter on site eq "A" leaves +// Open×2, Closed×2, empty×1 → clickFilter(table, ): table_filter_value_0 label "Closed (2)", _1 "Open (2)", +// no "Held"; table_filter_blanks label "(Blanks)"; untick "Open", Apply: t.filters.columns.status == +// {"combine":"any","exclude":[{"oneOf":["Open"]}],"include":[]} — then reopen: "Open (2)" is listed unticked; +// onFiltersChange ran once; the header's `filtered` prop names the status column. chooseMenu(table, nullopt, +// {"Clear all filters"}): t.filters == {"columns":{},"groups":[]}, `filtered` is empty, onFiltersChange ran twice. + +// Mutation: Apply writing the ticks and the conditions into one entry list. +TEST_CASE("filter menu: values and conditions are exclusive, and reopening shows the stored part", "[ui][table][config]") +// status (Text): tick only "(Blanks)", Apply → include [{"isEmpty":true}]; reopen: table_filter_blanks checked, every +// value unticked, table_filter_op_1 empty. Then choose "contains", operand "pe": after 250 ms t.filters.columns.status == +// {"combine":"any","include":[{"contains":"pe"}],"exclude":[]} and the ticks are gone; reopen shows the condition and +// (Select all) ticked. A Custom column `code` filtered {"include":[{"isEmpty":true}]} reopens with table_filter_op_1 +// "is empty" and no values list. + +// Mutation: the search sent on every keystroke (no debounce). +TEST_CASE("filter menu: a search typed quickly is one distinct request after the pause", "[ui][table][config]") +// kConfigModelTable over samplesDescription(5), first page replied: open the menu on `name` (one Table.samples call with +// `distinct`, replied by hand); type "a","ab","abc" 50 ms apart in table_filter_search; +// h.advance(249ms): no new call; h.advance(1ms): exactly one more, whose body's distinct.search == "abc". (D9 gate) + +// Mutation: the condition sent on every keystroke, or a half-typed between sent. +TEST_CASE("filter menu: a condition applies once after typing pauses, and an incomplete between is not sent", + "[ui][table][config]") +// kConfigModelTable, `name` (Text), op "contains": type ten letters 150 ms apart into table_filter_operand_1: +// h.advance(249ms) after the last: no new page request; h.advance(1ms): exactly one, filtering contains the ten +// letters (B4 gate). c3 (Decimal), op "between", operand_1 "2", no second: h.advance(1s): no request; second "5": one, +// include [{"between":["2","5"]}]; edit operand_1 to "3" and press Apply at once: the request goes without waiting. + +// Mutation: the note line ignoring `partial`. +TEST_CASE("filter menu: a partial list says it may grow and invalid cells are counted under it", "[ui][table][config]") +// kConfigModelTable; reply the distinct request with {"values":[{"text":"x","operand":"x","count":4}],"distinct":1, +// "blanks":0,"invalid":3,"partial":true}: table_filter_note text == "The list may grow while data loads\n3 cells could not +// be read"; no checkbox for the invalid cells. + +// Mutation: "(Select all)" under a search ticking only the values the page shows. +TEST_CASE("filter menu: Select all under a search covers every match, and both sides over the bound refuse", "[ui][table][config]") +// rows table of 25,000 rows, `code` "c00000".."c24999": untick (Select all), search "c0" (10,000 matches, 200 shown), +// tick (Select all), Apply: include [{"oneOf": the 10,000 operands "c00000".."c09999"}], not the 200 shown — resolved by +// ten distinct requests of limit 1000. Untick (Select all), tick (Select all) under "c1" (10,000) and under "c2" (5,000), +// Apply: T = 15,000, U = 10,000 → exclude [{"oneOf": "c00000".."c09999"}], named by paging every value. Untick +// (Select all), tick it under "c1", "c00" and "c01" (T = 12,000, U = 13,000), Apply: table_filter_note == "Too many +// values to list; filter with a condition" and t.filters is unchanged. + +// Mutation: conditions offered by Text for every kind; an operand sent as typed. +TEST_CASE("filter menu: conditions follow the column's kind, and typed operands are canonical", "[ui][table][config]") +// Integer column: table_filter_op_1 options "=","≠","<","≤",">","≥","between"; Bool column: no table_filter_op_1; +// Custom column: "is empty","is not empty"; a Date column: table_filter_operand_1 is a DateTimeInput (Date mode). +// Under a session locale "de": a Decimal column, ">" and operand "1.234,5" → include [{"gt":"1234.5"}]; a Measure column +// `weight` (mass: g, kg): table_filter_unit_1 offers "g","kg"; ">" with "0,3 kg" → [{"gt":"0.3 kg"}]; ">" with "250" and +// unit "g" → [{"gt":"250 g"}]; "12,5 xx" shows an error on the operand and sends nothing. + +// Mutation: the Measure list drawn without dimension headings. +TEST_CASE("filter menu: a Measure column's values are grouped under a heading per dimension", "[ui][table][config]") +// kConfigModelTable; distinct reply values 0.3 kg (mass), 300 g counted as one with it, 0.5 % (ratio): table_filter_heading_mass +// precedes table_filter_value_0, table_filter_heading_ratio precedes the ratio value. + +// Mutation: the group menu sending `together` as one oneOf. +TEST_CASE("filter menu: a group's values are pooled and the match line builds the quantifier", "[ui][table][config]") +// rows table with "groups": [{"id":"company","label":"Company","columns":["companyA","companyB","companyC"]}] and the five +// rows of the spec's truth table; the table's `columnGroups` prop is "[Company:0+3]" (the three stand side by side) and +// clickGroupFilter(table, 0) opens the group's menu; after moving companyB to the end it is "[]" and the menu is reached +// from the header and table menus only; menuOf(table, ) has "Filter Company, 3 columns…"; its values list counts +// F 4, S 2, X 4, Y 2, Z 1 (rows having it in any column: F in rows 1 to 4, S in 1 and 3, X in 1, 2, 4 and 5, Y in 4 and 5, Z in 5); tick F and S, match "all of them, each in a column", Apply: +// filters.groups == [{"group":"company","mode":"together","include":[{"eq":"F"},{"eq":"S"}]}] and the view holds rows 1 +// and 3 only; match "in at least N columns", N 2: rows 1, 2, 3. + +// Index decision 26. Mutations: a user-formed group's menu sending DistinctRequest::group with its layout id, a group +// the source does not declare; the filter sent with "group":"g1" (Part C's compileGroup answers UnknownColumn for it). +TEST_CASE("filter menu: a user-formed group offers conditions and the match line, no values list", "[ui][table][config]") +// columns a, b (Text) formed into "Pair" (12e's chooser, id g1): chooseMenu(table, , {"Filter Pair, 2 columns…"}): +// no table_filter_search, table_filter_all or table_filter_value_* widget, and no distinct request is sent; +// table_filter_op_1 offers the Text conditions and table_filter_match the four quantifiers (not "all of them, each in a +// column"); "equals" "F" with "in every column", after 250 ms: the request's filters.groups == +// [{"columns":["a","b"],"match":"all","include":[{"eq":"F"}]}] with no "group" member (table.md "Column groups": +// `match` is "any", "all", {"atLeast": n} or {"exactly": n}), and t.filters.groups holds the same one object; reopening the +// group's menu shows "equals" "F" and "in every column"; table_group_remove_g1 in the chooser (12e) empties +// t.filters.groups. + +// Mutation: the date tree filtering months on the client (an opened year past 200 months shows nothing). +TEST_CASE("filter menu: a date column lists years, then a year's months, then a month's days", "[ui][table][config]") +// kConfigModelTable over a description whose c3 is a Date column: opening its menu sends distinct {"bucket":"year"}; the reply +// lists 2025, 2026; table_filter_open_1 (2026) sends {"bucket":"month","search":"2026-"}; opening March sends +// {"bucket":"day","search":"2026-03-"}; every box starts unticked and there is no table_filter_all; tick March, then 2025 +// (in that order), Apply: include [{"between":["2025-01-01","2025-12-31"]}, {"between":["2026-03-01","2026-03-31"]}] +// (ascending, not the order of ticking) with combine "any"; reopen: 2025 and March are ticked, 2026 is not. +// Mutation: adjacent buckets sent as one entry each. Tick the 31 days of March and the first 9 of April one by one (40 +// touching days): Apply sends one entry, {"between":["2026-03-01","2026-04-09"]}. +// Mutation: a selection over maxEntries sent as it is (the server refuses the query). Tick 33 days no two of which +// touch (every second day from 2026-03-01): Apply sends nothing, t.filters is unchanged and table_filter_note == +// "Too many dates to list; filter with a condition". + +// Mutation: the unit choice written to the column's own unit instead of the layout. +TEST_CASE("display unit: the header menu writes the layout's units", "[ui][table][config]") +// Measure column `weight` (dimension mass, units g and kg): chooseMenu(table, , {"Display unit", "mass: g"}): +// t.layout.units == {"weight":{"mass":"g"}}; no new page request. +``` + +In `tests/net/test_push_tables.cpp` (Linux, recorded, not gates): + +```cpp +TEST_CASE("table benchmark: a sort change and a text filter over a socket with 50 ms each way", "[.benchmark][table]") +// B3: the server's handler waits 50 ms before running each request and 50 ms before sending each reply; a header sort on +// `wide` (100,000 × 300) to the accepted page (≤ 150 ms), and the last key of a text filter to the accepted page +// (≤ 250 ms + 150 ms). +TEST_CASE("table benchmark: a server-mode values list from open to shown", "[.benchmark][table]") // D9, ≤ 150 ms +``` + +**From Task 15 (Part F), which landed first.** The values list labels each entry with the column's display, not the +reply's `text`: `table_filter_value_` is `ui::distinctTexts(values, column, locale, units)[i] + " (" + count + ")"` +(`include/morph/ui/cell_format.hpp`; `column` the shown column's `table::TableColumn` with the document's display +parts over the description's, `units` the table's `DisplayUnits`). Two values that show alike keep their own places +there. Add to Step 1 a new case, "filter menu: the values list labels by the column's display": over +`companionDescription()`'s `mass` (2 places, half up), distinct values `0.124`, `0.123` and `0.5` label `0.124 (1)`, +`0.123 (2)` and `0.50 (1)`. Its name falls under this task's Step 2 filter (`filter menu`). Mutation: the entry +labelled with the reply's `text`. + +- [ ] **Step 2: Run them to see them fail.** Run: `cmake --build --preset cl-debug --target morph_tests && ctest --test-dir build/cl-debug -R "filter menu|display unit" --output-on-failure`. Expected: FAIL — no `table_filter` dialog is mounted. + +- [ ] **Step 3: Implement** `TableRows::distinctValues` in both implementations, `tableFilterDebounce`, the `groups` key, the menu and the `Display unit` submenu per the rules above. + +- [ ] **Step 4: Run them to see them pass.** The Step 2 command, then all `[ui]` cases. Expected: all pass. + +- [ ] **Step 5: Record B3 and D9** on Linux: `cmake --preset linux-everything && cmake --build build/linux-everything --target morph_net_tests && build/linux-everything/tests/net/morph_net_tests "table benchmark: a sort change*" "table benchmark: a server-mode values list*"`; write the figures into table.md's B3 and D9 rows. + +- [ ] **Step 6: Mutations, docs, commit.** Commit: `feat(ui): the filter menu with values, conditions, groups and units`. + +### Task 12e: The column chooser and the sort dialog + +**Files:** +- Create: `include/morph/ui/table_dialogs.hpp` (both dialogs' view trees) +- Modify: `src/ui/interpreter.cpp` +- Test: `tests/test_ui_table_model.cpp` +- Docs: `docs/spec/qt_quick/backend.md` (the dialogs) + +**Interfaces:** +- Consumes: 12a's gestures and `FormGroup`; 12c's lowering. +- Produces: `Columns…` opens a `ui::Dialog` `table_columns` listing every column of the description in layout order (a companion column is not listed once Task 15 marks companions): per column a Checkbox `table_columns_show_` (its label; disabled for a locked column and for the only visible one), Buttons `table_columns_up_` and `table_columns_down_`; Buttons `table_columns_reset` (`Reset columns`) and `table_columns_group` (`Group columns…`, offered while `hide` or `reorder` is allowed), which shows `table_group_label` (TextInput), `table_group_column_` Checkboxes (after the first is ticked, only columns of its kind stay enabled), `table_group_create` (Button, enabled at 2 to 16 ticked and a label), and under them one line per user-formed group of the layout, `table_group_` (Text, its label and column count, `Pair, 2 columns`) with Button `table_group_remove_` (`Remove group`), which applies `RemoveGroup{id}` and, per 12d's rule, removes the group's filter; `Sort…` opens `table_sort` listing the chain: per key `i` from 0 a Select `table_sort_column_` (sortable columns), Select `table_sort_direction_` (`ascending`, `descending`), Buttons `table_sort_up_`, `table_sort_down_`, `table_sort_remove_`; Button `table_sort_add` (`Add key`, adds the first sortable column not in the chain; at the bound it refuses with the message). Both dialogs apply each change as it is made, through the same gesture functions; a `Done` button and a dismissal close them. + +- [ ] **Step 1: Write the failing tests:** + +```cpp +// Mutation: the chooser listing only the visible columns. +TEST_CASE("column chooser: every column in order, with show, move and reset", "[ui][table][config]") +// kNine with c3 hidden: table_columns_show_c3 is listed unchecked in third place; check it: t.hiddenCount == 0; +// table_columns_down_c1: t.visibleColumns starts "c2","c1"; table_columns_reset: declared order. + +// Mutation: group creation accepting columns of two kinds. +TEST_CASE("column chooser: Group columns forms a group of one kind, which the layout keeps", "[ui][table][config]") +// columns a, b (Text) and n (Integer): tick table_group_column_a → table_group_column_n disabled; tick b, label +// "Pair", create: t.layout.groups == [{"id":"g1","label":"Pair","columns":["a","b"]}]; menuOf(table, ) holds +// "Filter Pair, 2 columns…"; the chooser lists table_group_g1 "Pair, 2 columns". +// Mutation: the Remove group button closing the line without applying RemoveGroup. +// click table_group_remove_g1: t.layout.groups == [], menuOf(table, ) no longer holds "Filter Pair, 2 columns…", +// and onLayoutChange ran once more. + +// Mutation: the sort dialog's move applying to the wrong neighbour. +TEST_CASE("sort dialog: keys in order with direction, move and remove; Add key refuses at the bound", "[ui][table][config]") +// sort c1 asc, c2 desc: table_sort_up_1 → [c2 desc, c1 asc]; table_sort_direction_0 "ascending" → c2 asc; +// table_sort_remove_1 → [c2 asc]; with eight keys table_sort_add leaves eight and shows "A table sorts by at most 8 columns". +``` + +**From Task 15 (Part F), which landed first.** The column chooser lists no companion column (the columns of +`table::companionColumns(description)`), even one the description marks `shown`. In Step 1, **extend the existing +case** "table display: companion columns are not arranged" in `tests/test_ui_table_model.cpp` (do not add a second +case of that name): over `companionDescription()` the chooser (`Columns…`, dialog `table_columns`) has +`table_columns_show_id`, `_mass`, `_name` and `_count`, and no `table_columns_show_massTone`, `_massTip` or +`_lockedBy`. Mutation: the chooser listing every column of the description. + +- [ ] **Step 2: Run to see them fail.** `ctest --test-dir build/cl-debug -R "column chooser|sort dialog|companion columns are not arranged" --output-on-failure` after building `morph_tests`. Expected: FAIL — no `table_columns` dialog. +- [ ] **Step 3: Implement** the dialogs and their openers. +- [ ] **Step 4: Run to see them pass**, then all `[ui]` cases. +- [ ] **Step 5: Mutations, docs, commit.** Commit: `feat(ui): the column chooser and the sort dialog`. + +### Task 12f: Copy, and the screens + +**Files:** +- Modify: `include/morph/ui/table_rows.hpp` (`TableRows::fetchRows`), `src/ui/interpreter.cpp` +- Test: `tests/test_ui_table_model.cpp` +- Docs: `docs/spec/ui/interpreter.md` (copy), `docs/spec/ui/document.md` (`maxCopyRows` named in the copy rule) + +**Interfaces:** +- Consumes: 12a's `copyText`, `tableText`; 12b's `onCopy`, `copyText`; Part D's `tableMessage` (Task 9d, index decision 11); Part D's `ui::detail::standInCellText(table::Cell const&, table::TableColumn const&)` (replaced by Task 15's `ui::formatCell(table::Cell const&, table::TableColumn const&, ui::FormatContext const&, DisplayUnits const& = {})`, which copy calls with the session's `FormatContext` and the layout's display units) and its range selection (Task 10a), whose bound this task's Review Focus case holds at its edge. +- Produces: + - `struct FetchedRow { table::RowId key; std::int64_t viewRow = 0; std::vector cells; }`; `TableRows::fetchRows(std::vector keys, std::vector columns) -> async::Completion, table::TableError>>` (pure virtual; `EngineRows` answers at once; `WindowRows` sends keyed queries naming `columns`, at most `QueryLimits::maxKeys` keys each, through the read that makes no cache entry, and returns the rows the replies hold with their view rows; a key no reply holds is not returned) +- Rules: `Ctrl+C` and `Copy` copy the selected rows in view order by the visible columns in layout order, each cell's display text; with no row selected the focused cell's text; `Copy with headers` adds the labels' line. Over `maxCopyRows` selected keys it refuses with `copyBound` and copies nothing; otherwise it fetches the rows the window does not hold, writes `copyText`, calls `IViewBackend::copyText`, and shows `copied(rows, unloaded)`; every message goes through `tableMessage`. + +- [ ] **Step 1: Write the failing tests:** + +```cpp +// Mutation: copy writing rows in selection order instead of view order. +TEST_CASE("copy: selected rows as tab-separated display text in layout order, rows not held fetched", "[ui][table][config]") +// kConfigModelTable over samplesDescription(5) sorted by name, c3 hidden, `name` moved first; the page holds view rows 0-29; +// select keys 9 and 2 (view rows 40 and 3); pressCopy(table): one keyed Table.samples request naming only the visible +// columns and keys [9] (the held row is not +// fetched); clipboardText(h) == "\n" with "\t" between cells in the arrangement's +// order; statusOf(h).message "Copied 2 rows". chooseMenu(table, nullopt, {"Copy with headers"}) prefixes the labels' line. +// No row selected: the focused cell's text alone. A rows table whose `name` column has its own `cell` (a badge reading +// `row.name`) copies the value's text, not the template's. + +// Mutation: unloaded cells copied as their placeholder text. +TEST_CASE("copy: unloaded cells copy as empty and are counted", "[ui][table][config]") +// kConfigModelTable whose page reply names both rows in `unloadedRows` for level `recipe` (hand-written reply; c4 of that +// level): select the two rows, copy: their c4 cells are empty fields; +// message "Copied 2 rows, 2 cells were not loaded"; no request waits for the level. + +// Review Focus 3. Mutation: the bounds compared with `>=`. +TEST_CASE("range and copy at their bounds: 10,000 pass, 10,001 are refused", "[ui][table][config]") +// kConfigModelTable, pageJson total 100,000, nothing held past the first page: selectTableRange(table, 0, 9'999): keysOf +// fetches pages naming no columns (each body's "columns" is []), t.selectedCount == 10000; pressCopy: copies 10,000 lines; +// selectTableRange(table, 0, 10'000): statusOf(h).message "A range selects at most 10,000 rows", selection unchanged; +// with 10,001 keys selected (a 10,000-row range, then a Ctrl-click), pressCopy: "A copy holds at most 10,000 rows", +// clipboardText(h) unchanged (still the 10,000 lines). +``` + +(`selectTableRange` is the `RecordingBackend` driver Part D's Task 10a adds for its range report. Replies the helpers of `tests/ui_table_support.hpp` do not build (distinct values, keyed replies, `unloadedRows`) are written as JSON in the test.) + +**From Task 15 (Part F), which landed first.** Copy writes each cell as the table shows it, with +`ui::formatCell(cell, column, scope->formatting(), displayUnits)`, and each header with `ui::headerText(label, unit)` +(`include/morph/ui/cell_format.hpp`), before `ui::copyText(labels, rows)` and `IViewBackend::copyText`. Add to Step 1 +a new case, "copy: writes the shown text and the header with its unit" (Task 15's brief planned it as "table +display: copy writes …"; it was never written, and this name falls under Step 2's `copy:` filter): over +`companionDescription()` with `"selectionMode":"multiple"` and `"columns":[{"id":"id"},{"id":"mass"},{"id":"name"}]`, +select row 1 and choose "Copy with headers": `clipboardText()` is `"Id\tMass [kg]\tName\n1\t0.13\tA"`. Mutation: copy +writing `table::displayText`, which writes `0.125`. + +- [ ] **Step 2: Run to see them fail.** `ctest --test-dir build/cl-debug -R "copy:|range and copy" --output-on-failure` after building `morph_tests`. Expected: FAIL — `fetchRows` does not exist; the clipboard stays empty (the range half of the bounds case passes already: it holds Part D's rule at its edge, and is here so the two bounds are tested side by side). +- [ ] **Step 3: Implement** `fetchRows` in both `TableRows` and the copy rule above. +- [ ] **Step 4: Run to see them pass**, then the whole of `morph_tests`, `morph_table_tests`, and in `build/cl-qt-debug` `morph_qt_quick_tests` and `morph_tui_tests`: all pass. +- [ ] **Step 5: The screens.** Existing tables now draw a `⋯` table-menu button, filter buttons on filterable headers and, on model-backed tables, a status line. This repository checks in no pixel baselines (`git ls-files '*.png'` lists none); screens are grabbed by `scripts/shoot_screens.sh` and `scripts/shoot_lims.sh`, which run the example clients with `QT_QPA_PLATFORM=offscreen --grab`. The user runs, on a Linux tree with Qt Quick and examples (`cmake --preset linux-everything && cmake --build build/linux-everything --target morph_examples_client morph_lims_client`), once on `master` and once on this branch: + `scripts/shoot_screens.sh /tmp/grabs- build/linux-everything/examples/client/morph_examples_client` and `scripts/shoot_lims.sh /tmp/lims-grabs- build/linux-everything/examples/client/morph_lims_client`, and compares each pair: the only differences are the three intended ones. The authoring goldens (`tests/ui/golden/*.json`) do not change, since no builder writes the new keys; confirm with `ctest --test-dir build/cl-debug -R "golden" --output-on-failure` (a golden that does change is regenerated with `MORPH_UPDATE_GOLDENS=1 build/cl-debug/tests/morph_tests.exe "[golden]"` and its diff reviewed in this commit). +- [ ] **Step 6: Mutations, docs, commit.** Commit: `feat(ui): copy a table's selection`. + +--- + +## Task 13: Collections through the same lowering (table.md step 8) + +**As landed (093110af and its fix round).** No `TableSurface` or `lowerTableSurface`: factoring the `rows` table's +node-reading lowering would have rewritten most of it while Task 17a changed the same file. A collection keeps a +`RowsTable` in its element (no source, no page) made by `ScreenCore::wireCollectionTable`, and +`ScreenCore::lowerCollectionRows` mounts it; it shares `configureTable` (gestures, menus, chooser, sort dialog, filter +menu, copy), the status line's message and gesture routing, the stored state's key and debounced saves, and the +saved views' `TableViews` with every other table, and has its own columns, cells, key translation and status line. +A per-table rule a later task adds to the lowering is therefore wired in three places: `makeRowsTable`/`lowerRows`, +`wireModelTable`/`modelTableOf`, and `wireCollectionTable`/`lowerCollectionRows`. The interface text below is the +design as planned. + +**Spec:** "Collections and master-detail"; "Every surface on the pipeline" (the collection row); gate U5 (recorded); the collection half of the Tests row "One order on every surface". + +**Files:** +- Modify: `include/morph/forms/engine/collection_view.hpp:31-46` (`CollectionChrome::rows`), `:177-227` (`collectionRows` calls it when set), `include/morph/forms/engine/collection.hpp:366-430` (nothing new in the session; its `source()` is the list's `DataSource`), `src/ui/interpreter.cpp:7033-7055` (`lowerComposite` sets `chrome.rows`) and the table lowering (factored as below) +- Test: `tests/test_ui_table_model.cpp`, `tests/bench_interpreter.cpp`, `tests/ui_table_support.hpp` (adds `rowKeys`, index decision 20); existing `tests/test_ui_interpreter_forms.cpp` and `tests/test_forms_engine_collection_view.cpp` stay green unchanged +- Docs: `docs/spec/forms/engine.md` ("Collections": the rows through the table lowering), `docs/spec/ui/interpreter.md` (a collection's table), table.md (U5 figure) + +**Interfaces:** +- Consumes: Part D's `EngineRows(std::shared_ptr, RecordOf, table::EngineOptions)` over `session.source()` (a `RecordOf` reading the collection row's key and its cells as a record), the state store and `SessionOptions::application`; 12c's lowering. +- Produces: + - `forms::CollectionChrome::rows : std::function const& buttons)>` — replaces the rows table; `buttons` is empty when the view has no Open or row action + - in `src/ui/interpreter.cpp`: `lowerTableSurface` — the part of the table lowering below reading the node. It reads no `DocNode`: everything 12c to 12f and 14 read from a `table` node reaches it as a member of the surface, so the document `table` node fills every member from its keys and a collection leaves the defaults. The types: + - `struct SurfaceColumn { std::string id; std::string label; table::ColumnKind kind = table::ColumnKind::Text; bool shown = true; bool sortable = false; bool filterable = false; bool locked = false; ui::TableColumn look; CellView cell; }` — `look` carries the column's `width`, `role`, `align`, `valign`, `wrap` and `shrink` (its `label`, `id`, `sortable` and `filterable` are overwritten from the members beside it); `cell` is the column's own cell view, of the type 9d's `TableSource::cellView` returns for one column (index decision 28), empty for the formatted text cell; + - `struct SurfaceValue { ExprPtr bound; DocCommands onChange; }` — `bound`: the node's expression when the document binds the value, null when the table holds it; `onChange`: what `DocNode::event` returns for the value's change key, run with `event` the new value; + - `struct TableSurface { std::shared_ptr rows; std::vector columns; std::vector groups; std::function trailingCell; std::string trailingLabel; std::function cellTestId; RowView rowView; ui::TableOptions options; SurfaceValue layout; SurfaceValue sort; SurfaceValue filters; Configure configurable = Configure::All; bool menus = true; std::optional status; std::optional stateKey; std::size_t maxSortKeys = 8; }` — `groups`: the declared groups (12d); `rowView`: 9d's row-level view (tone, label), empty for none; `menus`: false under `configurable: false`; `status`: the node's literal, absent for the default; `stateKey`: absent when the table persists nothing (`persist: false`, a `rows` table with no `id`); + - `Node ScreenCore::lowerTableSurface(TableSurface surface, LowerCtx const& ctx, ElementState* element)`. + What only a `rows` table has — `group` headings, `pageSize`/`page`, `rowSpans`, `empty` — stays in the document table's own code around the call. `CellView`, `RowView` and `DocCommands` stand for the types Part D's lowering already uses for these three things; the executor writes the landed names + - a collection's surface: columns from `CollectionModel::columns()` (`id = field`, `label`, `kind`, `shown = !hidden`, sortable and filterable), the trailing buttons column (label empty), cell test ids `cell__`, options from `forms::detail::engine::rowsTableOptions(session)` (test id `collection_rows`, master-detail selection), state key `{application = SessionOptions::application, model = the node's model type, table = the collection's action, qualifier = the screen's id, part}` + - test support, this task's (no earlier task defines it; later tasks reuse it by name): `std::vector rowKeys(ui::testing::TableHarness& h, int table)` in `tests/ui_table_support.hpp` (index decision 42 names it; if 9d has landed a `rowKeys` of this meaning, this task reuses it and adds none) — the `rowKey` property of each of `h.backend.children(table)` that has one, in child order (the order the mount placed the realized rows), with a string key's surrounding quotes removed (`RecordingBackend`'s `formatKey` quotes text keys and not integer ones), so a collection keyed by text and a rows table keyed by integer compare equal + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_model.cpp`, over this document in `tests/ui_table_support.hpp` (`Lims_ListSamples` is in `corpusCatalog()`, which `TableHarness`'s catalog includes; the rows table holds the rows the test replies to the collection, so both surfaces have the same four): + +```cpp +/// The Samples collection beside a rows table `t` over the same four rows. +inline constexpr std::string_view kCollectionBesideTable = R"({ + "vocab": "ui/1", "id": "both", + "models": { "sample": { "type": "Lims_SampleModel" } }, + "state": { "rows": { "init": { "lit": [ { "id": 1, "name": "beta" }, { "id": 2, "name": "Alpha" }, + { "id": 3, "name": "álpha" }, { "id": 4, "name": "Gamma" } ] } } }, + "view": { "kind": "column", "children": [ + { "kind": "collection", "model": "sample", "action": "Lims_ListSamples" }, + { "kind": "table", "id": "t", "testId": "t", "rows": { "ref": "rows" }, + "columns": [ { "id": "id", "label": "ID", "sortable": true }, + { "id": "name", "label": "Name", "sortable": true } ] } ] } })"; +``` + +`h.reply`, `h.dispatcher.last`, `h.find`, `h.byTestId` and `h.text` are the members `TableHarness` has in common with the existing `Harness` (`tests/ui_interpreter_support.hpp:560-603`); where 9d left one out, the test reads the same thing through `h.backend`. + +```cpp +// Mutation: the collection keeping the reply's order (chrome.rows not set by the interpreter). +TEST_CASE("collection: a collection and a rows table over the same rows show the same order and selection", "[ui][table]") { + ui::testing::TableHarness h; + auto screen = h.mount(kCollectionBesideTable); + std::string const rows = R"([{"id":1,"name":"beta"},{"id":2,"name":"Alpha"},{"id":3,"name":"álpha"},{"id":4,"name":"Gamma"}])"; + h.reply(h.dispatcher.last("Lims_ListSamples"), R"({"rows":)" + rows + "}"); + int const collection = h.byTestId("Table", "collection_rows"); + int const table = h.find("Table", "testId", "t"); + // A header index counts every column of `Table::columns`, hidden ones included (the surface lays out every + // column and hides through `Table::arrangement`): ID is index 0 and hidden, Name is index 1 on both tables. + REQUIRE(h.backend.prop(collection, "columns").starts_with("[ID")); + h.backend.clickHeader(collection, 1, ui::HeaderClick::Plain); // Name + h.backend.clickHeader(table, 1, ui::HeaderClick::Plain); // Name + h.settle(); + CHECK(rowKeys(h, collection) == rowKeys(h, table)); + CHECK(rowKeys(h, collection) != std::vector{"1", "2", "3", "4"}); + CHECK(h.text("cell_name_2") == "Alpha"); +} + +// Mutation: the master-detail selection lost when the engine reorders. +TEST_CASE("collection: a master-detail selection and its open row hold through a sort", "[ui][table]") +// master-detail view over the same rows: selectByUser(collection_rows, {3}) opens row 3; clickHeader(collection, 1, Plain) +// (Name): the table's selection prop still marks 3; detailForm visible; the editor's sampleId field reads 3. + +// Mutation: the collection's state saved under the screen's rows key. +TEST_CASE("collection: header and table menus are present and its arrangement persists under its action", "[ui][table]") +// TableHarness(store) over a MemoryTableStateStore: menuOf(collection, 1) (Name) holds "Hide column"; choose it, h.advance(500ms): +// one save whose key is {application "lims", model "Lims_SampleModel", table "Lims_ListSamples", qualifier the screen's +// id, part "state"}. +``` + +Extend Task 11b's `"one order on every surface"` case with the collection over the same rows (the same sort gives the same key order on all three surfaces). In `tests/bench_interpreter.cpp`: + +```cpp +TEST_CASE("interpreter bench: a collection of 20,000 rows: mount, sort, one row edited", "[.benchmark][interpreter]") // U5 +``` + +- [ ] **Step 2: Run to see them fail.** `ctest --test-dir build/cl-debug -R "collection:" --output-on-failure` after building `morph_tests`. Expected: FAIL — the collection's order is the reply's. +- [ ] **Step 3: Implement** `CollectionChrome::rows`, `TableSurface`, `lowerTableSurface` and the collection's surface as above. +- [ ] **Step 4: Run to see them pass**, then `ctest --test-dir build/cl-debug -R "collection|forms engine collection|one order on every surface" --output-on-failure` and the whole of `morph_tests`. Expected: all pass, existing collection tests unchanged. +- [ ] **Step 5: Record U5** with `build/cl-release/tests/morph_tests.exe "interpreter bench: a collection of 20,000 rows*"` into table.md's U5 row. +- [ ] **Step 6: Mutations, docs, commit.** Commit: `feat(ui): collections on the table pipeline`. + +--- + +## Task 14: Saved and shared views (table.md step 9) + +**Spec:** "Saved views", "Persisted state" ("What is stored", "Two windows, two devices", "The framework's stores"), the Tests rows "Views are not lost between windows" and "Shared views", gate T2. Three commits. + +### Task 14a: The views document, its operations, and publishing on the server + +**Files:** +- Modify: `include/morph/table/state_store.hpp` (views document, operations, `ITableStateStore::publish`, `MemoryTableStateStore` sharing), `include/morph/ui/table_state_model.hpp` (`publish`; a user's `save` of `shared` refused), `include/morph/ui/table_state.hpp` (`PreferencesTableStateStore::shares()`, `publish`) +- Test: `tests/table/test_table_state.cpp`, `tests/test_ui_table_state.cpp` +- Docs: `docs/spec/ui/preferences.md` (the `shared` part kept with no person); `docs/spec/table/table.md` is not edited for these: its `ITableStateStore` block in "Persisted state" already declares `publish` (with its default refusal) and `kNoDocument`, with the paragraph saying what the sentinel means; "Two windows, two devices" already says a `views` save from a table that loaded nothing sends `kNoDocument`; "The framework's stores" already names `MemoryTableStateStore`'s `Sharing` and its default, `Private`. Check: `grep -n "kNoDocument\|Sharing::Private" docs/spec/table/table.md` prints those lines. + +**Interfaces:** +- Consumes: Part D's `TableStateKey`, `SaveOutcome`, `SaveResult`, `ITableStateStore`, `MemoryTableStateStore`, `TableStateModel`, `TableStateSaved`, `registerTableState`, `fitState`; Task 8d's `ColumnLayoutValue` (with `groups`, `units`). +- Produces (namespace `morph::table`): + - `struct SavedView { std::string name; ColumnLayoutValue layout; SortChain sort; FilterSpec filters; }` + - `enum class ViewsPart : std::uint8_t { Own, Shared }` + - `struct ViewsDocument { int version = 1; std::optional defaultView; bool defaultOnMount = false; std::vector views; }` (JSON `{"version", "default", "defaultOnMount", "views"}`; a `Shared` document writes neither `default` nor `defaultOnMount`) + - operations `AddView{SavedView}`, `ReplaceView{SavedView}`, `RenameView{std::string from; std::string to;}`, `RemoveView{std::string name}`, `SetDefaultView{std::optional name}`, `SetDefaultOnMount{bool on}`; `using ViewOperation = std::variant<…>`; JSON `{"add": view}`, `{"replace": view}`, `{"rename": {"from", "to"}}`, `{"remove": name}`, `{"default": name|null}`, `{"defaultOnMount": bool}` + - `enum class ViewError : std::uint8_t { NameTaken, NoSuchView, NotShared }`; `[[nodiscard]] std::expected applyViewOperation(ViewsDocument document, ViewOperation const& operation, ViewsPart part)` (`AddView` and `RenameView` onto a taken name → `NameTaken`; `ReplaceView`, `RenameView`, `RemoveView`, `SetDefaultView` naming no view → `NoSuchView`; `SetDefaultView`/`SetDefaultOnMount` on `Shared` → `NotShared`; removing the default view clears `defaultView`) + - `[[nodiscard]] std::expected readViews(std::string_view json)` (an unknown `version` → `InvalidSpec`), `[[nodiscard]] std::string writeViews(ViewsDocument const&, ViewsPart part)`; an operation's JSON through `[[nodiscard]] std::string writeViewOperation(ViewOperation const&)` and `[[nodiscard]] std::expected readViewOperation(std::string_view)`; `[[nodiscard]] std::string viewErrorText(ViewError, ViewOperation const&)` (`A view named {name} exists`, `No view named {name}`, `The shared views have no default`) + - `inline constexpr std::string_view kNoDocument = "-";` — an `expected` revision that stores only when nothing is stored under the key and answers `Conflict` otherwise; `MemoryTableStateStore` and `TableStateModel` honour it in `save` and `publish` (a `views` part saved by a table that loaded nothing sends it, so two windows that both start from no views cannot overwrite each other) + - `ITableStateStore::publish(TableStateKey const& key, ViewOperation const& operation, std::string expected) -> async::Completion` (pure virtual: the interface owns no executor to deliver a default answer on; a store that does not share returns the protected `static async::Completion refusePublish(exec::IExecutor&)`, which answers `Refused` with reason `"this store does not share views"` on the store's executor; the test store `GatedTableStateStore` does so) + - `enum class Sharing : std::uint8_t { Private, Shared }`; Part D's constructor gains a defaulted parameter, `explicit MemoryTableStateStore(exec::IExecutor& executor, Sharing sharing = Sharing::Private)`, so every Part D call `MemoryTableStateStore(executor)` compiles unchanged and keeps `shares() == false`; `shares()` is `sharing == Sharing::Shared`; its `publish` applies the operation to the `shared` part under the `expected` rule (`kNoDocument` included); over `Private` its `publish` keeps the base class's refusal +- Produces (namespace `morph::ui`): `struct TableStatePublish { table::TableStateKey key; std::string operation; std::string expected; }` (the key's `part` must be `"shared"`; `operation` the operation's JSON) → `TableStateSaved`, registered as `morph.tableState`'s action `publish` by `registerTableState`; the model applies it to the person-less `shared` entry (preferences `person` empty: no verified caller is ever empty, since the model refuses one with none), comparing `expected` with the head's revision (`Conflict` with the current revision when they differ), refuses `SetDefaultView`/`SetDefaultOnMount`, and refuses a caller with no verified person; its `save` with `part == "shared"` answers `Refused` (`"the shared views are written by publish"`); `PreferencesTableStateStore::shares()` returns `true` and its `publish` calls `morph.tableState.publish`. + +- [ ] **Step 1: Write the failing tests.** In `tests/table/test_table_state.cpp`: + +```cpp +// Mutation: AddView over a taken name appending a second view of that name. +TEST_CASE("views document: operations apply to what is stored, and names stay unique", "[table][state]") { + table::ViewsDocument doc; + auto const add = [](std::string name) { return table::AddView{table::SavedView{.name = std::move(name)}}; }; + doc = *table::applyViewOperation(doc, add("Open orders"), table::ViewsPart::Own); + doc = *table::applyViewOperation(doc, table::SetDefaultView{"Open orders"}, table::ViewsPart::Own); + // Compared with std::unexpected, not through .error(): under the mutation the result holds a value, and .error() + // on it aborts the run instead of failing the check. + CHECK(table::applyViewOperation(doc, add("Open orders"), table::ViewsPart::Own) == std::unexpected(table::ViewError::NameTaken)); + doc = *table::applyViewOperation(doc, add("Late"), table::ViewsPart::Own); + CHECK(table::applyViewOperation(doc, table::RenameView{"Late", "Open orders"}, table::ViewsPart::Own).error() == + table::ViewError::NameTaken); + doc = *table::applyViewOperation(doc, table::RemoveView{"Open orders"}, table::ViewsPart::Own); + CHECK_FALSE(doc.defaultView); + CHECK(table::applyViewOperation(doc, table::SetDefaultOnMount{true}, table::ViewsPart::Shared).error() == + table::ViewError::NotShared); + CHECK(table::writeViews(doc, table::ViewsPart::Shared) == + R"({"version":1,"views":[{"name":"Late","layout":{"order":[],"hidden":[],"pinned":0,"widths":{},"groups":[],"units":{}},"sort":[],"filters":{"columns":{},"groups":[]}}]})"); + CHECK(table::readViews(R"({"version":2,"views":[]})").error().code == table::TableErrorCode::InvalidSpec); +} +``` + +(The expected `layout` text follows `ColumnLayoutValue`'s writer as Task 8d lands it; keep the rest exact.) + +In the same file, the sentinel and the sharing default on the memory store (completions delivered on the file's `StepExecutor` and read through 9b's `saveNow`/`loadNow` and a `publishNow` beside them; an `exec::InlineExecutor` is not serial, so a `Completion` refuses it as its owner; the code below is written with `resultOf`, read it as those helpers). Revisions are asserted as the values the store returned, never as literals: + +```cpp +// Mutation: MemoryTableStateStore treating kNoDocument as an ordinary revision (the first save answers Conflict). +// Mutation: the constructor's Sharing defaulting to Shared (the default store offers publishing). +TEST_CASE("memory table state store: kNoDocument stores only over nothing, and a default store does not share", + "[table][state]") { + exec::InlineExecutor executor; + table::MemoryTableStateStore store{executor}; + CHECK_FALSE(store.shares()); + table::TableStateKey const key{.application = "lims", .model = "", .table = "t", .qualifier = "s", .part = "views"}; + table::SaveResult const first = resultOf(store.save(key, R"({"version":1,"views":[]})", std::string{table::kNoDocument})); + REQUIRE(first.outcome == table::SaveOutcome::Saved); + table::SaveResult const again = resultOf(store.save(key, R"({"version":1,"views":[]})", std::string{table::kNoDocument})); + CHECK(again.outcome == table::SaveOutcome::Conflict); + CHECK(again.revision == first.revision); + CHECK(resultOf(store.load(key))->revision == first.revision); + table::SaveResult const refused = resultOf(store.publish(key, table::AddView{table::SavedView{.name = "X"}}, + std::string{table::kNoDocument})); + CHECK(refused.outcome == table::SaveOutcome::Refused); + CHECK(refused.reason == "this store does not share views"); + table::MemoryTableStateStore shared{executor, table::Sharing::Shared}; + CHECK(shared.shares()); + auto sharedKey = key; + sharedKey.part = "shared"; + table::SaveResult const published = resultOf(shared.publish(sharedKey, table::AddView{table::SavedView{.name = "X"}}, + std::string{table::kNoDocument})); + REQUIRE(published.outcome == table::SaveOutcome::Saved); + CHECK(resultOf(shared.publish(sharedKey, table::AddView{table::SavedView{.name = "Y"}}, + std::string{table::kNoDocument})).revision == published.revision); // Conflict +} +``` + +In `tests/test_ui_table_state.cpp`, over the server harness Task 9 built for `morph.tableState` (`RemoteServer`, a recording `IPreferencesStore`, calls as a chosen token). The model's revisions are digests (Part D: the first 16 hex digits of `sha256(previousRevision + document)`), so every case below captures the revision a call returned and asserts against that value, never against `"1"` or `"2"`: + +```cpp +// Mutation: publish written under the caller's person (bob does not see it). +TEST_CASE("shared views: published by one principal, read by another", "[ui][table][state][remote]") +// alice publish {"add": {"name":"Mine",…}} with expected "-" → Saved with revision r1 (16 hex digits); bob load part +// "shared" → a document holding "Mine" whose revision == r1; the store's calls show the write under person "" and the +// read under person "". + +// Mutation: the model treating kNoDocument as an ordinary revision in `save` (the first save answers Conflict). +TEST_CASE("table state model: a save with kNoDocument stores over nothing and conflicts over something", + "[ui][table][state][remote]") +// alice save part "views" with expected "-" → Saved r1; again with expected "-" → {"outcome":"conflict"} whose +// revision == r1; the store holds the first document. + +// Mutation: the authoriser consulted with action "save" for a publish. +TEST_CASE("shared views: an authoriser that refuses publish refuses it by action id", "[ui][table][state][remote]") +// an IAuthorizer refusing (morph.tableState, "publish") for token "bob": bob's publish answers an error envelope and the +// store sees no write; alice's succeeds. + +// Mutation: save of part "shared" accepted. +TEST_CASE("shared views: a user's own save of the shared part is refused", "[ui][table][state][remote]") +// alice save {part "shared"} → {"result":{"outcome":"refused","reason":"the shared views are written by publish"}}; no write. + +// Mutation: publish ignoring `expected`. +TEST_CASE("shared views: a publish over a replaced revision is a conflict", "[ui][table][state][remote]") +// publish "A" with expected "-" → Saved r1; publish "B" with expected r1 → Saved r2, r2 != r1; publish "C" with +// expected r1 → {"result":{"outcome":"conflict","revision":r2}} (the revision compared is the one the second publish +// returned); the shared document holds A and B only. + +// Mutation: every state written as segments. (T2 gates) +TEST_CASE("table state: a full state is one entry and one call; a 20,000-value filter reads back equal through segments", + "[ui][table][state][remote]") +// a state of 300 columns, 8 sort keys and 32 filters: one store `set` and one entry; its byte count is logged (INFO) for +// table.md's T2 row; a state whose filter ticks 20,000 values: reads back byte-equal, every segment entry ≤ 12 KiB; the +// same two documents as the `views` part behave alike. +``` + +In `tests/net/test_push_tables.cpp` (Linux): `"shared views: a view published over a socket is read by a second client"` — the first two remote cases above, over a real socket. + +- [ ] **Step 2: Run to see them fail.** `cmake --build --preset cl-debug --target morph_tests morph_table_tests && ctest --test-dir build/cl-debug -R "views document|kNoDocument|shared views|table state: a full state" --output-on-failure`. Expected: compile errors for `ViewsDocument`, `kNoDocument`, `Sharing`, `TableStatePublish`. +- [ ] **Step 3: Implement** the interfaces above. +- [ ] **Step 4: Run to see them pass**; on Linux `ctest --test-dir build/linux-everything -R "shared views" --output-on-failure`. +- [ ] **Step 5: Mutations, docs, commit.** Record T2's bytes and entry counts in table.md. Run the Docs line's check, and the docs build, since `kNoDocument`, `Sharing` and `publish` are public. Commit: `feat(table): saved views, their operations and publishing`. + +### Task 14b: Saved views on a table + +**Files:** +- Create: `include/morph/ui/table_views.hpp` +- Modify: `include/morph/ui/table_config.hpp` (view menu commands), `src/ui/interpreter.cpp` (the `Views` submenu, the name dialog, mount behaviour), `tests/ui_table_support.hpp` (`RecordingTableStateStore`, `LiteralTableStateStore`, index decision 20) +- Test: `tests/test_ui_table_state.cpp` +- Docs: `docs/spec/ui/interpreter.md` (saved views), `docs/spec/ui/document.md` (the table menu's views), `docs/spec/table/table.md` is not edited: "Two windows, two devices" already states the retry when the reload finds nothing stored + +**Interfaces:** +- Consumes: 14a; Part D's `TableStates` (9c) with its `[[nodiscard]] table::ITableStateStore& store() const noexcept` (the store it was built over) and `void keep(table::TableStateKey const& key, table::StoredTableState state)` (replaces the kept document of `key`; the next `load(key)` resolves to it with no call) — both declared and tested by 9c, index decision 32; this task adds nothing to `TableStates` — and `Session::tableStates()`, the state key, load at mount, save and fitting; 12c's arrangement. +- Produces: + - `MenuCommand::{ApplyView, SaveView, RenameView, RemoveView, SetDefaultView, DefaultOnMount, ApplySharedView, PublishView, SaveAsMyView}` + - `class TableViews` (`morph::ui`, `table_views.hpp`): `TableViews(TableStates& states, table::TableStateKey key)` (`key.part` is ignored; it reads and writes the parts `"views"` and `"shared"` of `key`); `load() -> async::Completion>` — calls `states.load` for the `views` key and, when `states.store().shares()`, for the `shared` key, so they join the turn's one batched `TableStateLoad` with the screen's `state` keys (gate T5) and a second mount reads them from the kept copies with no call; `own() -> table::ViewsDocument const&`; `shared() -> table::ViewsDocument const&`; `change(table::ViewOperation operation) -> async::Completion>` — applies the operation to the loaded document (an operation error answers at once, with no save) and saves through `states.store().save` with the loaded revision, or `kNoDocument` when nothing was loaded; on `Saved` calls `states.keep`; on `Conflict` loads again through `states.store().load` (not `states.load`, whose kept copy is the one that conflicted), keeps what it read, applies the operation to it and saves once more, with that document's revision, or with an empty `expected` when the reload finds nothing stored (a store that does not honour `kNoDocument` answers `Conflict` over nothing; a store that does cannot, unless the document was removed in between); a second `Conflict` answers `Views could not be saved: another window changed them at the same time`; an operation error after the reload answers `A view named {name} exists` or `No view named {name}` and saves nothing; `publish(table::ViewOperation)` the same through `states.store().publish` on the `shared` key; `shares() -> bool` (`states.store().shares()`) + - the lowering builds one `TableViews` per mounted table that has a state key, over `Session::tableStates()`, and calls its `load()` in the same turn as the table's `state` load +- Rules: the table menu gains `Views` (a submenu): each own view (checked when it is the state's `view`; labelled `{name} (modified)` while the arrangement differs from the fitted view), separator, `Save view…`, `Rename view…`, `Remove view`, `Set as default`, `Start from the default view` (checkable). `Save view…` and `Rename view…` open `table_view_dialog` with `table_view_name` (TextInput) and `table_view_save` (Button); saving under a name the user already has is a `ReplaceView`. Applying a view fits it as stored state is fitted, sets `layout`, `sort` and `filters` (through their handlers where bound) and writes its name to the state's `view`; the status line shows `Saved view {name}` after a save. At mount: with no stored `state`, the `default` view is applied; with `defaultOnMount`, the default view's `sort` and `filters` are applied over the stored state's, and the stored `layout` still applies. A mounted table does not follow saves made elsewhere. + +- **Split on landing.** The table menu is not lowered on a screen yet (Task 12a built its model in `table_config.hpp`; the lowering, `menuOf`, `chooseMenu` and the arrangement on screen are Tasks 12b to 12e). So 14b lands `TableViews`, the `MenuCommand` entries, and the lowering's views load in the turn of the state load; its cases drive `TableViews` over `TableStates` directly, as two windows are two `TableStates` over one store. `TableViews` also takes the session's owner (`TableViews(TableStates&, TableStateKey, exec::IExecutor& owner)`), where its completions are delivered: `TableStates` does not expose its own. The `Views` submenu, the name dialog, "Applying a view", the `(modified)` mark, the default view and `defaultOnMount` at mount, and the cases "the default view at mount, and Start from the default view" and "applying a view records its name, and a change marks it modified" move to Task 14c, after 12e; the taken-name case's "Save view… named A" is `ReplaceView` sent by the test, the rule the menu will apply, and its AddView mutation is 14c's. The first case's last clause (both windows change the sort; the state part holds B's whole arrangement) is 9c's behaviour, tested there, and is not repeated. A further case mounts a `rows` table and a model-backed table over a sharing `RecordingTableStateStore` and checks the `views` and `shared` loads beside `state`, and none on a second mount (mutation: the lowering's `views->load()` calls deleted). + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_state.cpp`. Two test stores join `tests/ui_table_support.hpp` here: `RecordingTableStateStore` (a map store under the `expected` rule, `kNoDocument` included, delivering on the executor it is given, that records each call as `{op, part, expected, outcome, revision}`, `op` one of `"load"`, `"save"`, `"publish"`; it does not wrap a `MemoryTableStateStore`, whose completions belong to its strand and cannot be attached to from the owner), and `LiteralTableStateStore` (a map store that knows no sentinel: it compares `expected` with the stored revision as text, nothing stored counting as revision `""`, so `expected "-"` over nothing answers `Conflict` with revision `""`; an empty `expected` replaces; revisions `"r1"`, `"r2"`, …). Revisions are asserted as the values a call returned, never as literals. + +```cpp +// Mutation: a views save with no expected revision (the second window's save overwrites the first's view). +TEST_CASE("views: views are not lost between windows", "[ui][table][state]") +// two TableHarnesses (two sessions) over one RecordingTableStateStore, the same table: both mount with no views stored; +// window A saves view "A": the record shows save(views, expected "-") → Saved rA; window B saves view "B": save(views, +// expected "-") → Conflict carrying rA, then load(views), then save(views, expected rA) → Saved rB, rB != rA; the +// store's views part holds "A" and "B". Both mount again (new sessions: the views document read has revision rB) and +// each adds a view: the second's first save answers Conflict carrying the first's new revision, it reloads and saves +// once more; four views stored. Then A and B each change the sort: the state part holds B's whole arrangement (last +// save wins, no merge). + +// Mutation: TableViews loading through the store directly rather than through TableStates (one call per part). +// Gate T5, extended to the views parts. +TEST_CASE("views: a screen's state, views and shared parts load in one call, and a second mount in none", + "[ui][table][state]") +// 9c's five-table fixture over PreferencesTableStateStore (which shares): dispatcher.count("load") == 1 and that one +// TableStateLoad names 15 keys, parts "state", "views" and "shared" for each table; remountScreen(): +// dispatcher.count("load") is still 1. Over a MemoryTableStateStore (Private): no key of part "shared" is loaded. + +// Mutation: the retry after a Conflict resending kNoDocument (the second Conflict reports the views unsaved). +TEST_CASE("views: a store that ignores kNoDocument still saves the first view", "[ui][table][state]") +// TableHarness over LiteralTableStateStore, no views stored: Save view… named "A": the store saw save(views, expected "-") +// → Conflict with revision "", a load finding nothing, save(views, expected "") → Saved; status "Saved view A"; the +// stored views document holds "A". + +// Mutation: defaultOnMount applying the default view's layout too. +TEST_CASE("views: the default view at mount, and Start from the default view", "[ui][table][state]") +// no state stored, views {"default":"Open orders", views:[Open orders: sort c2 desc, hidden c3]}: the first query sorts by +// c2 desc and c3 is hidden. Then state {sort c1 asc, layout hiding c4} and "defaultOnMount": true: the first query sorts +// by c2 desc and c4 (stored layout) is hidden, c3 is shown. + +// Mutation: the modified mark compared against the unfitted view. +TEST_CASE("views: applying a view records its name, and a change marks it modified", "[ui][table][state]") +// chooseMenu(table, nullopt, {"Views", "Open orders"}): t.sort is the view's; after h.advance(500ms) the saved state has +// "view":"Open orders"; clickHeader(table, 0): menuOf(table, nullopt)'s Views submenu labels it "Open orders (modified)". +// A view whose filter names a removed column applies without that filter. + +// Review Focus 5. Mutations: Save view… with a taken name sending AddView (refused as NameTaken, the sort change lost); +// change() on Conflict saving its own document with the new revision instead of applying the operation to the reloaded +// one (window 2's view "C" is lost, or two views are named "C"). +TEST_CASE("views: a taken name is replaced on save and refused on rename", "[ui][table][state]") +// Window 1 over a RecordingTableStateStore holding views "A" and "B" at revision r0. Save view… named "A" after a sort +// change: one save(views, expected r0) → Saved r1; one view "A" with the new sort, two views in all. Rename view… on +// "B" to "A": status "A view named A exists", no save is recorded, views unchanged. +// Then window 2 (a second TableHarness over the same store) mounts, reads r1, and saves view "C" → Saved r2. Window 1, which +// still holds r1 and no "C", renames "B" to "C": the record shows save(views, expected r1) → Conflict carrying r2, then +// load(views) (the reload: the first load of that key since window 1 mounted), and no further save; status +// "A view named C exists"; the stored document is window 2's, views "A", "B", "C" at revision r2. +``` + +- [ ] **Step 2: Run to see them fail.** `ctest --test-dir build/cl-debug -R "views:" --output-on-failure` after building `morph_tests`. Expected: compile error for `ui::TableViews` (`morph/ui/table_views.hpp` missing); with the header stubbed, FAIL — no `Views` entry in the table menu. +- [ ] **Step 3: Implement** `TableViews`, the menu, the dialog and the mount rules. table.md "Two windows, two devices" already says that a table that loaded no views saves with `kNoDocument`, and that when the reload after a `Conflict` finds nothing stored the one retry saves with an empty `expected`; check with `grep -n "retry saves with an empty" docs/spec/table/table.md`. +- [ ] **Step 4: Run to see them pass**, then the whole of `morph_tests`. +- [ ] **Step 5: Mutations, docs, commit.** Apply each named mutation, see its case fail, revert. Run the docs build (`TableViews` is public). Commit: `feat(ui): saved table views`. + +### Task 14c: Saved views in the table menu, and shared views + +Needs the table menu on a screen (Tasks 12b to 12e: the menu's lowering, `menuOf`, `chooseMenu`, and 12c's +arrangement). 14b landed `TableViews`, the `MenuCommand` entries and the views load at mount, and no menu; what a +user touches of the saved views is this task's, below, with the shared views. + +A collection's table is a third wiring site (Task 13 as landed): `wireCollectionTable` builds its `TableViews` and +`lowerCollectionRows` mounts its menu, so the `Views` submenu, applying a view and the default view at mount are +wired there too, beside the `rows` table's and the model table's, with a collection case. + +**Files:** +- Modify: `include/morph/ui/table_views.hpp`, `include/morph/ui/table_config.hpp` (the `Views` submenu's entries, built from the `MenuCommand` entries 14b declared), `src/ui/interpreter.cpp` (the `Views` submenu, the name dialog `table_view_dialog`, applying a view, the status messages, the default view and `defaultOnMount` at mount) +- Test: `tests/test_ui_table_state.cpp`, `tests/net/test_push_tables.cpp` +- Docs: `docs/spec/ui/interpreter.md` (the `Views` submenu, applying a view, the default view at mount, shared views), `docs/spec/ui/document.md` (the table menu's views) + +**Interfaces:** +- Consumes: 14a's `publish`; 14b's `TableViews` (`load`, `own`, `shared`, `change`, `publish`, `shares`), its `MenuCommand::{ApplyView, SaveView, RenameView, RemoveView, SetDefaultView, DefaultOnMount, ApplySharedView, PublishView, SaveAsMyView}` and the `TableViews` each table with a state key holds and loads at mount; 12b–12e's table menu and arrangement. 14b delivered no menu. +- Produces, the user's own views: the table menu gains `Views` (a submenu): each own view (checked when it is the state's `view`; labelled `{name} (modified)` while the arrangement differs from the fitted view), separator, `Save view…`, `Rename view…`, `Remove view`, `Set as default`, `Start from the default view` (checkable). `Save view…` and `Rename view…` open `table_view_dialog` with `table_view_name` (TextInput) and `table_view_save` (Button); saving under a name the user already has is a `ReplaceView`. Applying a view fits it as stored state is fitted, sets `layout`, `sort` and `filters` (through their handlers where bound) and writes its name to the state's `view`; the status line shows `Saved view {name}` after a save. At mount: with no stored `state`, the `default` view is applied; with `defaultOnMount`, the default view's `sort` and `filters` are applied over the stored state's, and the stored `layout` still applies. A mounted table does not follow saves made elsewhere. +- Produces, shared views: the `Views` submenu gains, while `shared().views` is not empty, a heading `Shared views` and each shared view (applied as an own view is), and `Save as my view` while the current view is a shared one (an `AddView` of it into the user's views); while `shares()`, `Publish view…` (the name dialog, then a `publish` of `AddView`, or `ReplaceView` over a taken shared name); a refused publish shows `This view could not be published: {reason}`, a done one `Published view {name}`. Over a store whose `shares()` is false none of the publish entries is offered. + +- [ ] **Step 1: Write the failing tests:** + +```cpp +// Mutation: the shared part saved through `save` instead of `publish` (an authoriser cannot tell it from own state). +TEST_CASE("shared views on a table: publish, read by another person, Save as my view; none over a store that does not share", + "[ui][table][state][remote]") +// two TableHarnesses with PreferencesTableStateStore against one server harness, tokens alice and bob: alice's +// chooseMenu(table, nullopt, {"Views", "Publish view…"}) named "Team", dispatched as action "publish" (never "save"); +// bob mounts: his Views submenu has heading "Shared views" and "Team"; applying "Team" then "Save as my view" adds +// "Team" to bob's own views. An authoriser refusing bob's publish: status starts "This view could not be published:". +// A TableHarness over MemoryTableStateStore(executor) (Sharing defaults to Private): no "Publish view…" entry, and no load of +// part "shared". Alice's publish result is asserted by the revision it returned, read back by bob's load. +``` + +```cpp +// Mutation: defaultOnMount applying the default view's layout too. +TEST_CASE("views: the default view at mount, and Start from the default view", "[ui][table][state]") +// no state stored, views {"default":"Open orders", views:[Open orders: sort c2 desc, hidden c3]}: the first query sorts by +// c2 desc and c3 is hidden. Then state {sort c1 asc, layout hiding c4} and "defaultOnMount": true: the first query sorts +// by c2 desc and c4 (stored layout) is hidden, c3 is shown. + +// Mutation: the modified mark compared against the unfitted view. +TEST_CASE("views: applying a view records its name, and a change marks it modified", "[ui][table][state]") +// chooseMenu(table, nullopt, {"Views", "Open orders"}): t.sort is the view's; after h.advance(500ms) the saved state has +// "view":"Open orders"; clickHeader(table, 0): menuOf(table, nullopt)'s Views submenu labels it "Open orders (modified)". +// A view whose filter names a removed column applies without that filter. + +// Mutation: Save view… with a taken name sending AddView (refused as NameTaken, the sort change lost). +TEST_CASE("views: Save view… under a taken name replaces that view", "[ui][table][state]") +// Window 1 over a RecordingTableStateStore holding views "A" and "B" at revision r0: after a sort change, +// chooseMenu(table, nullopt, {"Views", "Save view…"}), table_view_name "A", table_view_save: one save(views, expected +// r0) → Saved r1; one view "A" with the new sort, two views in all; the status line shows "Saved view A". +``` + +In `tests/net/test_push_tables.cpp`: the publish-then-read flow over a real socket. Gate T2 is held by 14a. + +- [ ] **Step 2: Run to see them fail.** `ctest --test-dir build/cl-debug -R "shared views on a table" --output-on-failure`. Expected: FAIL — no `Publish view…` entry. +- [ ] **Step 3: Implement** the `Views` submenu and its own-view entries, `table_view_dialog` (a taken name saved as a `ReplaceView`), applying a view (fitted, through the handlers where bound, its name written to the state's `view`), the `{name} (modified)` mark, `Saved view {name}`, the default view and `defaultOnMount` at mount; then the shared entries and the publish flow. +- [ ] **Step 4: Run to see them pass**, then `morph_tests`; on Linux `ctest --test-dir build/linux-everything -R "shared views" --output-on-failure`. +- [ ] **Step 5: Mutations, docs, commit.** Each case's named mutation run once. Docs: interpreter.md (the `Views` submenu, applying a view, the default view at mount, shared views) and document.md (the table menu's views). Commit: `feat(ui): saved and shared table views`. + +--- + +## Task 16: A raised sort bound (table.md step 9c) + +**Spec:** "Sort chains" (the bound); Failure modes "A table whose `limits` set `maxSortKeys` above 32" and "A sort key past the table's `maxSortKeys`"; the Tests row "A raised sort bound". Depends only on Task 12. + +A collection's bound is `config.maxSortKeys` in `wireCollectionTable` (8; a collection has no `maxSortKeys` key): +a rule that changes the bound reaches it there too. + +**Files:** +- Modify: `include/morph/table/description.hpp` (`servedDescription`; `table::detail::answerQuery` takes its description from it and answers its `SourceContract`), `table::DescribeTable::invoke` in the same header (the `Table..describe` handler `BRIDGE_REGISTER_TABLE` registers obtains the description through it; `registry.hpp` only names the action type), `src/ui/document.cpp` (`maxSortKeys` on `table`), `src/ui/interpreter.cpp` (the bound the lowering passes to `applySortGesture`: the description's on a model-backed table, the literal on a `rows` table, else 8) +- Test: `tests/table/test_table_description.cpp`, `tests/test_ui_table_model.cpp`, `tests/test_ui_document_rules.cpp` (its `rowsTable` and `modelTable` helpers) +- **Split:** the server half, the document key and its load check are Task 16's; the lowering's bound (`src/ui/interpreter.cpp`) and the `tests/test_ui_table_model.cpp` case below are owned by Task 12c ("Carried from Task 16" there), because the lowering that calls `applySortGesture` is 12c's and did not exist when Task 16 ran. The `test_ui_table_model.cpp` case and the interpreter bound below are kept for reference; 12c writes them. +- Docs: `docs/spec/ui/document.md` (`maxSortKeys`), `docs/spec/core/registry.md` (the bound carried from `limits`) + +**Interfaces:** +- One revision. After this task every server path that names a table's revision takes it from `servedDescription`: `answerQuery` (the page's `revision`), the `describe` handler, and whatever Parts B to F have added by then (the view cache's key, `resolve`). Step 3 ends with `grep -rn "describe(served" include src` listing `servedDescription` alone; a path left on `describe(served.description)` would answer a page whose revision differs from the description's whenever `limits.maxSortKeys` is not 8, and the client would refetch the description on every page. +- Consumes: Task 2's `ServedTable::limits` (`QueryLimits`, whose `maxSortKeys` defaults to 8); Task 1's `TableCapabilities::maxSortKeys`; 12a's `applySortGesture`. +- Produces: `inline constexpr std::size_t kMaxSortKeysBound = 32;` and `[[nodiscard]] std::expected servedDescription(ServedTable const& served)` in `morph::table` — `describe(d)` of a copy `d` of `served.description` with `d.capabilities.maxSortKeys = static_cast(served.limits.maxSortKeys)` (`QueryLimits::maxSortKeys` is a `std::size_t`, the capability a `std::uint32_t`), the bound set before the revision is taken because `capabilities` is part of the canonical JSON `describe` hashes; or `SourceContract` (message ``"a table's `limits.maxSortKeys` is 1 to 32"``) when it is 0 or above `kMaxSortKeysBound`; the document key `maxSortKeys` on `table`: a literal integer 1 to 32, a `rows` table's only (on a model-backed table refused at load with ``"`maxSortKeys` is a `rows` table's; a model's table carries its bound in its description"``; out of range refused with ``"`maxSortKeys` is 1 to 32"``). + +- [ ] **Step 1: Write the failing tests.** In `tests/table/test_table_description.cpp`: + +```cpp +// Mutation: servedDescription leaving capabilities at the default 8. +TEST_CASE("served description: limits carry the sort bound, up to 32", "[table][description]") { + table::ServedTable served{.description = threeColumns()}; + auto const eight = table::servedDescription(served); + REQUIRE(eight); + CHECK(eight->capabilities.maxSortKeys == 8); + CHECK(eight->revision.size() == 16); + CHECK(eight->revision == table::describe(*eight).revision); + served.limits.maxSortKeys = 32; + auto const wide = table::servedDescription(served); + REQUIRE(wide); + CHECK(wide->capabilities.maxSortKeys == 32); + CHECK(wide->revision != eight->revision); // Mutation: the revision taken before the bound is set. + served.limits.maxSortKeys = 33; + CHECK(table::servedDescription(served).error().code == table::TableErrorCode::SourceContract); + served.limits.maxSortKeys = 0; + CHECK(table::servedDescription(served).error().code == table::TableErrorCode::SourceContract); +} +``` + +(`threeColumns()` is a file-local helper returning a `TableDescription` of `id` Integer key, `name` Text and `c3` Decimal, built as this file's Task 1 cases build theirs. `samplesDescription` is not used here: it lives in `tests/ui_table_support.hpp`, the UI harness header of `morph_tests`, and this file is in `morph_table_tests`, which links `morph::morph` and `morph_test_main` only.) + +In the same file, the page's revision: + +```cpp +// Mutation: answerQuery hashing served.description as the model gave it (the page names a revision no describe reply has). +TEST_CASE("served description: a page carries the served description's revision", "[table][description]") +// a ServedTable over a VectorSource of three rows with limits.maxSortKeys = 32, built as this file's Task 2 answerQuery +// cases build theirs: table::detail::answerQuery(served, {})->revision == table::servedDescription(served)->revision; +// with limits.maxSortKeys = 33 answerQuery answers SourceContract. +``` + +In `tests/test_ui_table_model.cpp`: + +```cpp +// Mutation: the client holding 8 whatever the description says. +TEST_CASE("sort chains: a table whose limits set 32 accepts 32 keys from the header and refuses the 33rd", "[ui][table][config]") +// kConfigModelTable over samplesDescription(40) whose capabilities.maxSortKeys is 32: Shift-click 33 sortable headers: t.sort +// has 32 keys, the last page request's sort has 32 keys, status message "A table sorts by at most 32 columns". +// A rows table with "maxSortKeys": 12 over 13 sortable columns: 12 keys, the 13th refused with "…at most 12 columns". +``` + +In `tests/test_ui_document_rules.cpp`: `"ui document rules: table: maxSortKeys is a rows table's literal from 1 to 32"` — `33` refused, `{"ref":"n"}` refused, on a model-backed table refused with the reason above. + +- [ ] **Step 2: Run to see them fail.** `cmake --build --preset cl-debug --target morph_tests morph_table_tests && ctest --test-dir build/cl-debug -R "served description|accepts 32 keys|maxSortKeys is a rows" --output-on-failure`. Expected: compile error for `servedDescription`; the 32-key case stops at 8. +- [ ] **Step 3: Implement** `servedDescription`, call it from `table::detail::answerQuery` and from the `describe` handler (a `SourceContract` answers the request), the document key and the lowering's bound. +- [ ] **Step 4: Run to see them pass**, then `morph_table_tests` and `morph_tests`. +- [ ] **Step 5: Mutations, docs, commit.** Commit: `feat(table): a sort bound up to 32 keys`. + +--- + +## Order within this part + +12a → 12b → 12c → 12e → 12d, with 12f anywhere after 12c (12d's user-formed-group case forms and removes its group through 12e's chooser; each of the three touches the lowering, so they merge one at a time) → 13 → 14a → 14b → 14c. Task 16 needs only 12c and may run beside 13 and 14. All of Task 12 needs Part D's Tasks 9 to 11 (the lowering, the status line, the arrangement); Task 13 needs Tasks 9 and 11; Task 14 needs Task 9's store and model. diff --git a/docs/superpowers/plans/2026-11-17-one-table-f-display-and-acting.md b/docs/superpowers/plans/2026-11-17-one-table-f-display-and-acting.md new file mode 100644 index 000000000..0fc0198ba --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-one-table-f-display-and-acting.md @@ -0,0 +1,1489 @@ +# The One Table, Part F — How a Column Shows Its Cells, and Acting on Rows — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Give every table one formatter of a cell's text (places, rounding, empty text, units, labels, tone, tooltip, locked rows), and let a user act on rows: select the whole view, have the server resolve it, keep changed rows in view, follow a changed key, and see busy, failed and locked rows, with the application's own menu entries and a header it can disable. + +**Architecture:** Task 15 adds `ColumnDisplay` and its companions to the table's description (`include/morph/table/description.hpp`) and one client function, `ui::formatCell`, which every backend, copy, the filter menu and the status line call. Task 17 adds `RowSelection`, `resolve` and the view's membership digest on the server (`include/morph/table/row_selection.hpp`, the view cache), retained rows in the query, the engine and the window, `ChangedRow::from` in the result walk, and the client's busy, failed and locked rows, menus and disabled header in `ui::TableRows` and the interpreter's lowering. + +**Tech Stack:** C++23, glaze, Catch2, the Qt Quick backend (offscreen `morph_qt_quick_tests`), the terminal backend (`morph_tui_tests`). + +**Spec:** `docs/spec/table/table.md` — "How a column shows its cells" (lines 369–455), "Values with units › Display" (2586–2593), "Acting on rows" and all its subsections (2258–2451), the matching rows of "Tests" (3032–3046), "Invariants" 31–35, "Failure modes" (3314–3322), Delivery order steps 9a and 9b (3378–3379), and the 9a/9b rows of "Neighbouring specs" (3345–3355). Roadmap: `docs/superpowers/plans/2026-11-17-one-table.md`, Tasks 15 and 17. + +Part F of 7; index: 2026-11-17-one-table.md + +## Global Constraints + +Every line of the roadmap's Global Constraints applies. Those this part leans on, verbatim: + +- AGENTS.md "Comments and documentation": a comment or spec states what the code does now and why; no history, no issue numbers, no commit hashes. +- Every public symbol has complete Doxygen `@param`/`@tparam`/`@return`; the docs build runs `WARN_AS_ERROR = FAIL_ON_WARNINGS` (`cmake -S . -B build/doc -G Ninja -DMORPH_BUILD_DOCUMENTATION=ON -DMORPH_BUILD_TESTS=OFF -DMORPH_BUILD_EXAMPLES=OFF && cmake --build build/doc --target doc`). +- morph is public: no company, product or customer names in code, tests, specs or commit messages; examples use the neutral `lims` domain. +- Commits are authored `yaraslau ` and end with the session's attribution lines. +- No GUI application is launched by hand or by an agent; Qt Quick behaviour is tested through `morph_qt_quick_tests` (offscreen). +- AGENTS.md "Verify rather than assert": every test names the mutation it was seen to fail on, and the task runs that mutation once and records the failing output in its commit message body. +- Limits, verbatim: `QueryLimits::maxSelectedRows = 1'000'000`, `maxRetained = 10'000`, `maxKeys = 1000`; `SessionOptions::maxCopyRows = 10'000`, `retainHold = 2 s`. +- A spec that describes code takes its part in the task whose step its row names: `docs/spec/ui/document.md` takes "a column's display parts, `tone` and `tooltip`" in Task 15 (step 9a) and "`cellMenu`, `headerMenu`, `retainChanged`, `headerEnabled`" and the element values `selectionSet`, `busyCount`, `selectedCountKind` in Task 17 (step 9b). A backend call this part adds is described in `docs/spec/ui/backend_contract.md` and `docs/spec/qt_quick/backend.md` in the task that adds it. + +**Build and run.** The standard task loop of the roadmap, with: + +```bash +cmake --preset cl-debug # once per tree +cmake --build --preset cl-debug --target morph_tests morph_table_tests +ctest --test-dir build/cl-debug -R "" --output-on-failure + +# Socket cases: morph_net_tests is POSIX-only (index decision 18); on Windows run them in WSL, or leave them to the +# Linux CI leg +cmake --preset linux-everything && cmake --build --preset linux-everything --target morph_net_tests +ctest --preset linux-everything -R "" --output-on-failure + +# Qt Quick and terminal cases (their own tree; offscreen, nothing is launched) +cmake --preset cl-qt-debug -DMORPH_BUILD_QT_QUICK=ON -DMORPH_BUILD_TUI=ON # once per tree +cmake --build build/cl-qt-debug --target morph_qt_quick_tests morph_tui_tests +ctest --test-dir build/cl-qt-debug -R "" --output-on-failure +``` + +**Status line messages.** A transient refusal or notice goes through Part D's `ScreenCore::tableMessage(ElementState& table, std::string text)` (Task 9d, index decision 11; an empty text clears it), and, when it offers a choice ("Run on these"), through the overload `tableMessage(ElementState&, std::string text, std::vector entries)` that Task 17a adds. `ui::StatusEntry{std::string id; std::string label; bool operator==(StatusEntry const&) const = default;}` lives in `view.hpp` beside Part D's `TableStatus` (index decision 38: without the operator `TableStatus`'s defaulted `operator==` is deleted and its `Prop` does not compile), and `TableStatus` gains `std::vector entries` and `std::vector standingEntries`; the lowering keeps each entry's handler in a map keyed by `id`, and the backend reports a choice by `id` (`TableWidget::setOnStatusEntry(std::function)`). **Standing states** are not messages (index decision 19): "Saving n rows", "n rows could not be saved" with "Select them" / "Clear marks", and "n rows shown that no longer match" with "Show only matching rows" are a persistent part of `TableStatus` (`TableStatus::standing`, a `std::string`, with `standingEntries`), recomputed by the lowering from `RowStates::busyCount()`, `failedKeys()` and `counts().retained` whenever one changes; they stay until their source is zero, through the 6-second message hold and the user's gestures. When several hold, `standing` joins them with ". " in the order saving, failed, unmatched. + +**Shared test fixtures from other parts.** `tests/test_ui_table_model.cpp` and `tests/ui_table_support.hpp` are Part D's (Task 9). The harness is `ui::testing::TableHarness` (index decision 42, added by Task 9d), a type of its own in `morph::ui::testing` beside the existing `Harness`, which is not edited: its constructor calls `session.setLocale("en")`, and its catalog is `tableCatalog()` (`corpusCatalog()` plus `Table.samples` and `Table.samples.describe` on `Lims_SampleModel`) plus the actions each later task adds. Its members are Part D's: `h.mount(text)`, `h.settle()`, `h.advance(ms)`, `h.backend` (`RecordingBackend`), `h.dispatcher`, `h.host`, `h.diagnostics`, `h.session`. Every helper is a free function taking the fixture, Part D's among them: `replyDescribe(h)`, `replyPage(h, json)`, `samplesDescription(n)`, `describeJson(description)`, `pageJson(offset, count, total, columns, kind, undecided, awaiting)`, `lastQuery(h)` (the last `TableQuery` sent), `statusOf(h)` (the `TableStatus`; `.message` is the status line's message) and `formatFor(tag)`. A table's widget id, which the `RecordingBackend` drivers take, is `h.backend.find("Table", "testId", "t")`, so this part's table nodes carry `"testId":"t"`. `formatFor` (a `FormatContext` built from the locale table; a default-constructed `FormatContext` has no group separator, `render/locale_format.hpp:108`). Part E (Task 12) adds the `RecordingBackend` drivers `menuOf(table, column)`, `chooseMenu(table, column, labels)`, `moveColumn`, `clickFilter`, `pressCopy(table)` and `clipboardText()`, and the defaulted `HeaderClick` on the existing `clickHeader(int, std::size_t)`; Part D's Task 10a adds `selectTableRange`. Every `column` argument is an index into `Table::columns` (index decision 37). + +**Documents.** Every test mounts a whole document with a `models` block and an alias (index decision 42); a table node names the alias, and the table's record is `Lims_SampleModel.samples`. The test file's `doc(view, mutations = "{}")` returns + +```json +{"vocab":"ui/1","id":"samples","models":{"sample":{"type":"Lims_SampleModel"}},"mutations":,"view":} +``` + +and the sketches below write `h.mount(doc(R"(…)"))` with a node `{"kind":"table","id":"t","testId":"t","model":"sample","table":"samples",…}`. A mutation is `{"model":"sample","action":"","body":{"obj":{…}}}`, as the corpus documents write one (`tests/test_ui_interpreter_commands.cpp:31`). + +**Catalog actions.** A task whose client tests run an action adds it to `TableHarness`'s catalog in that task, before `h.mount`, with its schema text, `effects` and `records` (index decision 42), through `addAction(TableHarness& h, std::string id, std::string schemaJson, ui::ActionInfo info)`. Task 17a adds that helper to `tests/ui_table_support.hpp` with what it needs: a member `std::map, std::less<>> extraActions` on `TableHarness`, which the `Catalog::action` and `Catalog::schema` functions of the harness's catalog (`include/morph/ui/document.hpp:101`) consult before `tableCatalog()`'s own; the session's catalog and `mount`'s are that one catalog. This part's four actions all change the table's record, so the test file has one builder: + +```cpp +// The catalog entry of an action on Lims_SampleModel that declares `updatesTable` on `samples` and returns +// {"rows": ChangedRows}: the held record's keys are at "rows.rows", by the member "key". +morph::ui::ActionInfo samplesAction() { + morph::ui::ActionInfo info; + info.modelType = "Lims_SampleModel"; + info.effects = std::vector{{.kind = "updates", .record = "Lims_SampleModel.samples"}}; + info.records = {morph::ui::ActionRecordInfo{ + .record = "Lims_SampleModel.samples", .keyField = "key", .paths = {"rows.rows"}}}; + return info; +} +// An action whose member `rows` is a RowSelection of the table, and one whose member `row` is a RowRef of it. +inline constexpr std::string_view kSelectionSchema = + R"({"type":"object","properties":{"rows":{"type":"object","x-selectionOf":"Lims_SampleModel.samples"}}})"; +inline constexpr std::string_view kRowSchema = + R"({"type":"object","properties":{"row":{"x-rowOf":"Lims_SampleModel.samples"}}})"; +``` + +| Task | Action | Schema | Mutation in the document | +|---|---|---|---| +| 17a | `Lims_TagRows` | `kSelectionSchema` | `"tag":{"model":"sample","action":"Lims_TagRows","body":{"obj":{"rows":{"ref":"t.selectionSet"}}}}` | +| 17b | `Lims_CloseRows` | `kSelectionSchema` | `"close":{"model":"sample","action":"Lims_CloseRows","body":{"obj":{"rows":{"ref":"t.selectionSet"}}}}` | +| 17c | `Lims_SaveAs` | `kSelectionSchema` | `"save":{"model":"sample","action":"Lims_SaveAs","body":{"obj":{"rows":{"ref":"t.selectionSet"}}}}` | +| 17c | `Lims_TouchRow` | `kRowSchema` | `"touch":{"model":"sample","action":"Lims_TouchRow","body":{"obj":{"row":{"ref":"picked"}}}}` (`picked` a `state` name the test sets) | + +Each is added as `addAction(h, "", std::string{}, samplesAction())`. + +**Helpers this part adds** to `tests/ui_table_support.hpp`, in the task that first calls them, all free functions taking `TableHarness&` (index decisions 20 and 42): `value(json)` (a `ui::Value` from JSON text: `ui::parseJson` then `ui::valueFromJson`, `include/morph/ui/value.hpp:752` and `:570`, both `REQUIRE`d), `elementValue(h, id, name)` (an element value), `reportsOf(h)` (the reasons of `h.diagnostics`), `replyDescribe(h, json)` (an overload answering the describe request with this text; Part D's `replyDescribe(h)` serves `samplesDescription`), `cellText(h, key, column)` and `columnOf(h, id)` (the `ui::TableColumn` given to `setColumns`), `cellAccent(h, key, column)` (the last `setCellAccent` of that cell) — Task 15; `addAction` (above), `fireEvent(h, record, keys)` (a record change event), `runMutation(h, name)`, `settleMutation(h, name, replyJson)`, `refuseMutation(h, name, code)`, and the `RecordingBackend` drivers `selectAll(table)`, `clickRow(table, key)`, `ctrlClickRow(table, key)`, `chooseStatusEntry(table, id)` — Task 17a; `rowMarks(h, key)` (the last `setRowMarks` of that row) — Task 17b; `rightClickCell(table, key, column)` — Task 17d. In a comment-only case `run`, `settle(mutation, …)`, `refuse`, `click`, `ctrlClick` are `runMutation`, `settleMutation`, `refuseMutation`, `clickRow`, `ctrlClickRow`, and `element(id, name)` is `elementValue(h, id, name)`. `tests/net/test_push_tables.cpp` is Part A's (Task 2), with its server-and-client harness; `morph_net_tests` runs on `linux-everything` only (index decision 18). + +## Review Focus + +1. **Negative and boundary values in the display.** `-0.125` at two places under `HalfUp` is `-0.13`, under `HalfEven` `-0.12`; a value that rounds to zero shows no sign (`-0.001` → `0.00`); `0` with `empty` set shows `0`; the `de` locale with grouping shows `-12.500,50`. Test: Task 15, `"format cell: negative halves and empty text"`. +2. **A double whose binary value is below its decimal text.** `1.005` at two places under `HalfUp` is `1.01`, as a person reads the value, though the binary double is 1.00499…. Test: Task 15, `"format cell: a double rounds from its shortest decimal text"`. +3. **A key of `except` that leaves the view.** A view selection of 10 rows less key 3, then an edit takes row 3 out of the view: the count is 9 and exact, not 8. Test: Task 17a, `"view selection: a key of except that leaves the view is dropped from it"`. +4. **A key change onto a key the client already holds.** `ChangedRow{key: 7, from: 3}` while row 7 is held and selected: the selection holds 7 once, and row 3 is fetched again. Test: Task 17c, `"key change: onto a key already held"`. +5. **Two actions over overlapping rows.** Run A names rows {1, 2}, run B rows {2, 3}; A settles: row 2 stays busy until B settles, and `busyCount` is 2 then 0. Test: Task 17c, `"busy rows: overlapping runs"`. + +--- + +## Task 15: How a column shows its cells (table.md step 9a) + +**Spec:** "How a column shows its cells" (369–455); "Values with units › Display" (2586–2593); test rows "A column's display", "Companion columns travel with their column", "Locked rows and companions" (companion half); invariant 32. + +**Files:** +- Modify: `include/morph/table/description.hpp` — `Rounding`, `ValueLabel`, `ColumnDisplay`; `TableColumn::{display, tone, tooltip}`; `TableDescription::{rowTone, rowLock}`; `validateDisplay`, `CompanionOverrides`, `columnsWithCompanions`, `companionColumns`. Glaze meta writing `Rounding` as `"halfEven"` / `"halfUp"`. +- Create: `include/morph/ui/cell_format.hpp` — `CellLook`, `DisplayUnits`, `formatCell`, `cellLook`, `cellOfOperand`, `operandOf`, `distinctTexts`, `headerText`, `headerAccessibleName`. +- Modify: `include/morph/ui/view.hpp` (`ui::TableColumn::unit`, `CellAccent`, `AccentedCell`, `accentedCell`), `include/morph/ui/backend.hpp` (`TableWidget::setCellAccent`), `include/morph/ui/mount.hpp` (binds an accented cell's `accent` in the cell's own scope to `setCellAccent`), `include/morph/ui/testing/recording_backend.hpp` (records each `setCellAccent` and each column's `unit`), `src/qt_quick/table.cpp`, `src/qt_quick/kinds.hpp`, `src/qt_quick/qml/MorphTable.qml`, `src/tui/table_widget.hpp`, `src/tui/table_widget.cpp`. +- Modify: `src/ui/interpreter.cpp` (a column's display parts, `tone`, `tooltip`; the default cell's text through `formatCell`; the companions in the fetched columns; companions out of the layout), `src/ui/document.cpp` (load-time checks of the new parts). +- Create: `tests/test_ui_cell_format.cpp` (add to `morph_tests` in `tests/CMakeLists.txt`, beside `test_ui_table.cpp`). +- Test: `tests/table/test_table_description.cpp`, `tests/test_ui_table_model.cpp`, `tests/qt_quick/test_qt_quick_table.cpp`, `tests/tui/test_tui_table.cpp`. +- Docs: `docs/spec/ui/document.md` (the `table` row: a column's parts `decimals`, `rounding`, `padPlaces`, `grouping`, `empty`, `unit`, `date`, `labels`, `tone`, `tooltip`), `docs/spec/ui/backend_contract.md` and `docs/spec/qt_quick/backend.md` (`setCellAccent`, a column's `unit`). + +**Interfaces:** +- Consumes: `table::TableColumn`, `TableDescription`, `describe` (Task 1); `table::Unloaded`, `ColumnInfo::level` (Task 3); `DistinctValue{text, operand, count}` (Task 8a); `table::UnitInfo` (qualified in `ui` code: `ui::UnitInfo` already exists in `expression.hpp`), `UnitId`, `UnitRegistry`, `UnitRegistryBuilder`, `Measure`, `ColumnKind::Measure` (Task 8c); `ui::FormatContext` (`include/morph/ui/expression.hpp:325`), `ui::localeFacts`, `ui::withoutGrouping` (`include/morph/ui/locale_table.hpp`); `render::formatCanonicalNumber` (`include/morph/render/locale_format.hpp:708`); `math::checkedRoundToDecimalPlaces`, `math::RoundingMode` (`include/morph/util/rational.hpp`); `table::parseDecimal`, `table::displayText` (`include/morph/table/data_source.hpp`); `ui::formatDate(std::string_view pattern, time::DateTime local, std::int32_t offsetMinutes)` (`include/morph/ui/date_pattern.hpp:327`, in `morph::ui`, not `detail`); Task 9d's `TableSource::cellView` and `setCellLoad`, and Task 9's `formatFor` test helper; Task 9's `WindowRows`, its fetched-column set, and `ui::detail::standInCellText`; Part E's copy (`ui::copyText`, `IViewBackend::copyText`, Task 12f), values list (`table_filter_value_`, Task 12d) and column chooser (`table_columns`, Task 12e). +- Produces (later tasks and Part G's editing rely on these exact names): + +```cpp +namespace morph::table { +enum class Rounding : std::uint8_t { HalfEven, HalfUp }; // JSON "halfEven", "halfUp" +// Both declare operator== (index decision 38): TableColumn's and TableDescription's defaulted operator== cover +// them, and are deleted without it. +struct ValueLabel { + std::string operand; + std::string text; + [[nodiscard]] bool operator==(ValueLabel const&) const = default; +}; +struct ColumnDisplay { + std::optional decimals; + Rounding rounding = Rounding::HalfEven; + bool padPlaces = true; + bool grouping = false; + std::string empty; + std::string unit; + std::string date; + std::vector labels; + [[nodiscard]] bool operator==(ColumnDisplay const&) const = default; +}; +// TableColumn gains: ColumnDisplay display; std::string tone; std::string tooltip; +// TableDescription gains: std::string rowTone; std::string rowLock; +[[nodiscard]] std::expected validateDisplay(TableDescription const& description); +struct CompanionOverrides { + std::set> tone; // column ids whose document part gives `tone` + std::set> tooltip; // column ids whose document part gives `tooltip` + bool rowTone = false; // the node gives `rowTone` +}; +[[nodiscard]] std::vector columnsWithCompanions(TableDescription const& description, + std::span columns, + CompanionOverrides const& overrides = {}); +[[nodiscard]] std::vector companionColumns(TableDescription const& description); // sorted +} // namespace morph::table + +namespace morph::ui { +enum class CellLook : std::uint8_t { Text, Empty, Unloaded, Invalid }; +struct DisplayUnits { + table::UnitRegistry const* units = nullptr; // not owned; null: a Measure cell is Invalid + std::map> byDimension; // dimension -> unit id the user chose +}; +[[nodiscard]] std::string formatCell(table::Cell const& cell, table::TableColumn const& column, + FormatContext const& locale, DisplayUnits const& units = {}); +[[nodiscard]] CellLook cellLook(table::Cell const& cell, table::TableColumn const& column, + DisplayUnits const& units = {}); +[[nodiscard]] table::Cell cellOfOperand(std::string_view operand, table::TableColumn const& column, + DisplayUnits const& units = {}); +[[nodiscard]] std::optional operandOf(table::Cell const& cell, table::TableColumn const& column, + DisplayUnits const& units = {}); +[[nodiscard]] std::vector distinctTexts(std::span values, + table::TableColumn const& column, FormatContext const& locale, + DisplayUnits const& units = {}); +[[nodiscard]] std::string headerText(std::string_view label, std::string_view unit); // "Mass [kg]" +[[nodiscard]] std::string headerAccessibleName(std::string_view label, std::string_view unit); // "Mass, kg" +// view.hpp. What a cell shows beside its text (index decision 39). `invalid`: the value could not be read as the +// column's kind; the backend draws its error mark and `tooltip` is "The value could not be read". +struct CellAccent { + std::optional tone; + std::string tooltip; + bool invalid = false; + [[nodiscard]] bool operator==(CellAccent const&) const = default; +}; +// A cell with an accent: a node a `TableSource::cellView` returns (or a cell of a `TableRowView`). Anywhere but a +// table cell it mounts its content and the accent is not read. +struct AccentedCell { Node content; Prop accent; }; +[[nodiscard]] Node accentedCell(Node content, Prop accent); +// ui::TableColumn (view.hpp) gains: std::string unit; +// TableWidget (backend.hpp) gains, with a default that does nothing, as `setCellLoad` has: +// virtual void setCellAccent(Widget& row, std::size_t column, CellAccent const& accent); +// // `column`: an index into `Table::columns` (index decision 37) +} // namespace morph::ui +``` + +**Cells, not rows, carry the accent** (index decisions 28 and 39). A table mounted through `TableSource` builds no `TableRowView`; `TableRowView` stays the C++ `table()` path's only and gains nothing here. The lowering's `cellView(column, rowSignal)` returns `accentedCell(content, accent)`; Part G's Task 19 wraps that as `markedCell(accentedCell(content, accent), marks)`, and the mount unwraps a `MarkedCell` first, then an `AccentedCell`, then mounts `content`. The mount binds `accent` in the cell's own scope and calls `setCellAccent(row, column, accent)` after the row's key, on every change, and whenever a pooled cell is attached to another row widget (Task 10a), whether or not the accent changed; a pooled cell rebound to another row (its signal set) re-evaluates its accent with its content. + +The third parameter is the session's `ui::FormatContext`, as table.md ("Where it is formatted") names it: the session's formatting (numeric facts, date patterns, display zone), and it is what the existing default cell (`textOf(*value, scope->formatting())`, `src/ui/interpreter.cpp`) formats with. `DisplayUnits` carries what a `Measure` cell needs and the three-argument call does not have. + +- [ ] **Step 1: Write the failing description tests** in `tests/table/test_table_description.cpp` + +```cpp +TEST_CASE("description: a column's display is refused where it cannot apply", "[table][description][display]") { + using namespace morph::table; + auto base = [] { + TableDescription d; + d.id = "samples"; + d.key = "id"; + d.columns = { + TableColumn{.info = {.id = "id", .kind = ColumnKind::Integer}, .label = "Id"}, + TableColumn{.info = {.id = "mass", .kind = ColumnKind::Decimal}, .label = "Mass", + .display = {.decimals = 2, .unit = "kg"}, .tone = "massTone", .tooltip = "massTip"}, + TableColumn{.info = {.id = "amount", .kind = ColumnKind::Measure}, .label = "Amount"}, + TableColumn{.info = {.id = "massTone", .kind = ColumnKind::Text}, .shown = false}, + TableColumn{.info = {.id = "massTip", .kind = ColumnKind::Text}, .shown = false}, + TableColumn{.info = {.id = "lockedBy", .kind = ColumnKind::Text}, .shown = false}, + }; + d.rowLock = "lockedBy"; + return d; + }; + REQUIRE(validateDisplay(base()).has_value()); + + auto measureDecimals = base(); + measureDecimals.columns[2].display.decimals = 3; + CHECK(validateDisplay(measureDecimals).error().code == TableErrorCode::SourceContract); + auto measureUnit = base(); + measureUnit.columns[2].display.unit = "kg"; + CHECK(validateDisplay(measureUnit).error().code == TableErrorCode::SourceContract); + auto missingTone = base(); + missingTone.columns[1].tone = "nope"; + CHECK(validateDisplay(missingTone).error().code == TableErrorCode::SourceContract); + auto numericTooltip = base(); + numericTooltip.columns[1].tooltip = "id"; + CHECK(validateDisplay(numericTooltip).error().code == TableErrorCode::SourceContract); + auto missingLock = base(); + missingLock.rowLock = "nope"; + CHECK(validateDisplay(missingLock).error().code == TableErrorCode::SourceContract); + CHECK(validateDisplay(missingLock).error().column == "nope"); +} +// Mutation: validateDisplay skipping rowLock, which accepts `missingLock`. + +TEST_CASE("description: companions travel with their column", "[table][description][display]") { + using namespace morph::table; + TableDescription d; // id, mass (tone massTone, tooltip massTip), name; rowTone rowState; rowLock lockedBy + d.key = "id"; + d.columns = { + TableColumn{.info = {.id = "id", .kind = ColumnKind::Integer}}, + TableColumn{.info = {.id = "mass", .kind = ColumnKind::Decimal}, .tone = "massTone", .tooltip = "massTip"}, + TableColumn{.info = {.id = "name", .kind = ColumnKind::Text}}, + TableColumn{.info = {.id = "massTone", .kind = ColumnKind::Text}, .shown = false}, + TableColumn{.info = {.id = "massTip", .kind = ColumnKind::Text}, .shown = false}, + TableColumn{.info = {.id = "rowState", .kind = ColumnKind::Text}, .shown = false}, + TableColumn{.info = {.id = "lockedBy", .kind = ColumnKind::Text}, .shown = false}, + }; + d.rowTone = "rowState"; + d.rowLock = "lockedBy"; + std::vector const mass{"mass"}; + std::vector const name{"name"}; + CHECK(columnsWithCompanions(d, mass) == + std::vector{"mass", "massTone", "massTip", "rowState", "lockedBy"}); + CHECK(columnsWithCompanions(d, name) == std::vector{"name", "rowState", "lockedBy"}); + CHECK(columnsWithCompanions(d, mass, {.tone = {"mass"}, .tooltip = {}, .rowTone = true}) == + std::vector{"mass", "massTip", "lockedBy"}); + CHECK(companionColumns(d) == std::vector{"lockedBy", "massTip", "massTone", "rowState"}); +} +// Mutation: companions added for every column of the description, which puts massTone in `name`'s list. + +TEST_CASE("description: a display travels in the description and changes its revision", + "[table][description][display]") { + // A description whose `mass` column has display {decimals 2, rounding HalfUp, labels [{"3","three"}]}: + // its JSON holds "rounding":"halfUp" and "labels":[{"operand":"3","text":"three"}]; it reads back equal; + // its revision differs from the same description with rounding HalfEven. +} +// Mutation: `Rounding` without glaze meta, which writes 1 for "halfUp". + +TEST_CASE("description: a served table with a bad companion is refused", "[table][description][display]") { + using namespace morph::table; + auto const source = tabletest::makeSource({tabletest::col("id", ColumnKind::Integer)}, {{Cell{std::int64_t{1}}}}); + TableDescription d; + d.id = "samples"; + d.key = "id"; + d.columns = {TableColumn{.info = {.id = "id", .kind = ColumnKind::Integer}, .label = "Id"}}; + ServedTable good{.description = d, .source = source, .levels = {}, .mayRead = {}, .scope = {}, .services = {}, + .limits = {}}; + REQUIRE(detail::answerQuery(detail::pinned(good), TableQuery{}).has_value()); + ServedTable bad = good; + bad.description.rowLock = "nope"; + auto const refused = detail::answerQuery(detail::pinned(bad), TableQuery{}); + REQUIRE_FALSE(refused.has_value()); + CHECK(refused.error().code == TableErrorCode::SourceContract); + CHECK(refused.error().column == "nope"); +} +// Mutation: the validateDisplay call removed from answerQuery, which answers the query for `bad`. +``` + +Write the third case's assertions as the comment states (`CHECK(json.find("\"rounding\":\"halfUp\"") != npos)`, a read-back `==`, two `describe` revisions `!=`). The fourth is what shows `validateDisplay` is called: the first two pass with a `validateDisplay` no serving path ever reaches. + +- [ ] **Step 2: Run them; they fail to compile** (`validateDisplay`, `TableColumn::display` not declared). + +Run: `cmake --build --preset cl-debug --target morph_table_tests` +Expected: compile errors naming `validateDisplay` and `display`. + +- [ ] **Step 3: Implement the description additions** in `include/morph/table/description.hpp` with the Interfaces block's signatures. + - `validateDisplay` returns `TableError{.code = SourceContract, .column = }` for: `decimals` or `unit` set on a `Measure` column (column = that column); a `tone`, `tooltip`, `rowTone` or `rowLock` that names no column, or names a column whose kind is not `Text` (column = the named id). + - Call `validateDisplay(served.description)` first in `detail::answerQuery` (before `validate`; its error is the query's), and in `DescribeTable::invoke` beside the check that refuses a `rowScoped` table with an empty `scope` as `SourceContract` (Task 2; grep `SourceContract` in `include/morph/core/registry.hpp` and `description.hpp`), where it is refused the way that check refuses. + - `columnsWithCompanions`: for each id of `columns` in order, the id, then its `tone` companion unless `overrides.tone` holds the id, then its `tooltip` companion unless `overrides.tooltip` holds it; then `rowTone` unless `overrides.rowTone`; then `rowLock`. Empty names are skipped; an id already listed is not listed again. `rowLock` travels with every row as `rowTone` does: a locked row cannot be drawn without it. + - `companionColumns`: every non-empty `tone`, `tooltip`, `rowTone` and `rowLock` name, sorted, without duplicates. + +- [ ] **Step 4: Run them; they pass.** + +Run: `ctest --test-dir build/cl-debug -R "description:" --output-on-failure` +Expected: all `description:` cases pass. + +- [ ] **Step 5: Write the failing formatter tests** in `tests/test_ui_cell_format.cpp` (add the file to `morph_tests`) + +```cpp +namespace { +using morph::table::Cell; +using morph::table::ColumnKind; +using morph::table::Rounding; +using morph::table::TableColumn; + +morph::math::Rational dec(std::string_view text) { return morph::table::parseDecimal(text).value(); } +TableColumn numeric(ColumnKind kind, morph::table::ColumnDisplay display) { + return TableColumn{.info = {.id = "v", .kind = kind}, .label = "V", .display = std::move(display)}; +} +// Part D's formatFor (tests/ui_table_support.hpp) fills the separators and patterns from the locale table. A +// default-constructed FormatContext has no group separator, so `{}` would show 12500 for a grouped column. +morph::ui::FormatContext en() { return formatFor("en"); } // "," groups, "." decimal, ISO dates +morph::ui::FormatContext de() { return formatFor("de"); } // "." groups, "," decimal, dd.MM.yyyy +} // namespace + +TEST_CASE("format cell: a column's places and rounding", "[ui][cell_format]") { + using morph::ui::formatCell; + CHECK(formatCell(Cell{dec("0.125")}, numeric(ColumnKind::Decimal, {.decimals = 2}), en()) == "0.12"); + CHECK(formatCell(Cell{dec("0.125")}, + numeric(ColumnKind::Decimal, {.decimals = 2, .rounding = Rounding::HalfUp}), en()) == "0.13"); + CHECK(formatCell(Cell{dec("1.5")}, numeric(ColumnKind::Decimal, {.decimals = 2}), en()) == "1.50"); + CHECK(formatCell(Cell{dec("1.5")}, numeric(ColumnKind::Decimal, {.decimals = 2, .padPlaces = false}), en()) == + "1.5"); + CHECK(formatCell(Cell{dec("2")}, numeric(ColumnKind::Decimal, {.decimals = 2, .padPlaces = false}), en()) == + "2"); + CHECK(formatCell(Cell{std::int64_t{5}}, numeric(ColumnKind::Integer, {.decimals = 2}), en()) == "5.00"); + CHECK(formatCell(Cell{dec("12.50")}, numeric(ColumnKind::Decimal, {}), en()) == "12.50"); // own places + CHECK(formatCell(Cell{0.1}, numeric(ColumnKind::Number, {}), en()) == "0.1"); // shortest + CHECK(formatCell(Cell{std::int64_t{12500}}, numeric(ColumnKind::Integer, {.grouping = true}), en()) == + "12,500"); + CHECK(formatCell(Cell{std::int64_t{12500}}, numeric(ColumnKind::Integer, {}), en()) == "12500"); +} +// Mutation: `rounding` ignored (always HalfEven), which shows "0.12" under HalfUp. + +TEST_CASE("format cell: negative halves and empty text", "[ui][cell_format][review]") { + using morph::ui::formatCell; + auto const halfUp = numeric(ColumnKind::Decimal, {.decimals = 2, .rounding = Rounding::HalfUp, .empty = "–"}); + auto const halfEven = numeric(ColumnKind::Decimal, {.decimals = 2, .empty = "–"}); + CHECK(formatCell(Cell{dec("-0.125")}, halfUp, en()) == "-0.13"); + CHECK(formatCell(Cell{dec("-0.125")}, halfEven, en()) == "-0.12"); + CHECK(formatCell(Cell{dec("-0.001")}, halfEven, en()) == "0.00"); // zero shows no sign + CHECK(formatCell(Cell{std::int64_t{0}}, numeric(ColumnKind::Integer, {.empty = "–"}), en()) == "0"); + CHECK(formatCell(Cell{std::monostate{}}, halfEven, en()) == "–"); + CHECK(formatCell(Cell{std::monostate{}}, numeric(ColumnKind::Decimal, {}), en()).empty()); + CHECK(formatCell(Cell{dec("-12500.5")}, numeric(ColumnKind::Decimal, {.decimals = 2, .grouping = true}), de()) == + "-12.500,50"); + CHECK(formatCell(Cell{dec("-12500.5")}, numeric(ColumnKind::Decimal, {.decimals = 2}), de()) == "-12500,50"); +} +// Mutation: a zero value shown as `empty`, which gives "–" for 0. + +TEST_CASE("format cell: a double rounds from its shortest decimal text", "[ui][cell_format][review]") { + using morph::ui::formatCell; + auto const halfUp = numeric(ColumnKind::Number, {.decimals = 2, .rounding = Rounding::HalfUp}); + CHECK(formatCell(Cell{1.005}, halfUp, en()) == "1.01"); + CHECK(formatCell(Cell{2.675}, halfUp, en()) == "2.68"); + CHECK(formatCell(Cell{0.125}, numeric(ColumnKind::Number, {.decimals = 2}), en()) == "0.12"); + CHECK(formatCell(Cell{1e21}, numeric(ColumnKind::Number, {}), en()) == "1000000000000000000000"); +} +// Mutation: std::format("{:.2f}") on the binary value, which gives "1.00" for 1.005. + +TEST_CASE("format cell: labels, dates, quantities and measures", "[ui][cell_format]") { + using morph::ui::formatCell; + auto const available = TableColumn{ + .info = {.id = "ok", .kind = ColumnKind::Bool}, + .display = {.labels = {{.operand = "true", .text = "available"}, {.operand = "false", .text = "not available"}}}}; + CHECK(formatCell(Cell{true}, available, en()) == "available"); + CHECK(formatCell(Cell{false}, available, en()) == "not available"); + auto const coded = numeric(ColumnKind::Integer, {.labels = {{.operand = "3", .text = "three"}}}); + CHECK(formatCell(Cell{std::int64_t{3}}, coded, en()) == "three"); + CHECK(formatCell(Cell{std::int64_t{4}}, coded, en()) == "4"); + + auto const date = TableColumn{.info = {.id = "d", .kind = ColumnKind::Date}}; + CHECK(formatCell(Cell{std::int64_t{20'000}}, date, en()) == "2024-10-04"); + CHECK(formatCell(Cell{std::int64_t{20'000}}, date, de()) == "04.10.2024"); + auto const patterned = TableColumn{.info = {.id = "d", .kind = ColumnKind::Date}, .display = {.date = "dd-MMM-yyyy"}}; + CHECK(formatCell(Cell{std::int64_t{20'000}}, patterned, de()) == "04-Oct-2024"); + + auto const grams = morph::table::QuantityCell{.amount = dec("250"), .toCanonical = dec("0.001")}; + CHECK(formatCell(Cell{grams}, numeric(ColumnKind::Quantity, {.decimals = 3}), en()) == "0.250"); + + morph::table::UnitRegistryBuilder builder; + REQUIRE(builder.add({.id = "kg", .symbol = "kg", .dimension = "mass", .toBase = dec("1"), .decimals = 3})); + REQUIRE(builder.add({.id = "g", .symbol = "g", .dimension = "mass", .toBase = dec("0.001"), .decimals = 0})); + auto const registry = std::move(builder).build(); + morph::ui::DisplayUnits const units{.units = registry.get(), .byDimension = {}}; + auto const amount = TableColumn{.info = {.id = "amount", .kind = ColumnKind::Measure}}; + auto const kg = *registry->find("kg"); + auto const g = *registry->find("g"); + CHECK(formatCell(Cell{morph::table::Measure{.amount = dec("0.3"), .unit = kg}}, amount, en(), units) == "0.300 kg"); + CHECK(formatCell(Cell{morph::table::Measure{.amount = dec("200"), .unit = g}}, amount, en(), units) == "200 g"); + CHECK(formatCell(Cell{morph::table::Measure{.amount = dec("1.2345"), .unit = kg}}, amount, en(), units) == + "1.234 kg"); + morph::ui::DisplayUnits const inKg{.units = registry.get(), .byDimension = {{"mass", "kg"}}}; + CHECK(formatCell(Cell{morph::table::Measure{.amount = dec("200"), .unit = g}}, amount, en(), inKg) == "0.200 kg"); +} +// Mutation: a Measure shown at the column's `decimals` instead of its unit's, which gives "0.3 kg". + +TEST_CASE("format cell: empty, unloaded and invalid differ", "[ui][cell_format]") { + using morph::ui::CellLook; + using morph::ui::cellLook; + auto const integer = numeric(ColumnKind::Integer, {.empty = "–"}); + CHECK(cellLook(Cell{std::monostate{}}, integer) == CellLook::Empty); + CHECK(cellLook(Cell{morph::table::Unloaded{}}, integer) == CellLook::Unloaded); + CHECK(morph::ui::formatCell(Cell{morph::table::Unloaded{}}, integer, en()).empty()); + CHECK(cellLook(Cell{std::string{"abc"}}, integer) == CellLook::Invalid); + CHECK(morph::ui::formatCell(Cell{std::string{"abc"}}, integer, en()).empty()); + CHECK(cellLook(Cell{std::string{"12"}}, integer) == CellLook::Text); + CHECK(morph::ui::formatCell(Cell{std::string{"12"}}, numeric(ColumnKind::Integer, {.decimals = 1}), en()) == + "12.0"); + auto const amount = TableColumn{.info = {.id = "amount", .kind = ColumnKind::Measure}}; + CHECK(cellLook(Cell{morph::table::Measure{.amount = dec("1"), .unit = morph::table::kUnknownUnit}}, amount) == CellLook::Invalid); +} +// Mutation: `empty` shown for an unloaded cell, which gives "–". + +TEST_CASE("format cell: values that show alike keep their places in the values list", "[ui][cell_format]") { + std::vector const values{ + {.text = {}, .operand = "0.124", .count = 1}, + {.text = {}, .operand = "0.123", .count = 2}, + {.text = {}, .operand = "0.5", .count = 1}, + }; + CHECK(morph::ui::distinctTexts(values, numeric(ColumnKind::Decimal, {.decimals = 2}), en()) == + std::vector{"0.124", "0.123", "0.50"}); + CHECK(morph::ui::operandOf(Cell{dec("0.125")}, numeric(ColumnKind::Decimal, {.decimals = 2})) == "0.125"); + CHECK(morph::ui::operandOf(Cell{true}, TableColumn{.info = {.id = "b", .kind = ColumnKind::Bool}}) == "true"); + CHECK_FALSE(morph::ui::operandOf(Cell{std::monostate{}}, numeric(ColumnKind::Integer, {})).has_value()); + CHECK_FALSE(morph::ui::operandOf(Cell{morph::table::Unloaded{}}, numeric(ColumnKind::Integer, {})).has_value()); + CHECK(morph::ui::headerText("Mass", "kg") == "Mass [kg]"); + CHECK(morph::ui::headerText("Mass", "") == "Mass"); + CHECK(morph::ui::headerAccessibleName("Mass", "kg") == "Mass, kg"); +} +// Mutation: the values list formatting every entry by `decimals`, which shows "0.12" twice. +``` + +`UnitRegistryBuilder::add(UnitInfo) -> std::expected`, `build() &&`, `UnitRegistry::find` and `kUnknownUnit` are Task 8c's (Part C). `formatFor(tag)` is Part D's (Task 9a, `tests/ui_table_support.hpp`); when this task lands before Task 9, it adds the header with that one function, written as Part D writes it (`LocaleFacts const& f = ui::localeFacts(tag);` then `FormatContext{.locale = std::string{tag}, .numeric = f.numeric, .currency = f.currency, .datePattern = std::string{f.datePattern}, .dateTimePattern = std::string{f.dateTimePattern}}`), and Task 9 extends the file. + +`DisplayUnits::units` is not owned. Part C's `table::registryOf(description)` returns `std::expected, TableError>`; the lowering calls it once per description revision and keeps the `shared_ptr` beside the table's description for as long as that revision is held, handing `registry.get()` to every `DisplayUnits` it builds. When `registryOf` fails, the lowering reports the error once for the table and passes `units = nullptr`, under which a `Measure` cell is `Invalid`. `byDimension` is the column's entry of Task 8d's `ColumnLayoutValue::units`. + +- [ ] **Step 6: Run them; they fail to compile** (`morph/ui/cell_format.hpp` missing). + +Run: `cmake --build --preset cl-debug --target morph_tests` +Expected: `cannot open include file 'morph/ui/cell_format.hpp'`. + +- [ ] **Step 7: Implement `include/morph/ui/cell_format.hpp`** with the Interfaces block's signatures. The rules the tests do not fix: + - **The number path.** Every numeric cell becomes canonical decimal text (`-?digits(.digits)?`), is rounded on that text, then written by `render::formatCanonicalNumber` with `locale.numeric` when `display.grouping`, else `ui::withoutGrouping(locale.numeric)`. A `Rational` with `decimals` set rounds exactly with `math::checkedRoundToDecimalPlaces(value, DecimalPlaces{d}, mode)` (`HalfUp` → `RoundingMode::HalfAwayFromZero`), a failed round is `CellLook::Invalid`; without `decimals` it keeps its declared places (`units::detail::formatRationalDecimal`). A `double` is written with `std::to_chars(…, std::chars_format::fixed)` (its shortest round-trip text), then rounded as text. An `int64` is its digits. A `QuantityCell` is `amount × toCanonical`, multiplied with checked arithmetic (an overflow is `Invalid`). + - **Rounding text** (one private helper, used for `double` and padding): keep `d` fraction digits; the dropped tail decides: above half rounds the magnitude up, below keeps it, exactly half rounds up under `HalfUp` and to the even last kept digit under `HalfEven`. Then `padPlaces` pads to `d` digits, or else trailing zeros and a bare point are removed. A result whose digits are all zero has no sign. + - **Order of decisions.** `Unloaded` → `""`. `std::monostate` → `display.empty`. A `std::string` in an `Integer`, `Key`, `Decimal`, `Quantity`, `Number` or `Bool` column is read for the kind (`std::from_chars`, `table::parseDecimal`, `"true"`/`"false"`); text that does not read is `Invalid` and shows `""`; text that reads is formatted as the value it reads as. A string in a `Date`, `DateTime`, `Text` or `Custom` column shows as it is. Then `labels`: the first label whose `operand` equals `operandOf(cell)` gives the text (a `Decimal` or `Number` operand is compared by value: `"3"` matches 3.0). Then the kind's own text. + - **Dates.** `Date` is days since 1970-01-01, `DateTime` UTC seconds shifted by `locale.utcOffsetMinutes`; the pattern is `display.date`, else `locale.datePattern` / `locale.dateTimePattern`, else ISO (`2024-10-04`, `2024-10-04 08:30`); written by `ui::formatDate(pattern, local, locale.utcOffsetMinutes)`, `local` being the `time::DateTime` of the days (at midnight) or of the shifted seconds. An empty result (a pattern `checkDatePattern` refuses) falls back to ISO. + - **Measures.** The unit's `decimals` and `symbol` from `units.units`; with `units.byDimension` naming a unit of the cell's dimension, the amount is converted exactly (`amount × from.toBase / to.toBase`) and rounded `HalfEven` to that unit's decimals. Text is the number, one ASCII space, the symbol; the ratio unit (`""`) writes no space and no symbol. No registry, or a unit the registry does not know, is `Invalid`. + - `operandOf`: `int64` → its digits; `Rational` → `formatRationalDecimal` at its own places; `double` → shortest round-trip text; `bool` → `"true"`/`"false"`; `std::string` → itself; `QuantityCell` → its canonical amount; `Measure` → amount, a space, the unit's id; empty, unloaded and invalid → `std::nullopt`. `cellOfOperand` is its inverse for the column's kind. + - `distinctTexts`: each operand is read with `cellOfOperand` and formatted; when two entries' texts are equal, each of those entries is formatted again with `display.decimals` cleared (its own places). + +- [ ] **Step 8: Run them; they pass.** + +Run: `ctest --test-dir build/cl-debug -R "format cell:" --output-on-failure` +Expected: 6 test cases pass. + +- [ ] **Step 9: Write the failing lowering tests** in `tests/test_ui_table_model.cpp`. Each mounts a model-backed table over `companionDescription()`: the columns `id` (Integer, key), `mass` (Decimal, `display = {decimals 2, rounding HalfUp, unit "kg"}`, `tone = "massTone"`, `tooltip = "massTip"`), `name` (Text), `count` (Integer), the companions `massTone`, `massTip` and `lockedBy` (Text, `shown: false`) and `rowLock = "lockedBy"`. `kCompanionPage` is the page JSON of one row, written in the test with the description's revision: `{id 1, mass 0.125, name "A", count "abc", massTone "warn", massTip "Above limit", lockedBy ""}` (`count` holds text, an invalid cell). `kTable` is the node `{"kind":"table","id":"t","testId":"t","model":"sample","table":"samples"}`. + +```cpp +using morph::ui::testing::TableHarness; + +TEST_CASE("table display: a model-backed table draws its description's display", "[ui][table][display]") { + TableHarness h; + h.mount(doc(kTable)); + replyDescribe(h, describeJson(companionDescription())); + replyPage(h, kCompanionPage); + CHECK(cellText(h, 1, "mass") == "0.13"); + CHECK(cellAccent(h, 1, "mass") == + morph::ui::CellAccent{.tone = morph::ui::Tone::Warn, .tooltip = "Above limit", .invalid = false}); + CHECK(cellAccent(h, 1, "name") == morph::ui::CellAccent{}); + CHECK(columnOf(h, "mass").unit == "kg"); +} +// Mutation: the default cell's text left on the stand-in formatter, which shows "0.125". + +TEST_CASE("table display: an invalid cell draws its mark and no text", "[ui][table][display]") { + TableHarness h; + h.mount(doc(kTable)); + replyDescribe(h, describeJson(companionDescription())); + replyPage(h, kCompanionPage); + CHECK(cellText(h, 1, "count").empty()); + CHECK(cellAccent(h, 1, "count") == + morph::ui::CellAccent{.tone = std::nullopt, .tooltip = "The value could not be read", .invalid = true}); + CHECK_FALSE(cellAccent(h, 1, "mass").invalid); +} +// Mutation: the accent built from the companions only (cellLook not read), which leaves `invalid` false. + +TEST_CASE("table display: companions are fetched with their column only", "[ui][table][display]") { + { + TableHarness h; + h.mount(doc(R"({"kind":"table","id":"t","model":"sample","table":"samples","columns":[{"id":"name"}]})")); + replyDescribe(h, describeJson(companionDescription())); + CHECK(lastQuery(h).columns == std::vector{"id", "name", "lockedBy"}); + } + { + TableHarness h; + h.mount(doc(R"({"kind":"table","id":"t","model":"sample","table":"samples", + "columns":[{"id":"mass","tone":{"lit":"ok"}}]})")); + replyDescribe(h, describeJson(companionDescription())); + CHECK(lastQuery(h).columns == std::vector{"id", "mass", "massTip", "lockedBy"}); + replyPage(h, kCompanionPage); + CHECK(cellAccent(h, 1, "mass").tone == morph::ui::Tone::Ok); // the document's, not the companion's "warn" + } +} +// Mutation: companions fetched for every described column, which puts massTone in the first query. + +TEST_CASE("table display: companion columns are not arranged", "[ui][table][display]") { + TableHarness h; + h.mount(doc(kTable)); + replyDescribe(h, describeJson(companionDescription())); + replyPage(h, kCompanionPage); + CHECK(elementValue(h, "t", "visibleColumns") == value(R"(["id","mass","name","count"])")); + CHECK(elementValue(h, "t", "hiddenCount") == morph::ui::Value{std::int64_t{0}}); + // Part E's column chooser (`Columns…`, dialog `table_columns`) has table_columns_show_id, _mass, _name and + // _count, and no table_columns_show_massTone, _massTip or _lockedBy. +} +// Mutation: the chooser listing every column of the description, which lists table_columns_show_massTone. + +TEST_CASE("table display: a document's parts override the description", "[ui][table][display]") { + TableHarness h; + h.mount(doc(R"({"kind":"table","id":"t","model":"sample","table":"samples", + "columns":[{"id":"mass","decimals":1,"rounding":"halfEven","empty":"n/a"}]})")); + replyDescribe(h, describeJson(companionDescription())); + replyPage(h, kCompanionPage); + CHECK(cellText(h, 1, "mass") == "0.1"); +} +// Mutation: document parts read only on a `rows` table, which keeps "0.13". + +TEST_CASE("table display: an unknown tone is reported once for its column", "[ui][table][display]") { + // Two rows whose massTone is "purple": cellAccent(h, key, "mass").tone is empty for both, and `reportsOf(h)` + // holds exactly one entry, "column `mass`'s tone is \"purple\"; a tone is neutral, info, ok, warn or err". +} +// Mutation: reporting per row, which reports twice. + +TEST_CASE("table display: copy writes the shown text and the header with its unit", "[ui][table][display]") { + // A node with "selectionMode":"multiple" and "columns":[{"id":"id"},{"id":"mass"},{"id":"name"}]; select row 1, + // "Copy with headers": clipboardText() == "Id\tMass [kg]\tName\n1\t0.13\tA". +} +// Mutation: copy writing displayText, which writes 0.125. + +TEST_CASE("table display: text never orders", "[ui][table][display]") { + // A `rows` table over [{id:1, v:10}, {id:2, v:9}] with column v {"decimals":2,"sortable":true}, sorted asc: + // cellText reads "9.00" then "10.00" by view row. With the node's `filters` on v `eq "0.13"` (the literal shape + // Task 9d's `filters` key reads) over a row {v: 0.125} shown as "0.13" (decimals 2, rounding halfUp): + // elementValue(h, "t", "viewCount") == 0. A Bool column labelled "available"/"not available", sorted asc: the + // row with false comes first. +} +// Mutation: a sort over the formatted text, which orders "10.00" before "9.00". +``` + +`companionDescription()` is a function in the test file returning the `TableDescription` above; every case answers the describe request with it through `replyDescribe(h, json)`. Write the commented cases' assertions exactly as stated. + +- [ ] **Step 10: Write the failing backend tests.** In `tests/qt_quick/test_qt_quick_table.cpp`: `"qt_quick table: a toned cell keeps its selection mark, a tooltip cell is described, a unit header is named with its unit"` — a table with columns `{label "Mass", unit "kg"}` and one row whose cell gets `CellAccent{Tone::Warn, "Above limit"}`, selected: the cell item's tint is the theme's `warn` surface and the row's selection mark is still drawn; the cell's `Accessible.description` is `"Above limit"` and it shows the "more here" mark; the header item's `Accessible.name` is `"Mass, kg"`; a second cell given `CellAccent{.tone = {}, .tooltip = "The value could not be read", .invalid = true}` draws the theme's error mark with that text as its tooltip and accessible description, and after `setCellAccent(row, column, CellAccent{})` draws neither. Mutations: the tint painted over the selection mark; `invalid` ignored by `MorphTable.qml`, which draws no error mark. In `tests/tui/test_tui_table.cpp`: `"tui table: a header with a unit reads Mass [kg]"` — the header row's text holds `Mass [kg]`; a cell given an `invalid` accent draws the terminal's error glyph in place of its text. Mutations: `unit` ignored; `invalid` ignored. + +- [ ] **Step 11: Run them; they fail** (`unit`, `setCellAccent` undeclared). + +Run: `cmake --build --preset cl-debug --target morph_tests` and `cmake --build build/cl-qt-debug --target morph_qt_quick_tests morph_tui_tests` +Expected: compile errors naming `setCellAccent`, `unit`, `CellAccent`. + +- [ ] **Step 12: Implement the view, mount, backends and lowering.** + - `view.hpp`/`backend.hpp`/`mount.hpp`: the members in the Interfaces block and the mount rule under it ("Cells, not rows, carry the accent"): an `AccentedCell` is unwrapped where a cell is mounted, its `accent` bound in the cell's own scope and sent with `setCellAccent(row, column, accent)`, `column` an index into `Table::columns`. `ui::TableColumn::unit` goes to `setColumns`. The recording backend records both, the accent per row key and column. + - Qt Quick (`src/qt_quick/table.cpp`, `MorphTable.qml`): a toned cell is filled with the theme's tone surface under the selection and focus marks; an `invalid` cell draws the theme's error mark in place of its text; a cell with a tooltip draws the theme's "more here" mark, shows the tooltip on hover after the theme's delay and on keyboard focus at once, and carries it as `Accessible.description`; a header with a unit draws the unit on a second, muted line and has `Accessible.name` `headerAccessibleName(label, unit)`. + - Terminal (`src/tui/table_widget.cpp`): a header is `headerText(label, unit)`; a toned cell uses the tone's colour; an `invalid` cell draws the error glyph; a tooltip is shown in the status area while the cell is focused. + - `src/ui/interpreter.cpp`: a column part's `decimals`, `rounding`, `padPlaces`, `grouping`, `empty`, `unit`, `date` and `labels` (literals) build a `table::ColumnDisplay` that overrides the description's per member; on a table over `rows` they are its only source. A part's `tone` and `tooltip` are expressions in the row's scope and win over the description's companions; the lowering then passes them in `CompanionOverrides`. The default cell's text is `formatCell(cell, column, scope->formatting(), displayUnits)`. `cellView(column, rowSignal)` returns `accentedCell(content, accent)` for every column, whether its content is the default cell or the column's `cell` template. `accent` is a binding in the cell's row scope that gives a `CellAccent`: `tone` from the part's `tone` expression, else the tone the companion's field of the row's record names (`neutral`, `info`, `ok`, `warn`, `err`; anything else is none, reported once for the column); `tooltip` from the part's `tooltip` expression, else the companion's field; and, when `cellLook(cell, column, displayUnits)` is `CellLook::Invalid`, `invalid = true` with the tooltip `"The value could not be read"` in place of any other. A column with no tone, no tooltip and a valid cell has the accent `CellAccent{}`. An unloaded cell's placeholder is Task 9d's `setCellLoad`, from the column's level, and no part of the accent. The fetched column set is `columnsWithCompanions(description, windowColumns, overrides)`. The columns of `companionColumns(description)` are left out of the `ColumnLayout` the lowering builds, the column chooser and the header menus. An unknown tone name is reported once per column with the message in the test. A `Measure` column with no `align` part aligns to the end, with digits of one width, as an `end` column does ("Values with units › Display"). + - **Task 9's stand-in.** Task 9 formats a model-backed table's cells through a stand-in until this task lands. It is `ui::detail::standInCellText(table::Cell const&, table::TableColumn const&)` in `include/morph/ui/table_rows.hpp` (index decision 9). Find every call with `grep -rn "standInCellText" include src tests`, replace each (Part E's copy among them) with `formatCell(cell, column, scope->formatting(), displayUnits)`, and delete the stand-in; then the same grep prints nothing. Also `grep -n "displayText(\|textOf(" src/ui/interpreter.cpp`: a call that turns a table cell into its shown text goes through `formatCell` too. If Task 9 has not landed, Task 9 calls `formatCell` directly and this bullet does nothing. + - Part E's copy (Task 12f) writes each cell with `formatCell` and each label with `headerText(label, unit)` before `ui::copyText(labels, rows)` and `IViewBackend::copyText`. Part E's values list (Task 12d, dialog `table_filter`) labels `table_filter_value_` with `distinctTexts(values, column, locale, units)[i] + " (" + count + ")"` in place of the reply's `text`. + - `src/ui/document.cpp`: `rounding` is a literal `"halfEven"` or `"halfUp"`; `decimals` a literal integer 0 to 18; `labels` a literal list of `{operand, text}`; each other value is reported at its path as the existing column parts are. + +- [ ] **Step 13: Run the task's tests and their targets; all pass.** + +Run: `ctest --test-dir build/cl-debug -R "format cell:|description:|table display:" --output-on-failure` and `ctest --test-dir build/cl-qt-debug -R "qt_quick table:|tui table:" --output-on-failure`, then the whole `morph_tests`, `morph_table_tests`, `morph_qt_quick_tests` and `morph_tui_tests`. +Expected: all pass. + +- [ ] **Step 14: Mutations.** Apply each mutation named above by hand, run its test, see it fail, revert; keep each failing line for the commit body. + +- [ ] **Step 15: Docs.** `docs/spec/ui/document.md`: the `table` row gains a column's parts `decimals`, `rounding`, `padPlaces`, `grouping`, `empty`, `unit`, `date`, `labels`, `tone`, `tooltip`, each in one clause with its rule from "How a column shows its cells". `docs/spec/ui/backend_contract.md` and `docs/spec/qt_quick/backend.md`: `setCellAccent` and a column's `unit`. Run the docs build; it is green. + +- [ ] **Step 16: Commit.** + +```bash +git add include/morph/table/description.hpp include/morph/ui/cell_format.hpp include/morph/ui/view.hpp \ + include/morph/ui/backend.hpp include/morph/ui/mount.hpp include/morph/ui/testing/recording_backend.hpp \ + src/ui/interpreter.cpp src/ui/document.cpp src/qt_quick src/tui tests docs/spec +git commit -m "feat(table): column display, tone and tooltip" +``` + +--- + +## Task 17: Acting on rows (table.md step 9b) + +Needs Tasks 9 and 15. Four commits, each its own reviewer gate. + +### Task 17a: A selection of the view + +**Takes over Ctrl+A and the select-all box.** Until this task, Ctrl+A and the select-all box over a source table go to `setOnSelectRange` over every row of the view (Task 10b), which the lowering refuses past `SessionOptions::maxRangeRows`. That refusal is interim: this task routes both, in Qt Quick and the terminal, to the whole-view selection (`setOnSelectAll`), which needs no keys and has no such bound, and removes the range path for them. + +**Spec:** "A selection of the view" (2264–2357); test rows "A selection of the view", "Resolving from elsewhere", "The view revision is membership", "Copy of a selection of the view"; invariants 33, 34; failure modes 3314–3315. + +**Files:** +- Create: `include/morph/table/row_selection.hpp` — `RowSelection`, `SelectionPolicy`, `SelectedRows`, `ResolveRequest`, `RowRef`, `resolve`, `detail::membership`. +- Modify: `include/morph/table/data_source.hpp` (`TableErrorCode::ViewChanged`, wire name `"viewChanged"` in the enum's glaze meta at `data_source.hpp:934`), `include/morph/table/query.hpp` (`QueryLimits::maxSelectedRows`; `Page::viewRevision`; `PageRows::viewRevision`, filled by `apply`), `include/morph/table/view_cache.hpp` (`MembershipDigest`; the entry keeps the digest), `include/morph/table/description.hpp` (`GenericPage::viewRevision`, written and read), `include/morph/core/registry.hpp` (`BRIDGE_REGISTER_TABLE` adds `Table..resolve`), `include/morph/forms/forms.hpp` (`DeclaresSchemaValue`). +- Modify: `include/morph/ui/table_rows.hpp` (`ViewSelection`, `TableSelection`, `CountKind`, `SelectedCount`, `SelectAllRefusal`, the `TableRows` members below, `selectAllRefusalText`), `include/morph/ui/view.hpp` (`StatusEntry`; `TableStatus::{entries, standing, standingEntries}`; `onSelectAll`, `selectionView` and `onStatusEntry` on `ui::Table` and `TableOptions`), `include/morph/ui/backend.hpp` (`TableWidget::setOnSelectAll`, `setSelectionView`, `setOnStatusEntry`), `include/morph/ui/mount.hpp`, the recording, Qt Quick and terminal table widgets, `include/morph/ui/interpreter.hpp` and `src/ui/interpreter.cpp` (`RunObserver`, `Session::addRunObserver`/`removeRunObserver`, `TableInput`, `tableInputsOf`; the model-backed table's selection, element values `selectionSet` and `selectedCountKind`; the `viewChanged` refusal and its "Run on these" entry; Task 12's copy of a view selection). +- Test: `tests/table/test_table_selection.cpp`, `tests/net/test_push_tables.cpp`, `tests/test_ui_table_model.cpp`, `tests/qt_quick/test_qt_quick_table.cpp`, `tests/tui/test_tui_table.cpp`. +- Docs: `docs/spec/ui/document.md` (element values `selectionSet`, `selectedCountKind`), `docs/spec/ui/backend_contract.md` and `docs/spec/qt_quick/backend.md` (`setOnSelectAll`, `setSelectionView`, `setOnStatusEntry`). + +**Interfaces:** +- Consumes: `ServedTable`, `TableContext`, `TableOf`, `BRIDGE_REGISTER_TABLE`, `table::scoped` (Task 2); `Match`, `CompiledFilter::evaluate` (Task 3); `TableRuntime`, `currentTableRuntime`, `TableRuntimeScope` (Task 2; `views` from Task 6), `detail::answerQuery` and `AnswerContext` (Tasks 2 and 6); `ViewCache` and its entry for a validated sort and filter (Task 6); `TableRows`, `WindowRows`, `EngineRows`, `TableCountsView` (Task 9); `TableRows::keysOf` and range selection in server mode (Task 10); the copy path (Task 12f) and `ScreenCore::tableMessage` (Task 9d); `model::ActionRefusal` (`include/morph/core/action_refusal.hpp`); `model::recordRegistry()` (`include/morph/core/records.hpp:189`). +- Produces: + +```cpp +namespace morph::table { +template +struct RowSelection { + struct View { + FilterSpec filters; + std::vector retained; + std::string revision; + }; + std::vector keys; + std::optional view; + std::vector except; + /// The schema keyword and its value: {"x-selectionOf", "."}. + [[nodiscard]] static std::pair schemaValue(); +}; +enum class SelectionPolicy : std::uint8_t { Exact, Current }; // JSON "exact", "current" +struct SelectedRows { std::vector keys; std::int64_t dropped = 0; }; +template +struct ResolveRequest { RowSelection selection; SelectionPolicy policy = SelectionPolicy::Exact; }; +template +struct RowRef { // JSON: the key itself + RowId key; + [[nodiscard]] static std::pair schemaValue(); // {"x-rowOf", record} +}; +template +[[nodiscard]] async::Completion> +resolve(Model& model, RowSelection const& selection, TableContext const& context, SelectionPolicy policy); +// `Model&`, as table.md declares it (index decision 23): table functions are non-const, and `resolve` reaches +// one through Task 2's table::detail::serve(model, context), which also handles a typed table. + +// Consumed, not defined here (index decision 6): Task 2's TableRuntime{exec::IExecutor* work; ViewCache* views /* Task 6 */}, +// currentTableRuntime() and TableRuntimeScope. + +class MembershipDigest { // view_cache.hpp +public: + void add(RowId const& key) noexcept; + [[nodiscard]] std::string text() const; // 48 lowercase hex digits +}; +// QueryLimits: std::int64_t maxSelectedRows = 1'000'000; +// Page, PageRows, GenericPage: std::string viewRevision; +// TableErrorCode::ViewChanged ("viewChanged") +namespace detail { +struct Membership { std::vector rows; MembershipDigest digest; }; // rows in source order +[[nodiscard]] std::expected +membership(ServedTable const& served, FilterSpec const& filters, std::span retained, + ViewCache* views); +} +} // namespace morph::table + +namespace morph::ui { +struct ViewSelection { table::FilterSpec filters; std::vector retained; std::string revision; }; +struct TableSelection { // JSON as RowSelection's + std::vector keys; + std::optional view; + std::vector except; +}; +enum class CountKind : std::uint8_t { Exact, Approximate }; // element value "exact" / "approximate" +struct SelectedCount { std::int64_t rows = 0; CountKind kind = CountKind::Exact; }; +struct SelectAllRefusal { std::int64_t undecided = 0; std::vector levels; }; +// TableRows gains (pure virtual; EngineRows and WindowRows implement): +// [[nodiscard]] virtual std::expected selectView() const = 0; +// [[nodiscard]] virtual SelectedCount selectedCount(TableSelection const& selection) const = 0; +// virtual async::Completion, table::TableError>> +// rowsOf(std::int64_t first, std::int64_t count, std::span columns) = 0; +[[nodiscard]] std::string selectAllRefusalText(SelectAllRefusal const& refusal, FormatContext const& locale); +enum class TableInputKind : std::uint8_t { Selection, Row }; +struct TableInput { std::string member; std::string record; TableInputKind kind; }; +[[nodiscard]] std::vector tableInputsOf(std::string_view schemaJson); +struct RunStarted { std::uint64_t run; std::string const& action; Value const& body; }; +struct RunSettled { + std::uint64_t run; std::string const& action; Value const& body; bool succeeded; Value const& reply; + std::string const& refusalCode; // the ActionRefusal code, empty for none + std::function rerun; // runs the same mutation again with another body +}; +class RunObserver { +public: + virtual ~RunObserver() = default; + virtual void started(RunStarted const& run) = 0; + virtual void settled(RunSettled const& run) = 0; +}; +// Session gains: void addRunObserver(RunObserver* observer); void removeRunObserver(RunObserver* observer); +// StatusEntry (view.hpp): std::string id; std::string label; bool operator==(StatusEntry const&) const = default; +// ui::Table and TableOptions both gain (index decision 41; the lowering fills both): +// std::function onSelectAll; // set: the mount calls setOnSelectAll with it +// Prop>> selectionView; // engaged: the selection is the view less these keys; +// // the mount calls setSelectionView on each change, and +// // setSelection(selection) when it disengages +// std::function onStatusEntry; // a status-line entry the user chose, by its id +// TableWidget gains: virtual void setOnSelectAll(std::function onSelectAll) = 0; +// virtual void setSelectionView(std::vector const& except) = 0; +// virtual void setOnStatusEntry(std::function onStatusEntry) = 0; +} // namespace morph::ui +``` + +- [ ] **Step 1: Write the failing server tests** in `tests/table/test_table_selection.cpp`. The file's new cases share one model: + +```cpp +namespace { +using namespace morph::table; +// Ten rows, keys 0..9: status "open" for 0..5, "closed" for 6..9; mass i/10. +struct SelectionModel { + std::shared_ptr source = tabletest::makeSource( + {tabletest::col("status", ColumnKind::Text), tabletest::col("mass", ColumnKind::Decimal)}, + [] { + std::vector> rows; + for (int i = 0; i < 10; ++i) { + rows.push_back({Cell{std::string{i < 6 ? "open" : "closed"}}, + Cell{tabletest::dec(std::to_string(i) + ".0")}}); + } + return rows; + }()); + QueryLimits limits{}; + [[nodiscard]] ServedTable rows(TableContext const& /*context*/) { // non-const, as the spec's table functions + return ServedTable{.description = {}, .source = source, .levels = {}, .mayRead = {}, .scope = {}, + .services = {}, .limits = limits}; + } +}; +FilterSpec open() { return FilterSpec{.columns = {{"status", ColumnFilter{.include = {{.eq = "open"}}}}}}; } +// TableContext holds a reference: one caller context outlives every call in the file. +TableContext const& caller() { + static morph::session::Context const session{}; + static TableContext const context{.session = session}; + return context; +} +// resolve with no TableRuntime settles on an InlineExecutor before it returns: `then` runs at once. +template T settledNow(morph::async::Completion& completion); // `then` into an optional, REQUIRE set +std::string revisionOf(SelectionModel& model, FilterSpec const& filters, std::vector retained = {}) { + return detail::membership(model.rows(caller()), filters, retained, nullptr).value().digest.text(); +} +} // namespace + +TEST_CASE("view selection: the view revision is membership", "[table][selection][revision]") { + SelectionModel model; + std::string const before = revisionOf(model, open()); + model.source->patchRow(RowId{std::int64_t{2}}, {Cell{std::string{"open"}}, Cell{tabletest::dec("9.5")}}); + CHECK(revisionOf(model, open()) == before); // a cell changed, membership did not + TableQuery ascending{.sort = {{.column = "mass", .dir = SortDirection::Ascending}}, .filters = open()}; + TableQuery descending{.sort = {{.column = "mass", .dir = SortDirection::Descending}}, .filters = open()}; + CHECK(apply(*model.source, ascending).value().viewRevision == before); + CHECK(apply(*model.source, descending).value().viewRevision == before); // the sort is not membership + model.source->patchRow(RowId{std::int64_t{7}}, {Cell{std::string{"open"}}, Cell{tabletest::dec("0.7")}}); + CHECK(revisionOf(model, open()) != before); // a row came in + CHECK(revisionOf(model, open(), {RowId{std::int64_t{8}}}) != revisionOf(model, open())); +} +// Mutation: the revision taken from the snapshot's version, which changes it on the first edit. + +TEST_CASE("view selection: resolve under Exact is the view less except, in source order", + "[table][selection][resolve]") { + SelectionModel model; + RowSelection<&SelectionModel::rows> selection{ + .keys = {}, .view = {{.filters = open(), .retained = {}, .revision = revisionOf(model, open())}}, + .except = {RowId{std::int64_t{3}}}}; + auto exact = resolve(model, selection, caller(), SelectionPolicy::Exact); + auto const rows = settledNow(exact).value(); + CHECK(rows.keys == std::vector{std::int64_t{0}, std::int64_t{1}, std::int64_t{2}, std::int64_t{4}, + std::int64_t{5}}); + CHECK(rows.dropped == 0); + + model.source->patchRow(RowId{std::int64_t{7}}, {Cell{std::string{"open"}}, Cell{tabletest::dec("0.7")}}); + auto changed = resolve(model, selection, caller(), SelectionPolicy::Exact); + CHECK(settledNow(changed).error().code == TableErrorCode::ViewChanged); + auto current = resolve(model, selection, caller(), SelectionPolicy::Current); + CHECK(settledNow(current).value().keys == + std::vector{std::int64_t{0}, std::int64_t{1}, std::int64_t{2}, std::int64_t{4}, std::int64_t{5}, + std::int64_t{7}}); +} +// Mutation: `viewRevision` that ignores the source snapshot (a digest of the filter alone), which resolves the +// edited view under Exact. + +TEST_CASE("view selection: a key selection resolves to the keys the caller sees", "[table][selection][resolve]") { + SelectionModel model; + // The caller's source is rows 0..4 only, through Task 2's table::scoped. + // RowSelection{.keys = {3, 1, 8}}: keys == {1, 3} (source order), dropped == 1. +} +// Mutation: dropped keys left in the reply, which returns 8. + +TEST_CASE("view selection: a view over maxSelectedRows is LimitExceeded", "[table][selection][resolve]") { + CHECK(QueryLimits{}.maxSelectedRows == 1'000'000); + SelectionModel model; + model.limits.maxSelectedRows = 5; // the open view has 6 rows + // resolve of the open view with except {3} under Current: error().code == TableErrorCode::LimitExceeded + // (the bound is on the view, 6 rows, not on what is left of it, 5). + // With maxSelectedRows = 6 the same selection resolves to {0,1,2,4,5}. +} +// Mutation: the bound compared against the view less `except` (5 rows), which resolves the first case. + +TEST_CASE("view selection: retained rows are in the membership", "[table][selection][resolve]") { + // A view selection of open() with retained {8} and the revision revisionOf(model, open(), {8}): + // under Exact, keys == {0,1,2,3,4,5,8}. Retained {42}, a key the source lacks, adds nothing. +} +// Mutation: retained rows left out of `membership`, which refuses with ViewChanged. + +TEST_CASE("view selection: its JSON", "[table][selection]") { + // {"keys":[1,"a"]} reads as two keys and no view; {"view":{"filters":{"columns":{"status":{"include": + // [{"eq":"open"}]}}},"retained":[8],"revision":"r"},"except":[3]} round-trips byte for byte through glaze; + // SelectionPolicy writes "exact" and "current". +} +// Mutation: `SelectionPolicy` without glaze meta, which writes 0 and 1. +``` + +Write the commented cases' assertions exactly as their comments state. + +**The table is registered.** `resolve` reaches the table through Task 2's `detail::serve`, which reads `TableTraits` (its `row`, to tell a plain table from a `typed` one), and the primary `TableTraits` has only `registered = false`: an unregistered function does not compile there. So the model is not in the anonymous namespace: it is `seltest::SelectionModel`, with at file scope `BRIDGE_REGISTER_TABLE(seltest::SelectionModel, "rows", &seltest::SelectionModel::rows)` and the model registration Part A's own `tests/table` cases use for a model with a table (Task 2); the anonymous namespace keeps the helpers and a `using seltest::SelectionModel;`. + +- [ ] **Step 2: Run them; they fail to compile** (`row_selection.hpp` missing). + +Run: `cmake --build --preset cl-debug --target morph_table_tests` +Expected: `cannot open include file 'morph/table/row_selection.hpp'`. + +- [ ] **Step 3: Implement the server side.** + - **`MembershipDigest`.** Membership is a set of keys, so the digest does not depend on the order it is taken in, and a retained row merged into a reply is one more `add`. For each key, `h = fnv1a64(k)` (`morph::model::detail::fnv1a64`, `include/morph/core/payload_schema.hpp:213`) over `"i:" + decimal` for an integer key and `"s:" + text` for a text key, and `m = splitmix64(h)` (`z = h + 0x9E3779B97F4A7C15; z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9; z = (z ^ (z >> 27)) * 0x94D049BB133111EB; z ^ (z >> 31)`). The digest keeps `count`, `sum += h` and `mix += m`, all modulo 2^64; `text()` is the three as 16 lowercase hex digits each, in that order. A caller adds each key once. + - **Where it is taken.** The pass that computes a view in `apply` (and the view cache's computation, Task 6) adds the key of each row it puts in the view; the cache entry stores the `MembershipDigest` beside its order; `PageRows`, `Page` and `GenericPage` carry `viewRevision = digest.text()`, page and keyed replies alike. A distinct-values reply leaves it empty. + - **`detail::membership`.** Takes the view of `filters` with an empty sort from `views` when one is given (the entry under that key, computed by the cache's single flight when absent), else computes it with `apply`; with an empty sort the view's order is source order. Each key of `retained` the source has and the view lacks is merged in at its source row and added to a copy of the digest. A view whose size after merging is above `served.limits.maxSelectedRows` is `LimitExceeded`. + - **`resolve`.** It takes `Model&` (as table.md declares it, index decision 23) and gets the `ServedTable` with Task 2's `table::detail::serve(model, context)` on the caller's thread (the model's strand), so the caller's scope and `mayRead` apply and a `typed` table works as a plain one. The rest runs on `currentTableRuntime()->work` with `currentTableRuntime()->views`. The returned `Completion` comes from `Completion<…>::makeSettleable(exec)` (`include/morph/core/completion.hpp:738`), `exec` being the runtime's `work`; with no runtime, or a null `work`, the work runs inline with no view cache and `exec` is a function-local static `exec::InlineExecutor` (`include/morph/core/executor.hpp:384`), so the promise is settled and `then` runs before `resolve` returns. Tests rely on that: `settledNow` attaches `then` and `REQUIRE`s the value at once. + - **The schema.** `forms.hpp` gains `DeclaresSchemaValue` (`{ T::schemaValue() } -> std::convertible_to>`), and `annotateSchemaMarker` also writes `property[first] = second` for such a type. `RowSelection::schemaValue()` and `RowRef::schemaValue()` return `{"x-selectionOf" | "x-rowOf", name}`, `name` being the `RecordInfo::name` in `model::recordRegistry()` whose `type` is `typeid(TableOf)`, or empty when none is registered. + - **`Table..resolve`.** `BRIDGE_REGISTER_TABLE` registers it beside `Table.` and `Table..describe`: body `ResolveRequest`, result `SelectedRows`, run like `Table.`: the table's function for the caller's session, then `resolve`'s work on `tableWork`. A `TableError` surfaces as `Table.`'s errors do. + - **The runtime.** Nothing to add: `RemoteServer` installs Task 2's `TableRuntimeScope` (`work` = `ServerConfig::tableWork`, `views` = `ServerConfig::views`) around each dispatch, so a Task handler reads it when it calls `resolve`; `Table..resolve` reaches the same work through `detail::answerQuery`'s `AnswerContext`. + - **A handler's refusal.** A Task handler that gets `ViewChanged` from `resolve` throws `model::ActionRefusal{"morph.table.viewChanged", {}, error.message}`; add `[[noreturn]] void table::refuse(TableError const&)` mapping `ViewChanged` to that code and every other code to `"morph.table." + `. + +- [ ] **Step 4: Run them; they pass.** + +Run: `ctest --test-dir build/cl-debug -R "view selection:" --output-on-failure` +Expected: 6 test cases pass. + +- [ ] **Step 5: Write the failing bridge tests** in `tests/net/test_push_tables.cpp`. Register in the file a model `selnet::Rows` with table `rows` (the same ten rows; a row scope by principal: `alice` sees 0..9, `bob` sees 0..4, with `scope` = the principal), an action `TagRows{table::RowSelection<&Rows::rows> rows;}` whose Task handler awaits `resolve(*this, rows, context, Exact)`, refuses through `table::refuse` and returns `ChangedRows<&Rows::rows>` of the keys, an action `MoveRow{std::int64_t key; std::string status;}` declaring `updatesTable<&Rows::rows>`, and a model `selnet::Other` whose action `Count{table::ResolveRequest<&Rows::rows> request;}` sends `Table.rows.resolve`. + +```cpp +TEST_CASE("tables: an action resolves a view selection on its own model", "[net][tables][selection]") { + // alice: Table.rows page with filters open() -> reply.viewRevision == R. + // TagRows {view: {filters: open(), retained: [], revision: R}, except: [3]} -> rows.keys {0,1,2,4,5}. + // MoveRow {key 7, status "open"}, then TagRows with revision R -> refused, code "morph.table.viewChanged". +} +// Mutation: viewRevision that ignores the source snapshot, which tags rows under the old revision. + +TEST_CASE("tables: Table..resolve answers for the caller", "[net][tables][selection]") { + // bob runs Other.Count with {selection: {keys: [1, 3, 8]}, policy: "current"} -> keys {1, 3}, dropped 1. + // bob with a view of open() under Current -> keys {0,1,2,3,4}: no row outside bob's scope. + // With the table's limits.maxSelectedRows = 5, alice's view of open() -> LimitExceeded. +} +// Mutation: resolve run under the server's principal, which returns rows outside bob's scope. + +TEST_CASE("tables: a selection's schema names its table", "[net][tables][selection]") { + // The catalog's schema of TagRows has properties.rows["x-selectionOf"] == "selnet::Rows.rows" (the record's + // registered name); a RowRef<&Rows::rows> member has "x-rowOf" with the same name. +} +// Mutation: schemaValue returning an empty name, which leaves the client unable to mark busy rows. +``` + +Write each commented assertion exactly; use the harness Task 2 created in this file. + +- [ ] **Step 6: Run them; they fail** (`Table.rows.resolve` is not a registered action; the schema lacks `x-selectionOf`). + +Run: `cmake --build --preset linux-everything --target morph_net_tests && ctest --preset linux-everything -R "tables: .*(resolve|selection)" --output-on-failure` +Expected: FAIL. + +- [ ] **Step 7: Make them pass** with Step 3's code (the registration and the runtime scope). Run Step 6's command: PASS. + +- [ ] **Step 8: Write the failing client tests** in `tests/test_ui_table_model.cpp`. Fixtures, in the test file, shared by Tasks 17a to 17c: + +```cpp +// id (Integer, key), status (Text), and the lock companion. Ten rows, keys 0..9: "open" for 0..5, "closed" for 6..9. +morph::table::TableDescription selectionDescription() { + using namespace morph::table; + TableDescription d; + d.id = "samples"; + d.key = "id"; + d.columns = { + TableColumn{.info = {.id = "id", .kind = ColumnKind::Integer}, .label = "Id"}, + TableColumn{.info = {.id = "status", .kind = ColumnKind::Text}, .label = "Status"}, + TableColumn{.info = {.id = "lockedBy", .kind = ColumnKind::Text}, .shown = false}, + }; + d.rowLock = "lockedBy"; + return describe(std::move(d)); +} +// One row of a page: its key, its status and its lock text. +struct SelRow { std::int64_t key; std::string status = "open"; std::string lockedBy; }; +// A page reply of selectionDescription(): {"revision": , "columns":["id","status","lockedBy"], +// "keys":[…], "rows":[[key,"status","lockedBy"],…], "total": total, "offset": 0, "viewRevision": viewRevision, +// "unmatched": unmatched}. A keyed reply is the same text with "indices". +std::string selectionPage(std::vector const& rows, std::int64_t total, std::string_view viewRevision, + std::vector const& unmatched = {}); +std::vector openRows() { return {{0}, {1}, {2}, {3}, {4}, {5}}; } + +// The table of Tasks 17a to 17c: filtered to open(), with the mutations of the "Catalog actions" table. +inline constexpr std::string_view kSelectionTable = R"({"kind":"table","id":"t","testId":"t","model":"sample","table":"samples", + "selectionMode":"multiple","filters":{"columns":{"status":{"include":[{"eq":"open"}]}}}})"; +inline constexpr std::string_view kSelectionMutations = R"({ + "tag":{"model":"sample","action":"Lims_TagRows","body":{"obj":{"rows":{"ref":"t.selectionSet"}}}}})"; +// Mounts it and answers the describe request and the first page: six open rows, total 6, viewRevision "v1". +void mountSelection(TableHarness& h, std::string_view table = kSelectionTable, + std::string_view mutations = kSelectionMutations) { + addAction(h, "Lims_TagRows", std::string{kSelectionSchema}, samplesAction()); + h.mount(doc(table, mutations)); + replyDescribe(h, describeJson(selectionDescription())); + replyPage(h, selectionPage(openRows(), 6, "v1")); +} +``` + +`filters` is written as the literal `FilterSpec` Task 9d's `filters` key reads. Tasks 17b and 17c pass their own table text and mutations to `mountSelection` and add their own action first. + +```cpp +TEST_CASE("view selection: Ctrl+A selects the view and fetches no row", "[ui][table][selection]") { + TableHarness h; + mountSelection(h); + int const table = h.backend.find("Table", "testId", "t"); + auto const before = lastQuery(h); + std::size_t const sent = h.dispatcher.count("Table.samples"); + h.backend.selectAll(table); // the backend's Ctrl+A + CHECK(h.dispatcher.count("Table.samples") == sent); // nothing sent + CHECK(lastQuery(h) == before); + CHECK(elementValue(h, "t", "selectionSet") == + value(R"({"view":{"filters":{"columns":{"status":{"include":[{"eq":"open"}]}}}, + "retained":[],"revision":"v1"},"except":[]})")); + CHECK(elementValue(h, "t", "selection") == value("[]")); + CHECK(elementValue(h, "t", "selectedCount") == morph::ui::Value{std::int64_t{6}}); + CHECK(elementValue(h, "t", "selectedCountKind") == morph::ui::Value{std::string{"exact"}}); + h.backend.ctrlClickRow(table, std::int64_t{3}); + CHECK(elementValue(h, "t", "selectedCount") == morph::ui::Value{std::int64_t{5}}); + h.backend.clickRow(table, std::int64_t{2}); + CHECK(elementValue(h, "t", "selectionSet") == value(R"({"keys":[2]})")); +} +// Mutation: select-all selecting the held keys, which sends no view and counts the held rows only. + +TEST_CASE("view selection: a key of except that leaves the view is dropped from it", "[ui][table][selection][review]") { + // mountSelection; selectAll, ctrlClick(3): count 5. fireEvent(record, [3]); the keyed reply leaves 3 out of the + // view (it became "closed"): selectionPage of rows 0,1,2,4,5, total 5, viewRevision "v2": selectedCount == 5, + // selectedCountKind == "exact", selectionSet's except == []. + // Again from the start, with the event's keyed fetch left unanswered (key 3 held but owed a refetch): kind + // "approximate" and statusOf(h).counts == "about 5 of 6 selected". +} +// Mutation: except keys never pruned, which counts 4. + +TEST_CASE("view selection: its life", "[ui][table][selection]") { + // selectAll; a header sort: selectionSet still has "view". A filter change: selectionSet == {"keys":[]}. +} +// Mutation: the selection ended by a sort, which empties it on the first step. + +TEST_CASE("view selection: not while membership is open", "[ui][table][selection]") { + // A reply with undecided 40: selectAll changes nothing; statusOf(h).message == "Select all is available once 40 rows are + // decided". A reply with undecided 0 and awaiting ["recipe"], `recipe` the level of the filtered column (a + // description whose `status` column has level "recipe"): statusOf(h).message == "Select all is available once + // recipe data has loaded". awaiting ["recipe"] where only the sorted column has that level: selectAll selects + // the view. +} +// Mutation: select-all ignoring `undecided`, which selects a view whose rows are not known. + +TEST_CASE("view selection: the rows changed since the user selected them", "[ui][table][selection]") { + // mountSelection; selectAll, ctrlClick(3), runMutation(h, "tag"); a page reply of seven rows, total 7, + // viewRevision "v2" arrives; refuseMutation(h, "tag", "morph.table.viewChanged"): + // statusOf(h).message == "The rows changed since you selected them: 6 rows now. Run on these?" with one entry + // labelled "Run on these". chooseStatusEntry(table, ) sends Lims_TagRows again whose rows.view.revision + // is "v2" and whose except is [3]. Not choosing it sends nothing. +} +// Mutation: the rerun sending the old revision, which is refused again. + +TEST_CASE("view selection: a Shift range toggles a range of except", "[ui][table][selection]") { + // Six open rows 0..5 at view rows 0..5. selectAll; ctrlClick(1): anchor 1, except == [1]. A Shift range from + // the anchor to view row 3 (selectTableRange, keys 1,2,3 through keysOf): except == [1,2,3], selectedCount == 3. + // ctrlClick(5) twice (anchor 5, selected again); a Shift range from it to view row 2 (keys 2..5): + // except == [1], selectedCount == 5. With maxRangeRows = 2, a range of 3 rows leaves except unchanged and + // statusOf(h).message == "A range selects at most 2 rows". +} +// Mutation: a Shift range in a view selection replacing the selection with the range's keys. + +TEST_CASE("view selection: copying it fetches the view's rows in order", "[ui][table][selection]") { + // 6 open rows, a window holding 2; selectAll, ctrlClick(1), ctrlClick(4); Copy: the window sends page queries + // naming the visible columns, and clipboardText() holds rows 0,2,3,5 in view order, one line each. With + // SessionOptions::maxCopyRows = 3, statusOf(h).message == "A copy holds at most 3 rows" and clipboardText() is unchanged. +} +// Mutation: copying the held rows only, which writes rows 0 and 2. + +TEST_CASE("table rows: a new description revision drops a view selection that names a removed column", + "[ui][table][selection]") { + // Extends Part D's Review Focus 1 test (Task 9, same file; index decision 16). Description rev A with columns + // id, status, c; filters on status and on c; selectAll, ctrlClick(3). A page reply names revision B, and the + // describe reply B lacks c: selectionSet == {"keys":[]} (the view selection was of a filter that named c); + // lastQuery(h).filters.columns does not contain "c"; a Lims_TagRows run afterwards carries no "c" anywhere in + // its body. With the filter on status only, the same revision change keeps the view selection, its `except` + // [3] and its filters. +} +// Mutation: setDescription leaving the view selection as it was, which sends a view whose filter names c. +``` + +`selectAll`, `clickRow`, `ctrlClickRow` and `chooseStatusEntry` (this part's `RecordingBackend` drivers) call `setOnSelectAll`'s handler, `onSelectionChange` with `Replace` / `Extend`, and `setOnStatusEntry`'s handler; Write each commented assertion exactly as stated. + +- [ ] **Step 8a: Write the failing backend tests.** In `tests/qt_quick/test_qt_quick_table.cpp`: `"qt_quick table: select-all asks the handler and marks the view"` — a table of five rows, `SelectionMode::Multiple`, `setOnSelectAll` set: `Ctrl+A` and a click on the select-all box each call the handler once and `onSelectionChange` is not called; after `setSelectionView({key 2})` every row item but key 2's draws selected, and a `Ctrl`+click on row 1 reports `Extend` with the four other keys less 1; after `setSelection({})` no row draws selected. Mutation: `setOnSelectAll` ignored, under which `Ctrl+A` reports the five keys through `onSelectionChange`. `"qt_quick table: a status entry reports its id"` — `setStatus` with `message = "m"`, `entries = {{"run", "Run on these"}}`, `standing = "1 row could not be saved"`, `standingEntries = {{"select", "Select them"}, {"clear", "Clear marks"}}`: the status line shows the three entries as buttons with those labels; a click on "Clear marks" calls the `setOnStatusEntry` handler with `"clear"`. Mutation: the entries drawn as plain text, under which the click reports nothing. In `tests/tui/test_tui_table.cpp`: `"tui table: select-all asks the handler; a status entry reports its id"` — the same two assertions through the terminal's keys (`Ctrl+A`; the entry's key as the status line shows it). Mutation: `setOnStatusEntry` ignored. + +- [ ] **Step 9: Run them; they fail** (`selectionSet` is not an element value). + +Run: `cmake --build --preset cl-debug --target morph_tests && ctest --test-dir build/cl-debug -R "view selection:" --output-on-failure`; `cmake --build build/cl-qt-debug --target morph_qt_quick_tests morph_tui_tests` +Expected: FAIL; the backend tests do not compile (`setOnSelectAll`). + +- [ ] **Step 10: Implement the client side.** + - **`WindowRows`.** `selectView()` returns `SelectAllRefusal{undecided, levels}` when `counts().undecided > 0`, or when `counts().awaiting` holds a level of a column in the current filter (a column filter's column or a group filter's columns; levels from the description's `ColumnInfo::level`), `levels` then being those; otherwise `{filters, retained, viewRevision}` of the latest page reply. `selectedCount` for a view: the view's total less every key of `except` the window holds in the view, a key owed a refetch included (it still subtracts); a key of `except` a reply left out of the view is removed from `except` by the lowering. `kind` is `Exact` when the total is `Exact` and every key of `except` is held and owed nothing (`PageWindow::owed()` names none of them), else `Approximate` (so 6 less a held-but-owed 3 is "about 5 of 6"). For keys: `keys.size()`, `Exact`. `rowsOf` sends page queries of `pageSize` rows naming `columns` and completes with every row of the range. + - `rowsOf` completes with Part E's `FetchedRow{key, viewRow, cells}` (Task 12f), one per view row of the range. + - **`EngineRows`.** `selectView` returns the engine's filter, retained keys and the digest of its view; the lowering never uses it, since a table held whole selects all by keys. `rowsOf` reads the engine. + - **`selectAllRefusalText`.** `"Select all is available once " + n + (n == 1 ? " row is decided" : " rows are decided")`, `n` written with the locale's grouping; with no undecided rows, `"Select all is available once " + levels joined with " and " + " data has loaded"`. + - **The backend.** `setOnSelectAll(handler)`: when set, Ctrl+A, the select-all box and "Select all" call it instead of selecting keys. `setSelectionView(except)`: marks every row whose key is not in `except` until the next `setSelection`. In that state a Ctrl+click reports `Extend` with the keys now selected among the existing keys; the lowering reads every existing key absent from the report as added to `except`, and every present one as removed from it. A plain click reports `Replace` and ends the view selection. A `Shift` range in a view selection (Part D's Task 10a range report by view rows, `selectTableRange`) is resolved through `TableRows::keysOf(first, count)`, bounded by `SessionOptions::maxRangeRows` (over it: Task 10a's refusal through `tableMessage`, and `except` unchanged); a range from an anchor that is selected removes its keys from `except`, one from an anchor in `except` adds them. + - **A new description revision** (Part D's `setDescription`): a view selection whose filter names a column the new description lacks becomes `TableSelection{}`; one that names none is kept. + - **The view and the mount.** `ui::Table` and `TableOptions` both gain `onSelectAll`, `selectionView` and `onStatusEntry` (index decision 41). The mount calls `setOnSelectAll(onSelectAll)` when it is set, `setSelectionView(except)` whenever `selectionView` is engaged and changes, `setSelection(selection)` when it disengages, and `setOnStatusEntry(onStatusEntry)`. The lowering holds each status entry's handler in a map by `id` and runs it from `onStatusEntry`. + - **The lowering.** A model-backed table with `selectionMode: multiple` sets `Table::onSelectAll`; the handler takes `selectView()`, posts `selectAllRefusalText(…)` through `tableMessage`, or makes the element's selection `TableSelection{.view = …}`, which engages `selectionView` with its `except`. A filter change, and "Show only matching rows" (Task 17b), make it `TableSelection{}`; a sort change keeps it. `selectionSet` is the selection's JSON on every table (`{"keys": […]}` on a table over `rows`); `selection` is the key list, `[]` while the selection is a view; `selectedCount` and `selectedCountKind` come from `selectedCount`. The status line's count reads `"about " + n + " of " + total + " selected"` when the kind is `Approximate`. + - **Run ids.** A `RunStarted::run` is session-wide: `Session` keeps one counter, and `MutationRuntime::send` takes the next id from it for the observers (index decision 24); `MutationRuntime`'s own `_runs` (`src/ui/interpreter.cpp:2396`) is per mutation and two mutations both number their first run 1, so it is not what observers see. + - **Runs.** `MutationRuntime` calls each `RunObserver` of its session in `send` (`started`) and `settle` (`settled`, with the refusal's code and a `rerun` that calls `run` with a new body and the run's bindings). `tableInputsOf(schema)` lists the schema's top-level properties carrying `x-selectionOf` (`Selection`) or `x-rowOf` (`Row`), with the record the keyword names. Each model-backed table registers one `RunObserver` while mounted. On `settled` with code `morph.table.viewChanged`, for each `Selection` input whose body member is a view selection of this table's record, it takes `selectView()` again (same `except`), posts `"The rows changed since you selected them: " + n + " rows now. Run on these?"` through `tableMessage` with the status entry "Run on these", `n` the new `selectedCount`; choosing the entry calls `rerun` with that member replaced. + - **Copy** (Part E's Task 12f path): a view selection whose `selectedCount` is above `maxCopyRows` is refused with `tableText::copyBound(maxCopyRows)` through `tableMessage`; otherwise `rowsOf(0, total, visibleColumns)` page by page, rows of `except` left out, in view order. + +- [ ] **Step 11: Run them and their targets; all pass.** + +Run: `ctest --test-dir build/cl-debug -R "view selection:|table rows:" --output-on-failure`, then all of `morph_tests` and `morph_table_tests`; `ctest --test-dir build/cl-qt-debug -R "qt_quick table:|tui table:" --output-on-failure` and all of `morph_qt_quick_tests` and `morph_tui_tests`; on `linux-everything`, `ctest --preset linux-everything -R "tables:" --output-on-failure` and all of `morph_net_tests`. +Expected: PASS. + +- [ ] **Step 12: Mutations, docs, commit.** Run each named mutation and keep its failing line. `docs/spec/ui/document.md`: element values `selectionSet` (every table) and `selectedCountKind`; a model-backed table's select-all selects the view. `docs/spec/ui/backend_contract.md` and `docs/spec/qt_quick/backend.md`: `setOnSelectAll`, `setSelectionView`, `setOnStatusEntry` and the status line's entries. Docs build green. + +```bash +git add include/morph/table include/morph/core include/morph/forms/forms.hpp include/morph/ui src/ui src/qt_quick src/tui tests docs/spec +git commit -m "feat(table): select the whole view and resolve it on the server" +``` + +### Task 17b: Rows kept in view + +**Spec:** "Rows an action changed › Kept in view" (2382–2408); test rows "Retained rows", "Retained rows and the event"; invariant 35; failure mode 3317. + +**Carried from 17a.** Task 17a leaves `ViewSelection::retained` empty on the client (`WindowRows::selectView` sends `retained: []`), since the window's retained set lands here. This task must fill it from the window's retained keys, the same set its page queries send as `retain`. Once retained rows enter a reply's `viewRevision` (as the spec requires), a selection of the view sent with an empty `retained` names a membership the server never computes, and every `Exact` resolve of it is `ViewChanged`: add a client case that selects the view while rows are retained, runs an action under `Exact`, and checks that it is not refused, with the mutation "retained left empty in `selectView`". + +**Files:** +- Modify: `include/morph/table/query.hpp` (`TableQuery::retain`, `QueryLimits::maxRetained`, `Page::unmatched`, `PageRows::unmatched`; `validate` bounds `retain`), `include/morph/table/description.hpp` (`GenericPage::unmatched`, written and read; `TableQuery::retain` on the wire), `include/morph/table/view_cache.hpp` (`detail::mergeRetained`, used per request), `include/morph/table/engine.hpp` (`Engine::retain`, `retained`, `isUnmatched`; `detail::JobInput::retained`), `include/morph/ui/table_rows.hpp` (`TableCountsView::retained`; `TableRows::retain`, `clearRetained`, `unmatched`, `holdRefetches`, `releaseRefetches`; `RetainResult`), `include/morph/ui/interpreter.hpp` (`SessionOptions::retainHold`), `src/ui/interpreter.cpp` (`retainChanged`, the status line entries, muted unmatched rows), `include/morph/ui/view.hpp` (`RowMarks`, `TableRowLook::marks`), `include/morph/ui/backend.hpp` (`TableWidget::setRowMarks`), `include/morph/ui/mount.hpp`, the three table widgets. +- Test: `tests/table/test_table_selection.cpp`, `tests/test_ui_table_model.cpp`, `tests/qt_quick/test_qt_quick_table.cpp`, `tests/tui/test_tui_table.cpp`. +- Docs: `docs/spec/ui/document.md` (`retainChanged`), `docs/spec/ui/backend_contract.md` and `docs/spec/qt_quick/backend.md` (`setRowMarks`). + +**Interfaces:** +- Consumes: Task 17a's `MembershipDigest`, `RunObserver`, `tableInputsOf`; Task 9's `ChangedRows` reading from a reply (here `changedRowsOf`, below); `ui::ActionInfo::{effects, records}` (`include/morph/ui/document.hpp`). +- Produces: + +```cpp +namespace morph::table { +// TableQuery: std::vector retain; QueryLimits: std::size_t maxRetained = 10'000; +// Page, PageRows, GenericPage: std::vector unmatched; // indices into `rows` +// Engine: +// std::expected retain(std::vector keys); // replaces the retained set +// [[nodiscard]] std::span retained() const noexcept; +// [[nodiscard]] bool isUnmatched(std::size_t viewRow) const; +namespace detail { +struct MergedView { + std::vector order; // source rows, in view order + std::vector unmatched; // view rows of retained rows the filter rejects + std::int64_t undecided = 0; + MembershipDigest digest; +}; +[[nodiscard]] MergedView mergeRetained(std::span baseOrder, std::int64_t baseUndecided, + MembershipDigest baseDigest, std::span retainedRows, + std::function const& before, + std::function const& match, + std::function const& keyOf); +} +} // namespace morph::table + +namespace morph::ui { +enum class RetainResult : std::uint8_t { Retained, OverBound }; +// TableCountsView: std::int64_t retained = 0; // held view rows that are retained and unmatched +// TableRows gains: +// [[nodiscard]] virtual RetainResult retain(std::span keys) = 0; // adds +// virtual void clearRetained() = 0; +// [[nodiscard]] virtual bool unmatched(table::RowId const& key) const = 0; // by key: a row look has no index +// virtual void holdRefetches(std::uint64_t run) = 0; +// virtual void releaseRefetches(std::uint64_t run) = 0; +// SessionOptions: std::chrono::milliseconds retainHold{2000}; +// view.hpp. A row's own marks (index decision 39): they do not vary per cell, so the row look carries them. +struct RowMarks { + bool busy = false; + bool locked = false; + bool unmatched = false; + std::string tooltip; + [[nodiscard]] bool operator==(RowMarks const&) const = default; +}; +// TableRowLook (Task 9d) gains: std::optional> marks; // bound in the row's scope by `rowView` +// TableWidget: virtual void setRowMarks(Widget& row, RowMarks const& marks) = 0; +struct ChangedRowsValue { std::vector rows; std::vector failed; }; +[[nodiscard]] ChangedRowsValue changedRowsOf(Value const& reply, ActionInfo const& action, std::string_view record); +} // namespace morph::ui +``` + +- [ ] **Step 1: Write the failing engine and server tests** in `tests/table/test_table_selection.cpp`, over Task 17a's `SelectionModel`. + +```cpp +TEST_CASE("retained rows: they stay in the view, listed in unmatched", "[table][retain]") { + SelectionModel model; + TableQuery query{.sort = {{.column = "mass", .dir = SortDirection::Descending}}, .filters = open(), + .retain = {RowId{std::int64_t{1}}, RowId{std::int64_t{7}}, RowId{std::int64_t{8}}}}; + for (std::int64_t key : {1, 7, 8}) { // the action closed row 1; rows 7 and 8 were closed already + model.source->patchRow(RowId{key}, {Cell{std::string{"closed"}}, Cell{tabletest::dec(std::to_string(key) + ".0")}}); + } + auto const page = apply(*model.source, query).value(); + std::vector keys; + for (std::size_t i = 0; i < page.rows.size(); ++i) { keys.push_back(model.source->snapshot()->rowId(page.rows[i])); } + CHECK(keys == std::vector{std::int64_t{8}, std::int64_t{7}, std::int64_t{5}, std::int64_t{4}, + std::int64_t{3}, std::int64_t{2}, std::int64_t{1}, std::int64_t{0}}); + CHECK(page.unmatched == std::vector{0, 1, 6}); + CHECK(page.total == 8); + TableQuery const plain{.sort = query.sort, .filters = open()}; + CHECK(page.viewRevision != apply(*model.source, plain).value().viewRevision); +} +// Mutation: retained rows appended after the base view instead of merged by the sort's keys. + +TEST_CASE("retained rows: the shared view entry is not changed by one request's rows", "[table][retain]") { + // Through Task 6's ViewCache: a request retaining {7}, then a request of the same sort and filter retaining + // nothing: the second reply has 5 rows, no 7, and empty `unmatched`; the cache computed the view once. +} +// Mutation: the merged view written into the shared view cache entry, which serves one session's retained rows to +// another. + +TEST_CASE("retained rows: retaining adds, never removes", "[table][retain][property]") { + // Property over 200 random tables (seeded): for random filters and a random retain set R of up to 20 keys, + // view(with R) ⊇ view(without R); view(with R) \ view(without R) == R ∩ source keys \ view(without R); + // `unmatched` names exactly the rows of R whose filter evaluates to No. +} +// Mutation: a retained row counted twice when the filter passes it too, which breaks the second equation. + +TEST_CASE("retained rows: the bound and the wire", "[table][retain]") { + CHECK(QueryLimits{}.maxRetained == 10'000); + // validate of a query retaining 10'001 keys: LimitExceeded; 10'000: accepted. A GenericPage with unmatched + // [0, 6] round-trips; a page read without "unmatched" has it empty. +} +// Mutation: no bound, which accepts 10'001. + +TEST_CASE("retained rows: a client-mode engine does the same", "[table][retain]") { + // An Engine over the same source, filter open(), sort mass desc; patch rows 1,7,8 closed; retain({1,7,8}): + // the view's keys are {8,7,5,4,3,2,1,0}; isUnmatched(0), (1), (6) are true, the rest false; setFilter(open()) + // clears the retained set (retained().empty()) and the view is {5,4,3,2,0}. +} +// Mutation: Engine::retain ignored by the filter run, which leaves 1, 7 and 8 out. +``` + +Write the commented cases' assertions exactly; `apply`'s `PageRows` holds source rows in `rows` (use its existing member if it is named differently). + +- [ ] **Step 2: Run them; they fail to compile** (`TableQuery::retain`). + +Run: `cmake --build --preset cl-debug --target morph_table_tests` +Expected: compile error naming `retain`. + +- [ ] **Step 3: Implement.** `mergeRetained`: R = the retained rows (source rows) not in `baseOrder`; sort R by `before`, which is the query's comparator over the sort's key columns with ties to the lower source row (the engine's order); merge R into `baseOrder` with the same comparator, so the result is the view the sort would give over base ∪ R. Every row of R is in the view whatever its `match` (a row whose filter is `Unknown` is in the view, not undecided): `undecided = baseUndecided −` the rows of R that were undecided; `digest` = `baseDigest` plus each key of R; `unmatched` lists the view row of each row of R whose `match` is `No`, ascending. `apply` and the view cache path compute the base view as before and call `mergeRetained` per request when `retain` is not empty; the cache entry is never written with it. The total is the merged view's size. A keyed query reads the merged view; distinct values ignore `retain`. A reply's `unmatched` holds indices into its own `rows`. `Engine::retain` stores the keys and runs the filter again with them admitted; `setFilter` clears them. + +- [ ] **Step 4: Run them; they pass.** + +Run: `ctest --test-dir build/cl-debug -R "retained rows:" --output-on-failure` +Expected: 5 test cases pass. + +- [ ] **Step 5: Write the failing client tests** in `tests/test_ui_table_model.cpp`, over the ten rows, a table with `"retainChanged": true` filtered to `open()`, and the mutation `close` of the "Catalog actions" table. Each case starts with `addAction(h, "Lims_CloseRows", std::string{kSelectionSchema}, samplesAction());` and `mountSelection(h, , )`; `samplesAction()` is what makes `Lims_CloseRows` an action with an effect on the table's record and a `ChangedRows` at `rows.rows`. + +```cpp +TEST_CASE("retained rows: the rows an action changed stay in view", "[ui][table][retain]") { + // run close; settle with {"rows":{"rows":[{"key":1},{"key":2},{"key":3}],"failed":[]}}: the next query carries + // retain [1,2,3]; answer it with those rows unmatched: they are drawn with RowMarks{.unmatched = true, + // .tooltip = "This row no longer matches the filter"}, counts().retained == 3, statusOf(h).standing == + // "3 rows shown that no longer match" with the standing entry "Show only matching rows"; it is still there after + // h.advance(7000) and a click on a row. Choosing "Show only matching rows": the next + // query has no retain, and a view selection, if any, is empty. A filter change does the same. +} +// Mutation: retained keys dropped when the next page arrives, which loses them from the second query. + +TEST_CASE("retained rows: an action over the bound retains none", "[ui][table][retain]") { + // With 9'999 keys retained, a reply naming 2 changed rows: no key is added, statusOf(h).message == + // "The changed rows are not kept in view: a table keeps at most 10,000"; the 9'999 stay. With 9'998 retained, + // the same reply adds both. +} +// Mutation: a partial add up to the bound, which retains one of the two. + +TEST_CASE("retained rows: an event before its action's reply is held", "[ui][table][retain]") { + // run close (it declares an effect on the table); fireEvent(record, [1]) before the reply: no query is sent. + // settle the run: exactly one query is sent, keyed or page per Task 7's refresh plan, carrying retain [1]. + // A second run, an event, and the scheduler advanced by retainHold (2 s) without a reply: one query is sent + // then, and none when the reply arrives later except its retained rows' refetch. + // On a table without retainChanged, the event's query is sent at once. +} +// Mutation: no hold, under which row 1 leaves the view and comes back. +``` + +Write the commented assertions exactly as stated. `rowMarks(h, key)` is the last `setRowMarks` the recording backend got for the row with that key. + +- [ ] **Step 5a: Write the failing backend tests.** In `tests/qt_quick/test_qt_quick_table.cpp`: `"qt_quick table: a row's marks are drawn"` — three rows; `setRowMarks(row 0, {.unmatched = true, .tooltip = "This row no longer matches the filter"})`, `setRowMarks(row 1, {.busy = true})`, `setRowMarks(row 2, {.locked = true, .tooltip = "Being edited by another user"})`: row 0's item has the theme's muted opacity and that tooltip, row 1's shows the busy mark item, row 2's the locked hatch item and its tooltip; after `setRowMarks(row, RowMarks{})` each draws as an unmarked row. Mutation: `MorphTable.qml` ignoring `busy`, under which row 1 shows no busy mark. In `tests/tui/test_tui_table.cpp`: `"tui table: a row's marks are drawn"` — the same three rows: row 0's cells carry the dim attribute, row 1's line begins with the busy glyph, row 2's with the lock glyph. Mutation: `setRowMarks` doing nothing. + +- [ ] **Step 6: Run them; they fail.** + +Run: `cmake --build --preset cl-debug --target morph_tests && ctest --test-dir build/cl-debug -R "retained rows:" --output-on-failure` +Expected: FAIL. + +- [ ] **Step 7: Implement.** + - `changedRowsOf(reply, action, record)`: for each path of the `ActionRecordInfo` of `record`, the path names a `ChangedRows`' `rows` member (`".rows"`, or `"rows"` for the result itself); the value at the path's parent is read as `{"rows": [{"key", "from"?}], "failed": [{"key", "message"}]}`. A number is an integer key, a string a text key. + - `WindowRows::retain(keys)`: the keys not already retained are added when the set stays within `maxRetained`, else none is and the result is `OverBound`; each query from then on carries the set in `retain`. `clearRetained` empties it. `unmatched(key)` is true for a held row the last reply that supplied it listed in `unmatched`, false for a key the window does not hold; `counts().retained` counts those. `holdRefetches(run)` records the run and, while any run is recorded and for at most `SessionOptions::retainHold` from the first, makes a record event only mark what it would fetch; `releaseRefetches(run)` (or the hold's timer, on the session's scheduler) sends what was marked as one refetch. `EngineRows` maps these to `Engine::retain`, `isUnmatched` at the key's view row (false for a key not in the view), and no-op holds. + - The lowering, on a table with `retainChanged` (a literal flag, default `false`): its `RunObserver::started` calls `holdRefetches(run)` for an action whose catalog `effects` name this table's record; `settled` calls `retain` with the keys of `changedRowsOf(reply, …).rows` (and their `from` keys, Task 17c), posts the over-bound message through `tableMessage` on `OverBound` (a refusal: transient), then `releaseRefetches(run)`. A filter change and "Show only matching rows" call `clearRetained` and end a view selection. Retained rows are not part of the stored table state. + - `RowMarks` (index decision 39): `TableRowLook::marks` is bound by the lowering's `rowView` in the row's scope, as `tone` and `label` are; the mount calls `setRowMarks(row, marks)` after `setRowKey` for a row whose look has `marks`, and on every change. In this task the binding gives `RowMarks{.unmatched = rows->unmatched(key), .tooltip = unmatched ? "This row no longer matches the filter" : ""}`, `key` read from the row's record; Task 17c adds `busy`, `locked` and their tooltips to the same binding. `TableRows` and `RowStates` are not reactive, so the lowering holds one `reactive::Signal` per table (`marksRevision`), which the binding reads first and the lowering bumps after every change of the retained set, after every reply that changes a held row's `unmatched`, and (Task 17c) after every `RowStates` change; without that read a row that becomes unmatched is not drawn again. Qt Quick draws `unmatched` muted, `busy` with the theme's busy mark, `locked` with the theme's locked hatch, and `tooltip` as the row's tooltip; the terminal draws `unmatched` dim and prefixes a busy row with the busy glyph and a locked row with the lock glyph. + +- [ ] **Step 8: Run them and the targets; all pass.** + +Run: `ctest --test-dir build/cl-debug -R "retained rows:" --output-on-failure`, then all of `morph_tests`, `morph_table_tests`, and in `build/cl-qt-debug` `ctest --test-dir build/cl-qt-debug -R "a row's marks" --output-on-failure`, then all of `morph_qt_quick_tests`, `morph_tui_tests`. +Expected: PASS. + +- [ ] **Step 9: Mutations, docs, commit.** `docs/spec/ui/document.md`: `retainChanged`. Backend specs: `setRowMarks`. Docs build green. + +```bash +git add include/morph/table include/morph/ui src/ui src/qt_quick src/tui tests docs/spec +git commit -m "feat(table): keep rows an action changed in view" +``` + +### Task 17c: Key changes, busy, failed and locked rows + +**Spec:** "A key that changes" (2409–2420), "Rows at work, rows that failed" (2422–2443), "A locked row" (452–455); test rows "A key that changes", "Busy and failed rows", "Locked rows and companions" (the lock half); failure mode 3318. + +**Files:** +- Modify: `include/morph/table/description.hpp` (`ChangedRow::from` on Part A's `ChangedRow{RowId key;}`; `FailedRow`; `ChangedRows::failed`), `include/morph/core/records.hpp` (`RecordInfo::previousKeyField`), `include/morph/core/registry.hpp` (`BRIDGE_REGISTER_TABLE` sets it to `"from"`), `include/morph/core/changes.hpp` (`addUpdatesChange` collects it), `include/morph/ui/table_rows.hpp` (`RowStates`, `TableRows::states`, `TableRows::moveKey`, `lockText`, `refusesEdit`, `TableCountsView::busy`), `include/morph/ui/view.hpp` (`KeyMoves`; `keyMoves` on `ui::Table` and `TableOptions`), `include/morph/ui/mount.hpp` (the focus it holds follows a key move), `include/morph/ui/testing/recording_backend.hpp`, `src/ui/interpreter.cpp` (busy rows from inputs, failed marks, "Select them", "Clear marks", locked rows, key moves, element value `busyCount`). +- Test: `tests/net/test_push_tables.cpp`, `tests/test_ui_table_model.cpp`. +- Docs: `docs/spec/ui/document.md` (element value `busyCount`), `docs/spec/ui/view_tree.md` (a table's `keyMoves`: the mount's focus follows a row whose key changed). + +**Interfaces:** +- Consumes: Task 17a's `RunObserver`, `tableInputsOf`, `TableSelection`; Task 17b's `changedRowsOf`, `retain`, `RowMarks`; Task 15's `TableDescription::rowLock`. +- Produces: + +```cpp +namespace morph::table { +struct ChangedRow { RowId key; std::optional from; }; +struct FailedRow { RowId key; std::string message; }; +// ChangedRows: std::vector rows; std::vector failed; +} +namespace morph::model { +// RecordInfo: std::optional previousKeyField; // "from" on a table's record +} +namespace morph::ui { +class RowStates { +public: + void busyKeys(std::uint64_t run, std::vector keys); + void busyView(std::uint64_t run, std::vector except, std::int64_t count); + void settle(std::uint64_t run); + void fail(std::span rows); + void clearFailed(std::span keys); + void clearFailed(); + void move(table::RowId const& from, table::RowId const& to); + [[nodiscard]] bool isBusy(table::RowId const& key) const; + [[nodiscard]] std::optional failure(table::RowId const& key) const; + [[nodiscard]] std::int64_t busyCount() const; + [[nodiscard]] std::vector failedKeys() const; // in the order they failed +}; +// TableRows gains: +// [[nodiscard]] virtual RowStates& states() = 0; +// [[nodiscard]] virtual RowStates const& states() const = 0; +// virtual void moveKey(table::RowId const& from, table::RowId const& to) = 0; // retained and states +// TableCountsView: std::int64_t busy = 0; +[[nodiscard]] std::optional lockText(TableRowRef const& row, table::TableDescription const& description); +[[nodiscard]] bool refusesEdit(TableRows const& rows, std::int64_t index, table::TableDescription const& description); +struct KeyMoves { // view.hpp + std::uint64_t generation = 0; + std::vector> moves; // from, to + [[nodiscard]] bool operator==(KeyMoves const&) const = default; +}; +// ui::Table and TableOptions both gain (index decision 41): Prop keyMoves; +// No backend call: the selection reaches a backend through `selection` and `setSelection`, and focus is the +// mount's, held by (row key, column id) since Task 10a. +} +``` + +`refusesEdit` is what Part G's cell editing (editing.md "Read-only is one rule", Task 24) consults: a busy or locked row takes no cell edit. + +- [ ] **Step 1: Write the failing walk test** in `tests/net/test_push_tables.cpp`: `"tables: a changed key's event names both keys"` — the file's model gains `SaveAs{std::int64_t key;}` returning `{"rows": {"rows": [{"key": 10, "from": 2}], "failed": [{"key": 4, "message": "Locked"}]}}` and declaring `updatesTable<&Rows::rows>`; a watcher of `selnet::Rows.rows` receives one event whose keys are exactly `{10, 2}` (in any order) and not `4`. Mutation: the walk ignoring `from`, which leaves the old row's watchers untold (keys `{10}`). + +- [ ] **Step 2: Run it; it fails** (keys `{10}`). + +Run: `cmake --build --preset linux-everything --target morph_net_tests && ctest --preset linux-everything -R "tables: a changed key" --output-on-failure` +Expected: FAIL, keys `{10}`. + +- [ ] **Step 3: Implement.** `RecordInfo::previousKeyField` (absent by default); `BRIDGE_REGISTER_TABLE` sets it to `"from"` on the table's record; `addUpdatesChange` (`include/morph/core/changes.hpp:180`), after collecting `keyField` at each path, collects `*info->previousKeyField` at the same paths when it is set. A `failed` row is never at a `rows` path, so it is not collected. Run Step 2's command: PASS. + +- [ ] **Step 4: Write the failing client tests** in `tests/test_ui_table_model.cpp`, over the ten rows of Task 17a (no filter) and a description with `rowLock = "lockedBy"`; the mutations `save` and `touch` of the "Catalog actions" table. Each case starts with `addAction(h, "Lims_SaveAs", std::string{kSelectionSchema}, samplesAction());` and `addAction(h, "Lims_TouchRow", std::string{kRowSchema}, samplesAction());`, then `mountSelection(h, , )` with a first page of the ten rows (row 6's `lockedBy` is `"Being edited by another user"`); the document declares the `state` name `picked`, which a case sets before it runs `touch`. + +```cpp +TEST_CASE("key change: the session that ran the action moves what it holds", "[ui][table][keys]") { + // Rows 2 and 5 selected (keys), focus on row 2, row 2 failed from an earlier run, row 2 retained. + // run save; settle with {"rows":{"rows":[{"key":10,"from":2}],"failed":[]}}: selectionSet == {"keys":[10,5]} + // (key 10 in key 2's place), the mount's focus is on key 10 (the last setFocusCell names key 10's view row + // once key 10 is in the view, and no setFocusCell named another row meanwhile), states().failure(10) holds + // the message and + // failure(2) is empty, the retained set holds 10 and not 2; fireEvent(record, [10, 2]) sends one keyed query + // naming both 10 and 2. +} +// Mutation: the client ignoring `from`, which leaves 2 selected and 10 not. + +TEST_CASE("key change: the action's event before its reply", "[ui][table][keys]") { + // Rows 2 and 5 selected, focus on 2. runMutation save; fireEvent(record, [10, 2]) and the keyed reply that + // leaves 2 out of the view and holds 10, all before the reply: selectionSet still holds 2. settleMutation with + // {"rows":{"rows":[{"key":10,"from":2}],"failed":[]}}: selectionSet == {"keys":[10,5]} and the mount's focus + // is on key 10. The same with a reply that names no `from`: after settle, 2 leaves the selection and focus is + // on the row now at 2's view index. +} +// Mutation: no deferral while the run is in flight, which drops 2 before `from` names it and selects [5]. + +TEST_CASE("key change: onto a key already held", "[ui][table][keys][review]") { + // Rows 3 and 7 held; 7 and 3 selected. settle with {"rows":{"rows":[{"key":7,"from":3}],"failed":[]}}: + // selectionSet == {"keys":[7]} (7 once); fireEvent(record, [7, 3]): the keyed query names 3 and 7. +} +// Mutation: a move that appends `to` without checking it is held, which selects 7 twice. + +TEST_CASE("key change: a from the client does not hold", "[ui][table][keys]") { + // settle with {"rows":{"rows":[{"key":10,"from":99}],"failed":[]}}: nothing moves (selection, focus, states + // unchanged); the event's keyed query names 10. +} +// Mutation: a move inventing state for 99, which adds 10 to the selection. + +TEST_CASE("key change: another session's event drops the old key", "[ui][table][keys]") { + // Row 2 selected and focused; fireEvent(record, [10, 2]) with no run of this session, the keyed reply without + // row 2: 2 leaves the selection, focus moves to the row now at 2's view index. +} +// Mutation: a selection kept for keys that left the view, which keeps 2. + +TEST_CASE("busy rows: a run's rows are busy until it settles", "[ui][table][busy]") { + // Keys 1, 2 selected; run save: rows 1 and 2 drawn with RowMarks{.busy = true}; busyCount == 2; + // statusOf(h).standing == "Saving 2 rows"; refusesEdit for both. refuse(save, "lims.rows.denied"): no row is busy, + // busyCount == 0. A view selection of 6 rows less 3 held as except: every held row but 3 is busy, busyCount 5. + // run touch {"row": 4}: row 4 busy. +} +// Mutation: busy state cleared only on success, which leaves rows 1 and 2 busy after the refusal. + +TEST_CASE("busy rows: overlapping runs", "[ui][table][busy][review]") { + // Run A over keys {1,2}, run B over {2,3}: busyCount == 3. Settle A: row 2 still busy, busyCount == 2. + // Settle B: busyCount == 0. +} +// Mutation: a busy set keyed by row only, which frees row 2 when A settles. + +TEST_CASE("busy rows: two mutations' runs do not share an id", "[ui][table][busy]") { + // Mutations `save` and `touch`, each running for the first time: save over {1, 2}, touch {"row": 5}. Both + // runs are busy (busyCount == 3); settle touch: rows 1 and 2 stay busy, row 5 does not (busyCount == 2); + // settle save: busyCount == 0. +} +// Mutation: run ids taken from MutationRuntime's own counter, under which settling touch (run 1) frees save's rows. + +TEST_CASE("failed rows: marked until the row's next change", "[ui][table][failed]") { + // run save over {4, 5}; settle with {"rows":{"rows":[{"key":5}],"failed":[{"key":4,"message":"Locked"}]}}: + // row 4 has the err tone and tooltip "Locked"; statusOf(h).standing == "1 row could not be saved", standingEntries labelled "Select them" and + // "Clear marks". "Select them": selectionSet == {"keys":[4]}. An event naming 5 (the action's own): 4 stays + // marked. An event naming 4 after the run settled: the mark goes. Again failed; "Clear marks": the mark goes. + // Again failed; a new run naming row 4: the mark goes when the run starts. On a rowScoped table, an event with + // no keys leaves the mark. +} +// Mutation: a failed mark cleared by any event, which clears it on the action's own event. + +TEST_CASE("locked rows: a locked row draws locked and refuses an edit", "[ui][table][locked]") { + // Row 6's lockedBy is "Being edited by another user": RowMarks{.locked = true, .tooltip = "Being edited by + // another user"}, lockText == that text, refusesEdit true; it can be selected (click(6) selects it) and copied. + // Row 5's lockedBy is "": not locked, refusesEdit false. +} +// Mutation: lockText reading `rowTone`'s column, which locks no row. +``` + +Write each commented assertion exactly as stated. + +- [ ] **Step 5: Run them; they fail.** + +Run: `cmake --build --preset cl-debug --target morph_tests && ctest --test-dir build/cl-debug -R "key change:|busy rows:|failed rows:|locked rows:" --output-on-failure` +Expected: FAIL. + +- [ ] **Step 6: Implement.** + - `RowStates`: busy runs are kept per run (a key run's keys; a view run's `except` and the `count` it was started with); `isBusy(k)` is true when any key run holds `k` or any view run does not name `k` in its `except`; `settle(run)` drops the run whatever its outcome. **`busyCount`**: with no view run in flight, the number of distinct keys across the key runs (runs {1,2} and {2,3} count 3); with a view run in flight, the largest `count` among the view runs plus the distinct keys of key runs that every view run names in its `except` (those keys are outside the view runs' rows). `fail` records each key's message; `clearFailed(keys)` and `clearFailed()` drop marks. `move(from, to)`: moves the busy membership and the failed mark of `from` to `to`; when `to` already has one, `to`'s is kept and `from`'s dropped. + - The lowering's `RunObserver`: `started` reads `tableInputsOf(Catalog::schema(action))`; for each input naming this table's record, a `Selection` member's key selection is `busyKeys(run, keys)`, its view selection `busyView(run, except, selectedCount)`, a `Row` member `busyKeys(run, {key})`; each key the run names has its failed mark cleared. `settled` calls `settle(run)`; then, on success, with `changedRowsOf(reply, …)`: `fail(failed)`; for each row with `from` that this session holds in any way (selection, focus, retained, states), `TableRows::moveKey(from, key)`, the selection's `from` replaced by `key` (kept once if `key` is already selected), and a `KeyMoves` entry for the mount, whose generation increases; a `from` the client does not hold moves nothing. An event after the run settled clears the failed marks of the keys it names; an event with no keys clears none. + - **Held while an action is in flight.** A key leaving the view drops it from the selection, the focus and `RowStates`; but while a run of this session whose action's catalog `effects` name this table's record is in flight, that drop is deferred for the keys that left: they are kept (and still counted) until every such run has settled, so the action's own event, which can precede its reply (table.md:2396–2402), does not lose the old key a `from` then names. At settle the moves are applied first, then each deferred key that is still out of the view and was not a `from` is dropped as any key that left the view. + - The mount applies each new `KeyMoves` generation's moves to what it holds by key: when its focus (Task 10a's `(row key, column id)`) is on `from`, the focus key becomes `to` before the `ViewChange` that removes `from` is applied, so the rule "a focused row that leaves the view moves focus to the row now at its view index" does not fire for it, and `setFocusCell` follows `to` when it is in the view; a `highlightKey` on `from` moves the same way. Nothing is sent to the backend for the move itself: the selection mark moves because the lowering's `selection` now holds `to` (`setSelection`). A generation the mount has applied is not applied again. + - Drawing (index decision 39): Task 17b's `TableRowLook::marks` binding now gives `{busy = states().isBusy(key), locked = lockText has a value, unmatched = rows->unmatched(key), tooltip = lockText, else failure(key), else the unmatched text}`, and reads `marksRevision` first; the lowering bumps `marksRevision` after every `busyKeys`, `busyView`, `settle`, `fail`, `clearFailed` and `move`. A failed row's tone is `err` through `TableRowLook::tone`: the lowering's tone binding gives `Tone::Err` while `failure(key)` has a value, else the row's `rowTone`, and reads `marksRevision` too. `lockText` is the row's `rowLock` cell when it is non-empty text. `refusesEdit` is busy or locked. + - Element value `busyCount`; the standing part of the status line (not `tableMessage`) holds `"Saving " + n + (n == 1 ? " row" : " rows")` while `busyCount > 0`, and `n + (n == 1 ? " row could not be saved" : " rows could not be saved")` with the standing entries "Select them" (selection = `failedKeys()`) and "Clear marks" (`clearFailed()`), while `failedKeys()` is not empty. + +- [ ] **Step 7: Run them and the targets; all pass.** + +Run: `ctest --test-dir build/cl-debug -R "key change:|busy rows:|failed rows:|locked rows:" --output-on-failure` and all of `morph_tests`; `ctest --preset linux-everything -R "tables:" --output-on-failure` and all of `morph_net_tests`; and `morph_qt_quick_tests`, `morph_tui_tests` in `build/cl-qt-debug` (this task adds no backend call: busy and locked rows are drawn by Task 17b's `setRowMarks`, whose three flags Task 17b's backend tests cover). +Expected: PASS. + +- [ ] **Step 8: Mutations, docs, commit.** `docs/spec/ui/document.md`: element value `busyCount`. `docs/spec/ui/view_tree.md`: `keyMoves`. Docs build green. + +```bash +git add include/morph/table include/morph/core include/morph/ui src/ui tests docs/spec +git commit -m "feat(table): key changes, busy, failed and locked rows" +``` + +### Task 17d: The application's menu entries and a disabled header + +**Spec:** "The application's menu entries" (2359–2378), "The header while the application is busy" (2445–2451); test rows "The application's menu entries", "A disabled header"; invariant 31. + +**Files:** +- Modify: `include/morph/ui/view.hpp` (`cellMenu`, `headerEntries`, `headerEnabled` on `ui::Table` and `TableOptions`), `include/morph/ui/backend.hpp` (`TableWidget::setCellMenu`), `include/morph/ui/mount.hpp`, the three table widgets, `src/ui/interpreter.cpp` (`cellMenu`, `headerMenu`, `headerEnabled`; "Filter by this value", "Exclude this value", "Filter by this value in any "), `src/ui/document.cpp` (load-time checks). +- Test: `tests/test_ui_table_model.cpp`, `tests/qt_quick/test_qt_quick_table.cpp`. +- Docs: `docs/spec/ui/document.md` (`cellMenu`, `headerMenu`, `headerEnabled`), `docs/spec/ui/backend_contract.md` and `docs/spec/qt_quick/backend.md` (`setCellMenu`). + +**Interfaces:** +- Consumes: Part E's `TableOptions::menu(std::optional)` / `onMenu` and `TableWidget::setMenu` (Task 12b), `ui::headerMenu(HeaderMenuInput)`, `ui::menuEntries` and `MenuCommand::{Copy, CopyWithHeaders}` (Task 12a), its copy (Task 12f) and `ScreenCore::tableMessage` (Task 9d); Task 8a's `FilterEntry::oneOf`; Task 8b's `GroupFilter{group, columns, mode, match, combine, include, exclude}`; Task 15's `operandOf`, `cellLook`; the `menu` node's entry lowering in `src/ui/interpreter.cpp` (its `{label, icon, keys, checked, enabled, onClick, items, description, visible}` shape). +- Produces: + +```cpp +namespace morph::ui { +// ui::Table and TableOptions both gain (index decision 41; `column` an index into Table::columns, decision 37): +// std::function(Key const& row, std::size_t column)> cellMenu; // built-ins, separator, app's +// std::function(std::size_t column)> headerEntries; // the app's only +// Prop headerEnabled = true; +// TableWidget gains: +// virtual void setCellMenu(std::function(Key const& row, std::size_t column)> entries, +// std::function const& path)> chosen) = 0; +} +``` + +`path` is the chosen entry's index at each menu level. + +**Who composes a menu.** `MenuItem` (`view.hpp:715`) holds `Prop`s and an `Action`; `MenuEntry` (`backend.hpp:358`) is the plain value a backend draws. The mount owns the conversion in both menus, and the lowering never returns a `MenuItem` where a `MenuEntry` is expected: +- **Reading an item.** When a menu opens, the mount reads each item's `label`, `checked`, `enabled`, `description` and `visible` once, untracked (`runtime.untracked`), into a `MenuEntry`; hidden items and the separators they strand are left out, as `Menu` does, and the mount keeps, for that open menu, the item each entry path came from. The `Prop`s are bindings the lowering built over the scope it made for that row and column (or that column), so no scope is entered at open time. +- **A cell's menu.** `setCellMenu`'s `entries(row, column)` is the mount's conversion of `cellMenu(row, column)`; its `chosen(row, column, path)` runs the kept item's `onSelect`. +- **A header's menu.** Part E's `menu(column)` keeps returning the built-in `MenuEntry`s only, and `onMenu` keeps taking paths into them. With `headerEntries` set and a column given, what the mount hands to `TableWidget::setMenu` is `menu(column)`, then a separator entry, then the conversion of `headerEntries(column)` (nothing is appended when it converts to no entry); a chosen path whose first index is below `menu(column).size()` goes to `onMenu` unchanged, and one past the separator runs the kept item's `onSelect` with its first index less `menu(column).size() + 1`. The table's own menu (no column) is `menu(nullopt)` alone. + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_table_model.cpp`, each over a `TableHarness` and a whole document (`doc(view)`, with the `state` names `picked`, `opened` and `idle` the cases set and read through `elementValue`), over a model-backed table with columns `id`, `mass` (Decimal), `companyA`/`companyB` (Text, declared group `company`, label "Company") and `"selectionMode":"multiple"`: + +```cpp +TEST_CASE("table menus: the application's entries read the row, the column and the value", "[ui][table][menu]") { + // cellMenu [{"label": {"fn":"concat","args":[{"ref":"column"}," = ",{"ref":"value"}," of ",{"ref":"row.id"}]}, + // "onClick": [{"set":"picked","to":{"ref":"row.id"}}]}]: + // rightClickCell(table, 2, ): the menu of row 2's mass cell is ["Copy", "Copy with headers", "Filter by this value", "Exclude this value", + // separator, "mass = 0.2 of 2"]; choosing the last sets picked to 2. + // Rows 1 and 3 selected, a right-click on row 2: the selection is {"keys":[2]}; a right-click on row 1 while + // 1 and 3 are selected keeps both. + // headerMenu [{"label":"Units…","visible":{"fn":"eq","args":[{"ref":"column"},"mass"]}}]: menuOf(table, ) + // ends with a separator and "Units…"; the id header's has no "Units…". +} +// Mutation: the cell menu read in the table's scope, which reads `row` as null. + +TEST_CASE("table menus: filter by this value", "[ui][table][menu]") { + // "Filter by this value" on mass 0.2: filters == {"columns":{"mass":{"include":[{"oneOf":["0.2"]}]}}}, + // replacing mass's earlier entries. "Exclude this value" on 0.3 then 0.4: exclude == [{"oneOf":["0.3","0.4"]}]. + // On an empty cell: include == [{"isEmpty":true}]. On an unloaded cell both entries are disabled. + // On companyA "F": the menu has "Filter by this value in any Company", which sets + // groups == [{"group":"company","include":[{"oneOf":["F"]}]}]. +} +// Mutation: "Filter by this value" adding to include instead of replacing it, which keeps the earlier entry. + +TEST_CASE("table menus: an entry's keys work while the table has focus", "[ui][table][menu]") { + // cellMenu [{"label":"Open","keys":"Ctrl+O","onClick":[{"set":"opened","to":{"ref":"row.id"}}]}], focus on + // row 3: Ctrl+O sets opened to 3; with focus elsewhere, Ctrl+O does nothing. A query of this table names + // the columns the entries read (`id`) for every row. +} +// Mutation: keys bound only while the menu is open. + +TEST_CASE("table menus: a disabled header", "[ui][table][header]") { + // headerEnabled {"ref":"idle"}, idle false: clickHeader, clickFilter and moveColumn change nothing, + // send no query, and each sets statusOf(h).message to "Sorting, filtering and arranging are unavailable right now"; + // selecting, copying and cellMenu entries still work. idle becomes true: a header click sorts. +} +// Mutation: headerEnabled read once at mount, which leaves the header enabled after the condition turns false. +``` + +And in `tests/qt_quick/test_qt_quick_table.cpp`: `"qt_quick table: a right-click opens the cell menu on that cell and selects its row alone"` — rows 1 and 3 selected, a right-click on row 2's second cell: the backend's `onSelectionChange` reports `Replace` `{2}`, the focused cell is (2, 1), and the popup's entries are the ones `setCellMenu` returned; the menu key on the focused cell opens the same menu. Mutation: the menu opened without moving focus. + +Write each commented assertion exactly as stated. + +- [ ] **Step 2: Run them; they fail.** + +Run: `cmake --build --preset cl-debug --target morph_tests && ctest --test-dir build/cl-debug -R "table menus:" --output-on-failure`; `cmake --build build/cl-qt-debug --target morph_qt_quick_tests && ctest --test-dir build/cl-qt-debug -R "qt_quick table: a right-click" --output-on-failure` +Expected: FAIL. + +- [ ] **Step 3: Implement.** + - The lowering builds `cellMenu(row, column)`: "Copy" and "Copy with headers" (Part E's `MenuCommand::Copy` / `CopyWithHeaders`), "Filter by this value", "Exclude this value", for a column of a declared group "Filter by this value in any " + the group's label, a separator, then the document's `cellMenu` entries lowered in the row's scope with `column` (the column's id) and `value` (the cell as a document value) bound beside `row`. Its `headerEntries(column)` is the document's `headerMenu` lowered in a scope with `column`; the lowering's `menu(column)` and `onMenu` stay Part E's (`ui::menuEntries(ui::headerMenu(input))` and the built-in commands), and the mount appends and routes the application's entries as "Who composes a menu" says. + - "Filter by this value": the column's filter becomes `{include: [{oneOf: [operandOf(cell)]}]}`; "Exclude this value": `operandOf(cell)` is appended to the column's `exclude` `oneOf` entry, made when absent; an empty cell uses `{isEmpty: true}`; both are disabled when `cellLook` is `Unloaded` or `Invalid`. The group entry sets the filter of group `` to `{group: id, include: [{oneOf: [operand]}]}`, replacing that group's filter. + - A right-click, the menu key or a long press on a cell focuses it, makes the selection that row alone when it is not selected (reported as `Replace`), and opens the menu `setCellMenu`'s `entries` returns. An entry's `keys` are bound while the table has focus and run the entry for the focused cell. The columns the entries' expressions read are fetched for every row, as `rowTone`'s are (Task 9's column analysis). + - `headerEnabled` (a condition, default `true`) is a `Prop` on `ui::Table` and `TableOptions`: while false, the mount disables the header-menu entries whose `MenuCommand` sorts, filters or arranges, `Columns` and `SortDialog` included (all but `Copy` and `CopyWithHeaders`), and the refusal itself is the lowering's: its `onSort`, `onFilter`, `onGroupFilter`, `onColumnMove` and `onColumnResize` handlers (Part E) read `headerEnabled` when called, change nothing, and post the message in the test through `ScreenCore::tableMessage`. The mount, which cannot reach `ScreenCore`, only greys the entries. Selection, scrolling, copy and the application's entries stay. + - `src/ui/document.cpp`: `cellMenu` and `headerMenu` take the `menu` node's entry shape and are reported as its entries are. + +- [ ] **Step 4: Run them and the targets; all pass.** Step 2's commands, then all of `morph_tests`, `morph_qt_quick_tests`, `morph_tui_tests`. Expected: PASS. + +- [ ] **Step 5: Mutations, docs, commit.** `docs/spec/ui/document.md`: `cellMenu`, `headerMenu`, `headerEnabled`. Backend specs: `setCellMenu`. Docs build green. + +```bash +git add include/morph/ui src/ui src/qt_quick src/tui tests docs/spec +git commit -m "feat(ui): application entries in table menus and a disabled header" +``` diff --git a/docs/superpowers/plans/2026-11-17-one-table-g-editing.md b/docs/superpowers/plans/2026-11-17-one-table-g-editing.md new file mode 100644 index 000000000..61b5dc239 --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-one-table-g-editing.md @@ -0,0 +1,1659 @@ +# Editing in the Table — Implementation Plan (Part G) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build `docs/spec/table/editing.md`: grids of a form, derived values, cell selection with paste and fill, row operations, header bands, spans, summary rows, fixed grids, and cells of a model's table edited through `CellEdit` and `RowEdit` actions. + +**Architecture:** A grid is a form's `ObjectArray` field laid out by the table pipeline: `ui::FormRowsSource` is the `table::DataSource` over the field's `RowState`s, and `ui::GridController` owns focus, the editor, the walk, cell selection, paste, fill, clear and row operations over a `ui::GridSource`, which a form grid, a fixed grid and a model's table each implement. Every read-only decision is one function, `ui::cellReadOnly`. Derived values are rounds of the form session (`FormSession::noteCommit`, `loadDerived`) over the action's evaluation and the form's derive action; the server recomputes row members and clears derived ones. Bands, spans and summary rows are the mount's, for any table. + +**Tech Stack:** C++23, CMake (MSVC preset `cl-debug`), header-only morph, glaze, Catch2, Qt 6 Quick (offscreen `morph_qt_quick_tests` only), the terminal backend (`morph_tui_tests`). + +**Spec:** `docs/spec/table/editing.md` — all sections: "Two homes for an edit", "A grid of a form", "Cells of a model's table", "The cell", "Walking", "Selecting cells, clipboard and fill", "Rows of a grid", "Layouts", "Document vocabulary", "Invariants" (1–9), "API surface", "Tests", "Failure modes", "Neighbouring specs", "Delivery order" steps 1–6. It builds on `docs/spec/table/table.md` ("The client table model", "The renderer", "How a column shows its cells", "Acting on rows") and `docs/spec/forms/engine.md`. Roadmap: `docs/superpowers/plans/2026-11-17-one-table.md` (Tasks 19–24, its Global Constraints, standard task loop and Review Focus items 3 and 5). + +Part G of 7; index: 2026-11-17-one-table.md + +## Global Constraints + +Every constraint of the roadmap's "Global Constraints" applies; the ones that bite here, and this part's own: + +- Comments and specs state what the code does now and why; no history, no issue numbers, no commit hashes (AGENTS.md). +- Every public symbol has complete Doxygen `@param`/`@tparam`/`@return`. Docs build: `cmake -S . -B build/doc -G Ninja -DMORPH_BUILD_DOCUMENTATION=ON -DMORPH_BUILD_TESTS=OFF -DMORPH_BUILD_EXAMPLES=OFF && cmake --build build/doc --target doc` — exits 0. +- morph is public: test fixtures use the neutral `lims` domain (`Lims_RecordSpecimens`, `Lims_SetLimits`, `Lims_EditSpecimenCount`); no company or customer name anywhere. +- Commits are authored `yaraslau ` and end with the session's attribution lines. +- No GUI application is launched; Qt Quick behaviour is tested only in `morph_qt_quick_tests` (ctest sets `QT_QPA_PLATFORM=offscreen`). +- Every test below names its mutation; step "Mutate" of each task applies it by hand, runs the test, sees it fail, reverts, and pastes the failing line into the commit body. +- Values the spec pins, verbatim: `deriveDebounce` default **150 ms**; bands nest at most **3** levels; `enterMoves` default `down`; `walk` default `rows`; `editMode` default `cell`; summary `position` default `bottom`; a span's `rows` and `columns` default **1**; a block row's key is `"/"`. +- A neighbouring spec takes its part only in the task whose step its row names (editing.md "Neighbouring specs"), and says nothing of it before. +- The read-only rule is one function. No code path decides read-only, the read-only surface or a place in the walk except through `ui::cellReadOnly` (Invariant 4). +- **A `column` argument is an index into `Table::columns`** (index #37), which holds every column, hidden ones included: every `Table` handler, `TableWidget` call and `RecordingBackend` driver this part adds or uses (`setFocusCell`, `setOnCellClick`, `setCellEditor`, `setCellMarks`, `clickCell`). A visible place in the layout is always named `position` (`setCellSelection`, `setOnCellSelect`, `selectCells`, `BandRun::first`). +- **`ui::Table` and `TableOptions` are parallel** (index #41): every member a task below adds to `Table` it adds to `TableOptions` with the same name and type, and `table(…)` copies it across. +- **Tests that mount a document** use `ui::testing::TableHarness` (`tests/ui_table_support.hpp`, index #42): a whole document with a `models` block and an alias, the task's actions added to its catalog with their schema text, `effects` and `records`, and the free-function helpers (`elementValue(h, id, name)`, `cellMarks`, `rowMarks`, `menuOf`, `clipboardText`). Its locale is `en`. +- **The loader** (`src/ui/document.cpp`) accepts each new key in the task that lowers it, with a loader test in that task (index #44). + +**Commands** (verified against `tests/CMakeLists.txt`, `tests/qt_quick/CMakeLists.txt`, `tests/tui/CMakeLists.txt`, `CMakePresets.json`): + +```bash +cmake --preset cl-debug # once per tree +cmake --build --preset cl-debug --target morph_tests # test_ui_*.cpp, tests/forms/*.cpp +cmake --build --preset cl-debug --target morph_table_tests # tests/table/*.cpp +ctest --test-dir build/cl-debug -R "" --output-on-failure +# Qt Quick (offscreen, ctest sets the platform) and the terminal backend, one tree: +cmake --preset cl-qt-debug -DMORPH_BUILD_QT_QUICK=ON -DMORPH_BUILD_TUI=ON +cmake --build --preset cl-qt-debug --target morph_qt_quick_tests morph_tui_tests +ctest --test-dir build/cl-qt-debug -R "" --output-on-failure +# morph_net_tests is POSIX-only: build and run it on linux-everything +cmake --preset linux-everything && cmake --build --preset linux-everything --target morph_net_tests +ctest --test-dir build/linux-everything -R "" --output-on-failure +``` + +## Interfaces consumed from Parts A–F + +Names the roadmap pins are used as it gives them. Rows marked **assumed** are not pinned by the roadmap; this part uses exactly these names, and the executor checks them against the landed code before Task 19 starts and corrects this plan (not the other part) if they differ. + +| From | Name | Pinned by | +|---|---|---| +| Task 1 | `table::TableColumn{ColumnInfo info; std::string label, group; bool sortable, filterable, shown;}`, `table::TableDescription{id, label, columns, key, groups, levels, units, revision}`, `table::describe` | roadmap | +| Task 2 | `table::ChangedRow`, `ChangedRows`, `BRIDGE_REGISTER_TABLE`, `effects::updatesTable`, the record `.` | roadmap | +| Task 3 | `table::Unloaded`, `TableErrorCode::SourceContract`, `CellEdits::commit` refusing an unloaded cell with `FieldError{"…", "not loaded yet"}` | roadmap, table.md | +| Task 8d | `table::ColumnLayout::{setPinned, pinned, value, apply}` with `value()`/`apply` over `table::ColumnLayoutValue{order, hidden, pinned, widths, groups, units}`; existing `setVisible`, `visible`, `move`, `order` | index #7, Part C | +| Task 9 | `ui::TableRows`, `EngineRows`, `WindowRows`, `TableRowRef`, `TableCountsView`, `SortChain`; `WindowRows::setDescription(table::TableDescription)` and `onStaleDescription(std::function)` (the lowering refetches the description and calls `setDescription`) | roadmap, Part D | +| Task 9 | `EngineRows(std::shared_ptr source, RecordOf recordOf, table::EngineOptions options)`; `struct RowRecord { table::RowId key; Value row; }`; `using RecordOf = std::function` (an owning record, memoised by `EngineRows`); `TableRows::row(index)` empty for a row not fetched yet, `TableRows::total()` | index #21, #28, Part D | +| Task 9 | `ui::TableStatus{counts, state, retry, message, shown}`, `Table::status`; `ui::TableColumn::id`; `ui::TableArrangement{visible, pinned, widths}`, `Table::arrangement` | index #11, #14, Part D | +| Task 10a | Mount-held focus `(row key, column id)`; `TableWidget::setFocusCell(std::size_t viewRow, std::size_t column)` (`column` an index into `Table::columns`, index #37), `setOnFocusMove(std::function)`, `enum class FocusMove { Up, Down, Left, Right, Home, End, First, Last, PageUp, PageDown }` | Part D | +| Task 11 | `ui::ValueRowsSource` | roadmap | +| Task 12b | `IViewBackend::copyText(std::string_view) -> bool` | index #12, Part E | +| Task 9d | `void ScreenCore::tableMessage(ElementState& table, std::string text)` (`tableMessage(table, "")` clears the message; 6 s hold, `kStatusMessageHold`); every grid and model-table message is posted through it | index #11, Part D | +| Task 15 | `ui::formatCell(table::Cell const&, table::TableColumn const&, ui::FormatContext const&, DisplayUnits const& = {}) -> std::string`; `ui::FormatContext` (`ui/expression.hpp`), `ui::localeFacts`, `ui::withoutGrouping`; `TableColumn::{display, tone, tooltip}`; `TableDescription::{rowTone, rowLock}` | index #9, Part F | +| Task 17a | `forms::DeclaresSchemaValue` (a type's `schemaValue()` returning `{keyword, name}`, written by `annotateSchemaMarker` on the **property** of a member of that type), `name` the `RecordInfo::name` in `model::recordRegistry()` whose `type` is `typeid(TableOf)`; `TableInputKind`, `TableInput{member, record, kind}`, `tableInputsOf(std::string_view schemaJson)` (top-level properties only), `RunObserver` (called by `MutationRuntime`, so only for runs the session's mutations make) | Part F | +| Task 17a | `ui::StatusEntry{std::string id; std::string label;}` (by value); `TableStatus::{entries, standing, standingEntries}`; `ScreenCore::tableMessage(ElementState&, std::string text, std::vector entries)`; `TableWidget::setOnStatusEntry(std::function)`. A transient notice with a choice is a message with entries; a state that lasts while its source holds is `standing` | index #19, Part F | +| Task 17d | `TableOptions::cellMenu` (`std::function(Key const& row, std::size_t column)>`: built-ins, separator, the application's), `TableWidget::setCellMenu`; Part E's `TableOptions::menu(std::optional)` | Part F, Part E | +| Task 17c | `ChangedRow::from`, `FailedRow`, `ChangedRows::failed`; `ui::RowStates` via `TableRows::states()` (`isBusy(key)`, `failure(key)`, `busyCount()`), `TableRows::moveKey(from, to)`, `ui::lockText(TableRowRef const&, TableDescription const&)`, `ui::refusesEdit(TableRows const&, std::int64_t index, TableDescription const&)` | index #10, Part F | +| Task 15 | `ui::CellAccent{optional tone; std::string tooltip; bool invalid}`, `accentedCell(Node content, Prop accent)`, `TableWidget::setCellAccent(row, column, accent)`: a lowered `cellView` returns an `accentedCell`, which this part wraps in `markedCell` | index #39, Part F | +| Task 17b | `TableRowLook::marks` (`std::optional>`), `TableWidget::setRowMarks` | index #39, Part F | +| Task 9 | `TableRows::onChange` is one slot, set by the mount; this part never subscribes a second time and wraps the rows in a forwarding decorator instead | index #40, Part D | +| Task 9d | `ui::testing::TableHarness`, `elementValue`, `cellMarks`, `rowMarks`, `statusOf`, `replyDescribe`, `replyPage` in `tests/ui_table_support.hpp` | index #42, Part D | + +## File structure + +| File | Responsibility | Task | +|---|---|---| +| `include/morph/ui/view.hpp` | `CellRef`, `KeyOutcome`; `Table::onKey`, `keyChords`, `onText`, `onGridFocus`, `onActivateCell`, `onFocusOut`, `editing`, `editor`; `CellMarks`, `MarkedCell`, `markedCell`, `TableRowLook::modified`; `CellRange`, `Table::cellSelection`, `onCellSelect`; `RowSpan::columns`; `TableRowLook::summary`; `BandRun`; `Table::bands`; `GridFocus` | 19, 21, 22 | +| `include/morph/ui/mount.hpp` | The focus chain, `Mounted::focusNext/focusPrevious`; the cell editor in place of a cell; cell marks bound in each cell's own scope (`MarkedCell`); the cell rectangle; `bandRuns`, `columnUnitShown`, `bandedHeaderName`; `cutColumns`; summary rows | 19, 21, 22 | +| `include/morph/ui/backend.hpp` | `TableWidget::setOnText`, `setOnCellClick`, `setOnFocusOut`, `setCellEditor`, `setCellMarks`, `setRowModified`, `setCellSelection`, `setOnCellSelect`, `setBands`, `setRowSummary` (all with no-op defaults); the Tab contract | 19, 21, 22 | +| `include/morph/ui/testing/recording_backend.hpp` | Drivers `typeInto`, `clickCell`, `focusOut`, `selectCells`; records `marks:`, `modified`, `editor:`, `cellSelection` | 19, 21 | +| `include/morph/forms/engine/field_control.hpp` (new) | The scalar controls of a field, moved out of `form_view.hpp` so `grid.hpp` and `form_view.hpp` both include them and neither includes the other's includer | 19 | +| `include/morph/forms/engine/form_view.hpp` | Includes `field_control.hpp` and `ui/grid.hpp`; draws an `ObjectArray` whose widget is `grid` with `ui::formGrid` | 19 | +| `include/morph/ui/form_rows.hpp` (new) | `FormRowsSource` | 19 | +| `include/morph/ui/grid.hpp` (new) | `GridColumn`, `GridOptions`, `CellFacts`, `cellReadOnly`, `GridSource`, `FormGridSource`, `GridRows`, `GridController`, `formatOf`, `FormGrid`, `makeFormGrid`, `formGrid`, `PasteResult`, `pasteMessage`, `SummaryRows`, `SummarySpec`, `summaryScopeRows`, `FixedGridSource`, `ModelGridSource`, `ModelColumn` | 19–24 | +| `include/morph/forms/derive.hpp` (new) | `DeriveOf`, `Derived`, `derived<>()`, `clearDerived`, `DeriveOptions`, `DeriveRound`, `DeriveLoad`, `DeriveState` | 20 | +| `include/morph/forms/forms.hpp` | `FieldMeta::derived`, `withDerived()`; `x-derived`; row types' `computedFields` in the schema and in `recomputeAll` | 20 | +| `include/morph/forms/engine/field_model.hpp` | `FieldSpec::computed`, `derived`, `minItems`, `maxItems` | 19, 20, 21 | +| `include/morph/forms/engine/form_session.hpp` | Per-cell snapshots, `modified`, `rowModified`, `revert`; `field()` by row key; `onBeforeSubmit`; rounds; `insertRow`, `removeRows`, `restoreRows`; row-scoped and shared Choice options | 19–21 | +| `include/morph/core/registry.hpp` | `clearDerived` in `prepareAction` and `evaluateAction` | 20 | +| `include/morph/table/description.hpp` | `BandInfo`, `TableDescription::bands`, `checkBands`; `EditInfo`, `TableColumn::edit` | 22, 24 | +| `include/morph/table/edits.hpp` | Includes `description.hpp` and `forms/engine/field_model.hpp`. `CellEdit`, `RowEdit` (each with an in-class glaze meta), `checkEdits`; `CellEdits` row commits, drafts by key, `moveRow`, `keepColumns`, `rowAbsent` | 24 | +| `include/morph/forms/forms.hpp` | `annotateSchemaRoot`: the action's own `schemaValue()` at the schema root | 24 | +| `src/ui/document.cpp`, `src/ui/interpreter.cpp`, `include/morph/ui/interpreter.hpp` | Vocabulary, refusals, lowering, element values | 19–24 | +| `src/qt_quick/table.cpp` + QML, `src/tui/table_widget.cpp` | Editors in cells, marks, bands, spans, summary rows | 19, 22 | +| `tests/test_ui_grid.cpp` (new), `tests/forms/test_forms_derive.cpp` (new), `tests/grid_test_support.hpp` (new) | Grid and derive tests and their fixtures: `GridFixture` (19), `FixedGridFixture` (23), `FakeRows` and `ModelGridFixture` (24) | 19–24 | +| `tests/tui/test_tui_table.cpp` | The terminal grid: editor in a cell, Tab, bands | 19, 22 | + +## Review Focus + +1. **An empty grid** (roadmap Review Focus 3). A grid over an `ObjectArray` with no rows: `Tab` leaves the table at once; a paste with `appendRows` adds the block's rows up to `maxItems`, without it drops every value and the status line counts them; a summary shows `count` 0 and an empty `mean`. Tests: Task 19 `"grid: an empty grid lets Tab leave at once"`, Task 21 `"grid: paste into an empty grid"`, Task 22 `"summary: over no rows"`. +2. **Bands under a stored layout** (roadmap Review Focus 5). A stored layout hides every column of a band, then one is shown again: the band reappears over that one column with its unit; a band whose columns are all pinned draws only in the pinned part. Test: Task 22 `"bands: a stored layout hides then shows a band's column"`. +3. **Clipboard text from a spreadsheet.** A spreadsheet copies `"1,5\t2\r\n3\t4\r\n"`: CRLF line ends, a trailing line break, values padded with spaces, grouped numbers (`"1.234,5"` in a comma locale). The block is 2 × 2, no value holds `\r`, no empty third row is pasted or appended, `" 12,5 "` is 12.5 and `"1.234,5"` is 1234.5. Test: Task 21 `"grid: spreadsheet clipboard text pastes as typed values"`. +4. **A row fetch that arrives before the edit's reply.** The action's change event can reach the client before its reply (table.md "Rows an action changed"), so the window refetches the edited row while the cell is still stale. The cell stays stale with the committed text until the reply, and is modified from the reply until the next fetch after it. Test: Task 24 `"cell edits: a fetch before the reply keeps the cell stale"`. +5. **A description revision that removes an edited column** (roadmap Review Focus 1, editing half). A model table holds a draft and an error in column `count` when the description's new revision drops `count`: the draft and its error are gone, `errorCount` falls by one, and nothing is committed for it. Test: Task 24 `"cell edits: a new revision drops drafts of a removed column"`. + +--- + +## Phase B — editing (`editing.md`) + +### Task 19: The focus chain and a grid of a form (editing.md step 1) + +**Spec:** editing.md "A grid of a form" (Binding, Columns are fields, Submission), "The cell" (all), "Walking", Invariants 1, 2, 4, 5; Delivery order step 1. Needs Tasks 9–11, 15, 17a, 17c and 17d (index #45): Task 10a's focus, Task 17a's status entries, Task 17c's `states()` and `moveKey` (pure virtuals `GridRows` answers) and Task 17d's `cellMenu`. + +**Files:** +- Modify: `include/morph/ui/view.hpp`, `include/morph/ui/backend.hpp`, `include/morph/ui/mount.hpp`, `include/morph/ui/testing/recording_backend.hpp` +- Create: `include/morph/ui/form_rows.hpp`, `include/morph/ui/grid.hpp`, `tests/grid_test_support.hpp`, `tests/test_ui_grid.cpp` (add to `morph_tests` in `tests/CMakeLists.txt`) +- Create: `include/morph/forms/engine/field_control.hpp` (the helpers `isSet` … `controlCommon`, `optionSelect` and every scalar case of `fieldControl`, moved verbatim from `form_view.hpp` into `forms::detail::engine::scalarControl(FormSession& session, FieldState& state)` (the session stays a parameter: the date and date-time cases read `session.options().displayOffsetMinutes` and `session.pattern(date)`, `form_view.hpp:255-272`); it includes `form_session.hpp` and `ui/view.hpp`, never `form_view.hpp` or `grid.hpp`) +- Modify: `include/morph/forms/engine/form_session.hpp`, `include/morph/forms/engine/field_model.hpp` (`FieldSpec::computed`), `include/morph/forms/engine/form_view.hpp` (includes `field_control.hpp` and `../../ui/grid.hpp`; `fieldControl` calls `scalarControl(session, state)` for every scalar kind and draws an `ObjectArray` whose `spec().widget == "grid"` with `ui::formGrid`), `src/ui/document.cpp`, `src/ui/interpreter.cpp`, `include/morph/ui/interpreter.hpp`, `tests/ui_interpreter_support.hpp` (catalog schema `Lims_RecordSpecimens`) +- Modify: `src/qt_quick/table.cpp` and its QML, `src/tui/table_widget.cpp` (cell editors, `setOnText`, `setOnCellClick`, `setOnFocusOut`, `setCellEditor`, marks); `tests/qt_quick/test_qt_quick_table.cpp`, `tests/tui/test_tui_table.cpp` + +**The include order.** `fieldControl` (the forms control a cell editor is) lives in `form_view.hpp`, and `form_view.hpp` must draw a grid, so `grid.hpp` including `form_view.hpp` while `form_view.hpp` includes `grid.hpp` would be a cycle. The scalar controls move to `field_control.hpp`; `grid.hpp` includes `field_control.hpp`, `form_session.hpp`, `ui/view.hpp`, `ui/table_rows.hpp` and `ui/expression.hpp`; `form_view.hpp` includes `grid.hpp`. Verified against the code: `form_view.hpp` includes `ui/view.hpp`, `form_session.hpp`, `overrides.hpp` (lines 25–33) and defines `fieldControl` at line 210, whose scalar cases read the session and the field and no `ViewOptions` member (only the `Object`/`ObjectArray` cases do, through `fieldCell`). +- Docs: `docs/spec/ui/view_tree.md` (`markedCell`: a cell's marks are its cell view's, bound with the cell and rebound with it), `docs/spec/ui/backend_contract.md` (focus chain, `focusNext`/`focusPrevious`, `setOnText`, Tab delivered to a widget that declares it), `docs/spec/forms/engine.md` (the grid widget leaves "Not supported"; per-cell snapshots, `modified`, `revert`), `docs/spec/ui/document.md`, `docs/spec/ui/interpreter.md` (`form`/`field` on `table`, the `grid` overlay, `enterMoves`, `walk`, element values), `docs/spec/qt_quick/backend.md` (editors inside cells, cell and row marks), `docs/spec/table/table.md` (check it points to editing.md and lists `TableColumn::edit`, `TableDescription::bands`; add what is missing). + +**Interfaces:** +- Consumes: `ui::TableRows`, `EngineRows` (Task 9); `ValueRowsSource` (Task 11); `ui::formatCell` (Task 15); Task 10a's mount-held focus, `TableWidget::setFocusCell(viewRow, column)` (`column` an index into `Table::columns`) and `setOnFocusMove(FocusMove)`; Task 15's `accentedCell` (index #39); `ui::TableColumn::id`, `Table::arrangement` and `TableStatus::message` (Task 9); `ScreenCore::tableMessage` and `TableStatus::{standing, standingEntries}`, `StatusEntry` (Tasks 9d, 17a; index #19); `TableOptions::cellMenu` (Task 17d); `forms::FormSession` (`options()` gives `locale`, `bcp47`, `datePattern`, `dateTimePattern`), `FieldState`, `RowState`, `forms::detail::engine::fieldControl` (existing, its scalar part moved to `scalarControl(session, state)`). +- Produces: + - `view.hpp`: `struct CellRef { Key key; std::string column; bool operator==(CellRef const&) const = default; };` `struct GridFocus { std::optional key; std::size_t viewRow = 0; std::string column; bool operator==(GridFocus const&) const = default; };` — a focused cell as the mount shows it: `key` is empty while the row at `viewRow` is not fetched yet (a placeholder), `column` a column id. `Table::gridFocus` (`std::optional>>`, not `focus`, which names the mount's own focused cell already: when set, the table's focus is the grid's, and the mount shows it with Task 10a's `setFocusCell(viewRow, column)`, `viewRow` the key's view position now, or `GridFocus::viewRow` while `key` is empty, and `column` the index into `Table::columns` of the column with that id; a focused view row stays realized, key or not, so the window fetches a placeholder) and `Table::onGridFocus` (`std::function`: a click or a `FocusMove` the mount resolves to a cell — `key` empty when that row is not fetched — handed to the grid instead of moving the mount's own focus); `Table::onActivateCell` (`std::function`: a double click on a cell); `Table::onFocusOut` (`std::function`: focus left the table's widget and everything inside it, an open editor included); `Table::editing` (`std::optional>>`) and `Table::editor` (`std::function`): while `editing` names a cell, the mount builds `editor(cell)` once, mounts it as a child of that cell's row widget, calls `TableWidget::setCellEditor(row, column, &widget)` (`column` the index into `Table::columns`) and `widget.focus()`; when `editing` changes it calls `setCellEditor(row, column, nullptr)` and unmounts the editor (a focused cell's row stays realized, Task 10a, so the editor's row is never pooled while it is open); `enum class KeyOutcome : std::uint8_t { Handled, Ignored, FocusNext, FocusPrevious };` `Table::onKey` (`std::function`), `Table::keyChords` (`Prop>`, re-declared to the backend with `setKeys` on each change), `Table::onText` (`std::function`); `struct CellMarks { bool readOnly = false; bool modified = false; bool error = false; bool stale = false; bool muted = false; bool operator==(CellMarks const&) const = default; };` Marks are a cell's, drawn by its cell view (index #28), not a row's: `struct MarkedCell { Node content; Prop marks; };` and `[[nodiscard]] Node markedCell(Node content, Prop marks)` — a node a `TableSource::cellView` returns (or a cell of a `TableRowView`). The mount mounts `content` as the cell and binds `marks` in the cell's own scope, calling `TableWidget::setCellMarks(row, column, marks)` (`column` the cell's index into `Table::columns`, as `setCellLoad` and `setCellAccent` take it) after the row's key, on every change, and whenever a pooled cell is attached to another row widget (Task 10a), whether or not the marks changed. Because the binding lives with the cell and reads the cell's own row signal, a pooled cell rebound to another row (its signal set) re-evaluates its marks with its content; nothing per row holds them. Anywhere but a table cell a `MarkedCell` mounts its content and its marks are not read. Its `content` may be Task 15's `accentedCell` (index #39: a cell view is `markedCell(accentedCell(content, accent), marks)`); the mount binds the accent and the marks of the one cell, each in the cell's scope. The row's own mark is `TableRowLook::modified` (`std::optional>`, bound in the row's scope by `rowView`; the mount calls `TableWidget::setRowModified`), beside Task 9d's `tone`, `label`, `spans` and `heading` and Task 17b's `marks`. Every `Table` member above has its twin on `TableOptions` (index #41). + - `backend.hpp` (every new member has a default that does nothing): `virtual void TableWidget::setOnText(std::function onText)` (printable text typed while a cell has focus and no editor is open); `virtual void TableWidget::setOnCellClick(std::function onClick)` (`column` the index into `Table::columns`, index #37; a single click calls it with `false`, the second click of a double click with `true`); `virtual void TableWidget::setOnFocusOut(std::function onFocusOut)` (focus moved to a widget outside the table, its editor and its popups); `virtual void TableWidget::setCellEditor(Widget& row, std::size_t column, Widget* editor)` (`column` the index into `Table::columns`; draws `editor`, a child of `row`, over the cell's area in place of its content; null draws the cell again); `virtual void TableWidget::setCellMarks(Widget& row, std::size_t column, CellMarks const& marks)`; `virtual void TableWidget::setRowModified(Widget& row, bool modified)`. Contract: a widget whose `setKeys` lists `Tab` or `Shift+Tab` receives them instead of moving focus. Verified against the code: `TableWidget` (`backend.hpp:764`) has `setOnActivate(std::function)` for a row and no cell click, and no widget has a focus-out callback; `Widget::setKeys` and `Widget::focus` exist (`backend.hpp:91`, `:94`). + - **Chords.** `GridController::keyChords()` (tracked) is what `Table::keyChords` binds. With no editor open: `Tab`, `Shift+Tab`, `Enter`, `F2`, `Space`, `Delete`, `Escape`, `Ctrl+Enter`, and from Task 21 `Shift+Up`, `Shift+Down`, `Shift+Left`, `Shift+Right`, `Ctrl+A`, `Ctrl+C`, `Ctrl+V`, `Ctrl+D`, `Ctrl+Shift+=`, `Ctrl+-` (plain arrows are Task 10a's `FocusMove`). With an editor open: exactly `Enter`, `Tab`, `Shift+Tab`, `Escape`, `Ctrl+Enter`, so every other key (arrows, `Home`, `End`, `Delete`, `Ctrl+C`/`Ctrl+V` on the text, `Alt+Down` on a dropdown) reaches the editor. The editor is `GridSource::editor(key, column)`: `scalarControl(session, field)` for a form's field, or for the `value` field of a model cell's edit session (Task 24); its `TextInput` is drawn with no `onCommit`, so `Enter` is the table's alone. A cell whose `GridSource::toggles` is true (a `Boolean`) has no editor (`Space` toggles it). + - **Where the editor's text lives.** In the field's draft, live: the editor is bound to `field->text()`, so every keystroke is the cell's draft at once (what `Escape` "restores the draft the cell had when it opened" presupposes, editing.md line 269). When the editor opens, the controller keeps the draft the cell held (`GridSource::draft`) and, for typing on a focused cell, writes the typed text with `write`. `Escape` writes the kept draft back with `write` and closes; it calls no `committed()`. **Commit** closes the editor and calls `committed()` exactly once when the draft differs from the kept one, and not at all when it is equal; it writes nothing, the draft being there already. `GridController::type(text)` with an editor open is `write(cell, text)` — what the editor's input does through its own binding — and exists so a test can drive a grid with no mounted editor. + - `mount.hpp`: `bool Mounted::focusNext(std::string_view focusId)`, `bool Mounted::focusPrevious(std::string_view focusId)`; the mount answers a table's `KeyOutcome::FocusNext`/`FocusPrevious` by moving focus along the chain from the table's widget. The chain is the mounted widgets that take focus — `TextInput`, `Button`, `Checkbox`, `Select`, `Menu`, `DateTimeInput`, `Slider`, `FilePicker`, `ActionButton`, `Table`, `Tabs`, a `Badge` with `onRemove` — that are visible and enabled, in document order (a walk of the mounted tree in child order, computed when asked). + - `form_rows.hpp`: `class FormRowsSource final : public table::DataSource` — `FormRowsSource(forms::FormSession& form, std::string arrayPath, std::vector columns)`; `columns()`, `snapshot()`, `subscribe`, `unsubscribe`; `[[nodiscard]] forms::RowState* row(table::RowId const& key) const`. A row's id is `RowId{static_cast(RowState::key())}`; rows in the array's order. A cell is the member's encoding as a cell of the column's kind (`Integer` → `int64`, `Decimal`/`Quantity` → `Rational`, `Number` → `double`, `Text`/`Enum`/`Choice` → `std::string`, `Date` → days, `DateTime` → seconds, `Bool` → `bool`), `std::monostate` when blank, and, when the draft does not encode, `std::string{draft}` — an invalid cell in every column but `Text`, where it is the text itself. A draft change of one member notifies `Updated` for its row alone. + - `grid.hpp`: + - `enum class EnterMoves : std::uint8_t { Down, Right, None };` `enum class Walk : std::uint8_t { Rows, Columns };` + - `struct GridColumn { std::string id; std::string label; std::string field; std::function value; };` — `field` empty with `value` set is a display column. + - `struct GridOptions { EnterMoves enterMoves = EnterMoves::Down; Walk walk = Walk::Rows; std::function onActivate; };` — `onActivate` is the table's `onActivate`, which `Enter` or a double click on a read-only cell runs. + - `struct CellFacts { forms::FieldState const* field = nullptr; bool hasEdit = true; bool overlayReadOnly = false; bool companionReadOnly = false; bool busy = false; bool locked = false; bool unloaded = false; };` and `[[nodiscard]] bool cellReadOnly(CellFacts const& facts);` — true when `field` is null or `!hasEdit`, the field's `readonly()` (which covers `x-readonly`, `x-computed`, `x-derived` and a `readonlyWhen` reaching it), or any other member is true. + - `class GridSource` (pure virtual), **by view index**, because a model's table holds only a window of its rows: `rowCount() const -> std::size_t` (the view's rows, fetched or not); `keyAt(std::size_t viewRow) const -> std::optional` (empty while that row is not fetched); `positionOf(Key const&) const -> std::optional` (the key's view position now, empty when it is not in the view); `columns() const -> std::vector` (the ids of the visible columns in layout order: the walk's and the rectangle's order, not `Table::columns`' — a cell is always named by its column id, and `node()` looks a `Table::columns` index up by `columns[c].id`); `editor(Key const&, std::string_view column) -> Node` (the editor of an editable cell, built once per opening: the forms control of the cell's field; never called for a read-only cell or one that `toggles`); `toggles(Key const&, std::string_view column) const -> bool` (the cell's field is a `Boolean`: `Space` and a click flip it, no editor opens); `readOnly(Key const&, std::string_view column) const -> bool` (calls `cellReadOnly`); `covered(Key const&, std::string_view) const -> bool`; `draft(Key const&, std::string_view) const -> std::string`; `text(Key const&, std::string_view) const -> std::string` (display text, `formatCell`); `error(Key const&, std::string_view) const -> std::optional`; `write(Key const&, std::string_view column, std::string draft) -> void` (a user's draft); `committed() -> void` (an edit is meant; one call per change); `marks(Key const&, std::string_view) const -> CellMarks` (tracked: every read it depends on is a tracked read, so a binding over it follows drafts, errors, edits and row states); `keyOf(Value const& record) const -> std::optional` (the key of the row a cell's row signal holds: a cell view knows its row only through that signal, which a pooled cell's rebind sets to another record; empty for a record with no key, which draws no marks); `rowModified(Key const&) const -> bool` (tracked: some cell of the row is modified, or the row was added since the load); `view() -> TableRows&` (the data rows, by view index: what `rowCount`, `keyAt` and `positionOf` count, and what `node()` mounts unless a decorator is given to it, Task 22's `SummaryRows`). + - `class FormGridSource final : public GridSource` — `FormGridSource(forms::FormSession& form, std::string arrayPath, std::vector columns, FormatContext format)` (it makes its `std::shared_ptr` and the `GridRows` over it; every row of a form is fetched, so `keyAt` is never empty below `rowCount`; `text()` is the draft while blank or not encoding, else `formatCell` of the cell with the column's display places set to the field's places); `view()` (its `GridRows`); `rowModified(key)` is `FormSession::rowModified(arrayPath, key)`; `void setLayout(std::vector visible)` (the visible column ids in layout order, which the lowering feeds from Task 9's `Table::arrangement`; default every column in declared order); `[[nodiscard]] forms::FieldState* field(Key const& row, std::string_view column) const`; `editor(key, column)` is `forms::detail::engine::scalarControl(form, *field(key, column))` and `toggles` is `field(key, column)->spec().kind == forms::FieldKind::Boolean`; `void onBeforeSubmit(std::function commit)` (registers `commit` with `FormSession::onBeforeSubmit` for the source's life; `GridController` passes its commit of an open editor, so the form's submit ends the edit first); `modifiedCount() const -> std::size_t`, `modifiedRows() const -> std::size_t`, `errorCount() const -> std::size_t` (all tracked). + - `class GridRows final : public TableRows` — `GridRows(std::shared_ptr source)`, over `EngineRows(source, source->recordOf(), table::EngineOptions{})` (index #21): the engine's view, less the rows added since the sort or the filter last changed, which follow it in the order they were added (they pass the filter until it changes). With no sort and no filter the view is the array's order, an inserted row in its place. It answers Task 17c's `states()` with a `RowStates` of its own that nothing registers into (a grid of a form runs no action per row) and `moveKey` by doing nothing (a form row's key never changes). + - `form_rows.hpp` also gives `[[nodiscard]] RecordOf FormRowsSource::recordOf() const` — the grid's own record (index #28): `RowRecord{RowId{key}, row}`, `row` an object holding, for every member of the row type, its encoded value, `null` when blank or not encoding, and the member `#key`, the row's key (no member of a row type is named `#key`: `#` introduces a row key in `FormSession::field` paths). `FormGridSource::keyOf` reads `#key`. `summaryScopeRows` (Task 22) and a column's `value` expression read this record. + - `class GridController` — `GridController(reactive::Runtime& runtime, GridSource& source, GridOptions options)`; `[[nodiscard]] std::optional focus() const` (tracked; the focused cell when its row is fetched, empty when nothing has focus or the focus stands on a placeholder); `[[nodiscard]] std::optional place() const` (tracked; the focus as the mount shows it and what `Table::gridFocus` binds: `{key, positionOf(key), column}` for a focused cell, `{nullopt, viewRow, column}` after the walk stopped at a row not fetched yet; when `keyAt(viewRow)` answers, on the source's next change, the place takes that key and `focus()` names the cell); `void focusPlace(GridFocus place)` (what `Table::onGridFocus` calls: `focusCell` when `place.key` is set, else the placeholder focus); `void focusCell(CellRef cell)` (a click or an arrow; refused for a covered cell; commits an open editor on another cell first); `void activate(CellRef cell)` (what `Enter` and `F2` with no editor, and a double click, do: focuses the cell, then opens the editor holding the value on an editable cell, or calls `GridOptions::onActivate(cell.key)` on a read-only one); `[[nodiscard]] std::optional editing() const` (tracked); `[[nodiscard]] std::vector keyChords() const` (tracked, per **Chords** above); `KeyOutcome press(std::string_view chord)`; `void type(std::string_view text)` (on a focused cell with no editor: keeps the cell's draft, writes `text` as the draft and opens the editor; with the editor open: `write(cell, text)`, the editor's whole new text, see **Where the editor's text lives**); `void leave()` (focus left the table: commits); `[[nodiscard]] std::string const& message() const` (tracked; the latest transient refusal or notice, which the lowering posts with `ScreenCore::tableMessage`) and `[[nodiscard]] std::vector const& messageEntries() const` (tracked; the choices that notice offers, posted with it through `tableMessage`'s entries overload); `[[nodiscard]] std::string standing() const` and `[[nodiscard]] std::vector standingEntries() const` (tracked; a state that lasts while its source holds, which the lowering writes to `TableStatus::standing`/`standingEntries`, index #19; Task 20 fills them); `void chooseEntry(std::string_view id)` (an entry chosen in the status line, `TableWidget::setOnStatusEntry`); `[[nodiscard]] std::vector cellEntries(Key const& row, std::string_view column)` (the grid's entries of a cell's menu, which the lowering puts after Task 17d's built-ins and before its separator and the document's entries: here "Revert cell", enabled while `modified` holds for that cell, and "Revert row", enabled while `rowModified` holds, each calling `FormSession::revert` and then `committed()` once; Task 21 adds the row entries); `[[nodiscard]] Node node(std::vector columns, TableOptions options, std::optional base = {})` — the table node over `columns` (every column, hidden ones included, each with its `id`), wiring `gridFocus` → `place()`, `onGridFocus` → `focusPlace`, `onKey`, `keyChords`, `onText`, `onActivateCell` → `activate`, `onFocusOut` → `leave`, `editing`, `editor` → `source.editor(cell.key, cell.column)` and `cellMenu`. Its rows are Task 9d's `Table::source`. With no `base`: `TableSource{rows = source.view() (a non-owning `shared_ptr`, aliasing an empty owner: whoever holds the grid outlives the mounted node, see `FormGrid`), cellView, rowView}`, `alwaysFetched` and `levels` empty (a grid holds every row and has no levels), and `cellView(c, row)` is `markedCell(accentedCell(, ), )` with `key = source.keyOf(row.get())` and `id = columns[c].id`. With `base` (a model's table, Task 24; a grid under summary rows, Task 22): `rows`, `alwaysFetched` and `levels` are the base's, a cell is `markedCell(base->cellView(c, row), )` — the base cell is already the lowering's `accentedCell` over the column's `cell` template, tone and tooltip (index #39), so an editable table keeps every column's own view — and `rowView(row)` is the base's look with `modified` set. Either way `rowView(row)` gives `.modified = `, and a record with no key (`keyOf` empty: a heading, a summary row) draws no marks and no modified mark. + - `[[nodiscard]] FormatContext formatOf(forms::FormSession const& form)` — `{.locale = options().bcp47, .numeric = options().locale, .datePattern = options().datePattern, .dateTimePattern = options().dateTimePattern}`, read when called (a later `setFormat` is read by the next call). + - `struct FormGrid { std::shared_ptr source; std::shared_ptr grid; Node node; };` and `[[nodiscard]] FormGrid makeFormGrid(forms::FormSession& form, forms::FieldState& array, std::vector columns, GridOptions options, FormatContext format, TableOptions table = {})` — makes the source and the controller over `form.runtime()` (`FormSession::runtime()`, existing), registers the controller's commit with `source->onBeforeSubmit`, and builds `node` as `grid->node(, table)` whose handlers each capture both `shared_ptr`s, so the node owns the grid it shows. The lowering keeps the `FormGrid` in the table's `ElementState` (element values, `setLayout`, messages). `[[nodiscard]] Node formGrid(form, array, columns, options, format)` is `makeFormGrid(…).node`, for `form_view.hpp`, which passes `formatOf(session)` and every member as a column in schema order. With no `ScreenCore` to post through (a C++ `formView`), `node()` binds `Table::status` itself: `TableStatus{.message = message(), .entries = messageEntries(), .standing = standing(), .standingEntries = standingEntries(), .shown = any of them is set}`; the lowering passes its own `status` in `table` and posts through `tableMessage` instead. + - `form_session.hpp`: `[[nodiscard]] std::size_t FormSession::addBeforeSubmit(std::function hook)` and `void FormSession::removeBeforeSubmit(std::size_t id)`: `submit()` (`form_session.hpp:1017`; explicit mode, and the interpreter's `form_submit`) calls every hook, in registration order, before it assembles the body (`FormGridSource::onBeforeSubmit` wraps the pair). `FormSession::field(path)` also takes `rows#.member` (a row by key); `[[nodiscard]] bool modified(std::string_view path) const` (tracked: reads the field's draft and unit; true when they differ from what the field held when the form was last loaded, or the field's row was added since; false for a computed or derived member, `spec().computed || spec().derived`, whose value only a round writes, and for no other: a member a `readonlyWhen` rule or `x-readonly` freezes after the user typed in it stays modified); `field_model.hpp`: `bool FieldSpec::computed = false;`, set where `x-computed` is read (`field_model.hpp:598`), since `computedInputs` alone cannot tell an `x-computed` with no inputs from none; `[[nodiscard]] bool rowModified(std::string_view arrayPath, std::uint64_t key) const`; `void revert(std::string_view path)` (programmatic: restores the loaded draft and unit; a row path reverts each member; reverting a row added since the load removes it). The load record is `std::map>` by `FieldState::path()`, `struct LoadedCell { std::string text; std::size_t unit; }`, written for every member of every `ObjectArray` row by `prefill`, `reset`, construction, a field `refill` loads and a field `acceptSent` ends the edit of. + - Document: `table` takes `form` (a form node id) and `field` (a path) in place of `rows`; a form field overlay takes `"widget": "grid"` with `grid`, a part holding a table node's keys; `enterMoves` (`down`/`right`/`none`), `walk` (`rows`/`columns`); element values `modifiedCount`, `modifiedRows`, `errorCount`, `editing` (`{key, column}` or `null`). Loader refusals: `form` with `rows`; a column `field` naming no member of the row type ("Refused when the document loads"). + - Status-line copy (posted through `ScreenCore::tableMessage`): typing on a read-only cell: `"This cell is read-only"`. + - `recording_backend.hpp`: drivers `void typeInto(int tableId, std::string text)` (calls the `setOnText` handler), `void clickCell(int tableId, std::size_t viewRow, std::size_t column, bool doubleClick = false)` (`column` the index into `Table::columns`; calls the `setOnCellClick` handler; a double click first calls it with `false`, as a backend does), `void focusOut(int tableId)` (calls the `setOnFocusOut` handler; `RecordingBackend::focus(id)` of a widget outside a table that held focus calls it too); records `setCellMarks` as property `marks:` on the row widget it names (`r`,`m`,`e`,`s`,`u` for the set flags, `""` for none; a pooled cell's marks land on the row widget it is attached to now), `setRowModified` as `modified`, `setCellEditor` as `editor:` (the editor widget's id, `""` for null). + +- [ ] **Step 1: Write the fixture** `tests/grid_test_support.hpp` — namespace `morph::test::grid`: + +```cpp +// A form whose `specimens` rows are entered in a grid. `density` is computed, `limit` derived (Task 20 adds the +// `x-derived` reading; until then its `x-readonly` makes it read-only). `reviewer` freezes the grid by rule. +inline constexpr std::string_view kSpecimens = R"({"type":"object","title":"Specimens","properties":{ + "sampleId":{"type":"integer","title":"Sample","x-order":0}, + "reviewer":{"type":["string","null"],"title":"Reviewer","x-order":1}, + "specimens":{"type":"array","title":"Specimens","x-order":2,"minItems":0,"maxItems":5, + "items":{"type":"object","properties":{ + "label":{"type":["string","null"],"title":"Label","x-order":0}, + "mass":{"type":["object","null"],"title":"Mass","x-decimalPlaces":2,"x-order":1}, + "volume":{"type":["object","null"],"title":"Volume","x-decimalPlaces":1,"x-order":2}, + "density":{"type":["object","null"],"title":"Density","x-decimalPlaces":3,"x-readonly":true, + "x-computed":{"inputs":["mass","volume"]},"x-order":3}, + "limit":{"type":["object","null"],"title":"Limit","x-decimalPlaces":2,"x-readonly":true,"x-derived":true, + "x-order":4}, + "note":{"type":["string","null"],"title":"Note","x-order":5}}}}}, + "required":["sampleId"], + "x-rules":[{"kind":"readonlyWhen","fields":["specimens"],"when":{"kind":"engaged","fields":["reviewer"]}}]})"; + +struct GridFixture { + morph::test::formsengine::Harness h; + std::unique_ptr form; + std::unique_ptr source; + std::unique_ptr grid; + // Loads `rows` blank rows (keys 1..rows) with sampleId 1, in a comma locale, columns in schema order. + explicit GridFixture(std::size_t rows, ui::GridOptions options = {}, std::string schema = std::string{kSpecimens}); + [[nodiscard]] std::string json(std::string_view path) const; // the field's encoded JSON, "" when none +}; +inline ui::CellRef at(std::int64_t key, std::string column) { return ui::CellRef{ui::Key{key}, std::move(column)}; } +// Every fetched key of the source's view, in view order. +inline std::vector keysOf(ui::GridSource const& source) { + std::vector keys; + for (std::size_t i = 0; i < source.rowCount(); ++i) { + if (auto key = source.keyAt(i)) keys.push_back(*key); + } + return keys; +} +``` + +`grid_test_support.hpp` also gives `columnsOf(GridFixture const&) -> std::vector` (one per member in schema order, `id` and `label` the member's name) for `GridController::node`. `GridFixture` registers the controller's commit with `source->onBeforeSubmit`, as `makeFormGrid` does, and prefills `{"sampleId":1,"specimens":[{},…]}`, builds the session with `FormSessionOptions{.locale = ui::localeFacts("de").numeric, .bcp47 = "de"}` and the source with `ui::FormatContext{.locale = "de", .numeric = ui::withoutGrouping(ui::localeFacts("de").numeric)}` (`localeFacts` returns a `LocaleFacts` row and `withoutGrouping` takes its `render::NumericLocale`, `locale_table.hpp:117`, `:171`), so a cell of `1` at two places shows `1,00`. Add the same schema to `corpusCatalog().schema` in `tests/ui_interpreter_support.hpp` as `Lims_RecordSpecimens`. + +- [ ] **Step 2: Write the failing tests** in `tests/test_ui_grid.cpp`: + +```cpp +// Mutation: FormGridSource::write parsing the number itself (std::stod after replacing ','), not through the field. +TEST_CASE("grid: a cell encodes as its field does", "[ui][grid]") { + GridFixture f{3}; + f.grid->focusCell(at(1, "mass")); + f.grid->type("12,5"); + CHECK(f.grid->press("Enter") == ui::KeyOutcome::Handled); + CHECK(f.json("specimens[0].mass") == R"({"num":1250,"den":100,"dp":2})"); + CHECK(f.grid->focus() == at(2, "mass")); // enterMoves: down + f.grid->type("1,234"); + f.grid->press("Enter"); + CHECK(f.form->field("specimens[1].mass").draft() == "1,234"); // kept as typed + CHECK(f.form->field("specimens[1].mass").error().peek()->code == "too-precise"); + CHECK_FALSE(f.form->ready()); + CHECK(f.source->marks(ui::Key{std::int64_t{2}}, "mass").error); + f.grid->focusCell(at(2, "mass")); + CHECK(f.grid->message() == "Too many decimal places"); // the forms error, while the cell has focus +} + +// Mutation: GridSource::readOnly testing spec().readOnly only (the readonlyWhen section fails). +TEST_CASE("grid: read-only is one rule", "[ui][grid]") { + GridFixture f{2}; + SECTION("computed and derived members") { + f.grid->focusCell(at(1, "volume")); + f.grid->type("2,0"); + f.grid->press("Tab"); + CHECK(f.grid->focus() == at(1, "note")); // density and limit skipped + f.grid->press("Shift+Tab"); + CHECK(f.grid->focus() == at(1, "volume")); + for (std::string const column : {"density", "limit"}) { + f.grid->focusCell(at(1, column)); // an arrow or a click reaches it + f.grid->type("5"); + CHECK_FALSE(f.grid->editing().has_value()); + CHECK(f.grid->message() == "This cell is read-only"); + CHECK(f.source->marks(ui::Key{std::int64_t{1}}, column).readOnly); + } + } + SECTION("a readonlyWhen rule") { + f.h.type(*f.form, "reviewer", "ana"); + f.grid->focusCell(at(1, "mass")); + f.grid->type("5"); + CHECK_FALSE(f.grid->editing().has_value()); + CHECK(f.source->marks(ui::Key{std::int64_t{1}}, "mass").readOnly); + CHECK(f.grid->press("Tab") == ui::KeyOutcome::FocusNext); // no editable cell is left + } +} + +// Mutation: Tab wrapping to the first editable cell, which never leaves the grid. +TEST_CASE("grid: the walk", "[ui][grid]") { + SECTION("enterMoves down fills a column") { + GridFixture f{3}; + f.grid->focusCell(at(1, "mass")); + for (auto const* text : {"1", "2", "3"}) { f.grid->type(text); f.grid->press("Enter"); } + CHECK(f.json("specimens[2].mass") == R"({"num":300,"den":100,"dp":2})"); + CHECK(f.grid->focus() == at(3, "mass")); // no row below and no appendRows: it stays + } + SECTION("Tab on the last editable cell leaves") { + GridFixture f{2}; + f.grid->focusCell(at(2, "note")); + CHECK(f.grid->press("Tab") == ui::KeyOutcome::FocusNext); + f.grid->focusCell(at(1, "label")); + CHECK(f.grid->press("Shift+Tab") == ui::KeyOutcome::FocusPrevious); + } + SECTION("walk: columns goes down first") { + GridFixture f{2, ui::GridOptions{.walk = ui::Walk::Columns}}; + f.grid->focusCell(at(1, "mass")); + f.grid->press("Tab"); + CHECK(f.grid->focus() == at(2, "mass")); + f.grid->press("Tab"); + CHECK(f.grid->focus() == at(1, "volume")); + } + SECTION("Escape restores the draft the cell had when the editor opened") { + GridFixture f{1}; + f.grid->focusCell(at(1, "label")); + f.grid->type("a"); + f.grid->press("Enter"); + f.grid->focusCell(at(1, "label")); + f.grid->type("b"); + f.grid->press("Escape"); + CHECK(f.form->field("specimens[0].label").draft() == "a"); + } +} + +// Review Focus 1, walk half. Mutation: an empty grid answering Tab with Handled. +TEST_CASE("grid: an empty grid lets Tab leave at once", "[ui][grid]") { + GridFixture f{0}; + CHECK_FALSE(f.grid->focus().has_value()); + CHECK(f.grid->press("Tab") == ui::KeyOutcome::FocusNext); + CHECK(f.grid->press("Shift+Tab") == ui::KeyOutcome::FocusPrevious); +} + +// Mutation: FormRowsSource giving the engine's view order to the array (a source that reorders the field's rows). +TEST_CASE("grid: a sorted grid keeps its record", "[ui][grid]") { + GridFixture f{3}; + for (auto const& [key, text] : {std::pair{1, "3"}, {2, "1"}, {3, "2"}}) { + f.grid->focusCell(at(key, "mass")); f.grid->type(text); f.grid->press("Enter"); + } + REQUIRE(f.source->view().setSort({table::SortKey{.column = "mass"}}).has_value()); + CHECK(keysOf(*f.source) == std::vector{ui::Key{std::int64_t{2}}, ui::Key{std::int64_t{3}}, ui::Key{std::int64_t{1}}}); + f.grid->focusCell(at(3, "mass")); f.grid->type("9"); f.grid->press("Enter"); + CHECK(f.json("specimens[2].mass") == R"({"num":900,"den":100,"dp":2})"); // in place, entered order + CHECK(f.json("specimens[0].mass") == R"({"num":300,"den":100,"dp":2})"); + std::uint64_t const added = f.form->field("specimens").addRow(); + f.grid->focusCell(at(static_cast(added), "mass")); f.grid->type("0"); f.grid->press("Enter"); + CHECK(keysOf(*f.source).back() == ui::Key{static_cast(added)}); // at the end until the sort changes + REQUIRE(f.source->view().setSort({}).has_value()); + REQUIRE(f.source->view().setSort({table::SortKey{.column = "mass"}}).has_value()); + CHECK(keysOf(*f.source).front() == ui::Key{static_cast(added)}); // 0,00 sorts first +} + +// Mutation: modified() comparing the whole ObjectArray's snapshot, which marks every cell. +TEST_CASE("grid: what changed", "[ui][grid]") { + GridFixture f{2}; + f.grid->focusCell(at(1, "mass")); f.grid->type("4"); f.grid->press("Enter"); + CHECK(f.form->modified("specimens#1.mass")); + CHECK_FALSE(f.form->modified("specimens#1.volume")); + CHECK_FALSE(f.form->modified("specimens#2.mass")); + CHECK(f.form->rowModified("specimens", 1)); + CHECK_FALSE(f.form->rowModified("specimens", 2)); + CHECK(f.source->modifiedCount() == 1); + CHECK(f.source->modifiedRows() == 1); + f.form->revert("specimens#1.mass"); + CHECK(f.form->field("specimens[0].mass").draft().empty()); + CHECK(f.source->modifiedCount() == 0); + std::uint64_t const added = f.form->field("specimens").addRow(); + CHECK(f.form->rowModified("specimens", added)); // a row added since the load, as a whole +} + +// Mutation: modified() false for every read-only member (the readonlyWhen section loses the typed cell's mark). +TEST_CASE("grid: only computed and derived members never draw a modified mark", "[ui][grid]") { + GridFixture f{1}; + SECTION("a cell frozen by a rule after typing stays modified") { + f.grid->focusCell(at(1, "mass")); f.grid->type("4"); f.grid->press("Enter"); + f.h.type(*f.form, "reviewer", "ana"); // readonlyWhen now freezes the grid + REQUIRE(f.form->field("specimens[0].mass").readonly().get()); + CHECK(f.form->modified("specimens#1.mass")); + CHECK(f.source->marks(ui::Key{std::int64_t{1}}, "mass").modified); + } + SECTION("a computed member written programmatically is not modified") { + f.form->assign("specimens[0].density", R"({"num":2,"den":1,"dp":3})"); + CHECK_FALSE(f.form->modified("specimens#1.density")); + CHECK_FALSE(f.form->rowModified("specimens", 1)); + } +} + +// Mutation: "Revert row" reverting the focused cell only (label keeps "x"). +TEST_CASE("grid: revert cell and revert row from the cell's menu", "[ui][grid]") { + GridFixture f{2}; + f.grid->focusCell(at(1, "label")); f.grid->type("x"); f.grid->press("Tab"); + f.grid->type("4"); f.grid->press("Enter"); // (1, mass) + auto entries = f.grid->cellEntries(ui::Key{std::int64_t{2}}, "mass"); + CHECK(labelsOf(entries) == std::vector{"Revert cell", "Revert row"}); + CHECK_FALSE(enabledOf(entry(entries, "Revert cell"))); // row 2 holds nothing typed + entries = f.grid->cellEntries(ui::Key{std::int64_t{1}}, "mass"); + entry(entries, "Revert cell").onSelect(); + CHECK(f.form->field("specimens[0].mass").draft().empty()); + CHECK(f.form->field("specimens[0].label").draft() == "x"); + entries = f.grid->cellEntries(ui::Key{std::int64_t{1}}, "label"); + entry(entries, "Revert row").onSelect(); + CHECK(f.form->field("specimens[0].label").draft().empty()); + CHECK_FALSE(f.form->rowModified("specimens", 1)); +} +``` + +```cpp +// Mutation: the editor holding its text in a buffer of its own until commit (the draft is still "" while typing). +TEST_CASE("grid: the editor's text is the cell's draft, and a commit is one change", "[ui][grid]") { + GridFixture f{2}; + std::size_t commits = 0; + f.source->onCommitted([&] { ++commits; }); // test seam: called by committed() + f.grid->focusCell(at(1, "label")); + f.grid->type("a"); + CHECK(f.grid->editing() == at(1, "label")); + CHECK(f.form->field("specimens[0].label").draft() == "a"); // live, before any commit + CHECK(commits == 0); + f.grid->type("ab"); // the editor's whole new text + CHECK(f.form->field("specimens[0].label").draft() == "ab"); + f.grid->press("Enter"); + CHECK(commits == 1); + CHECK_FALSE(f.grid->editing().has_value()); + f.grid->focusCell(at(1, "label")); f.grid->press("F2"); f.grid->press("Enter"); // opened, nothing changed + CHECK(commits == 1); + f.grid->focusCell(at(1, "label")); f.grid->type("zz"); f.grid->press("Escape"); + CHECK(f.form->field("specimens[0].label").draft() == "ab"); + CHECK(commits == 1); // Escape is no change +} + +// Mutation: FormSession::submit not calling the before-submit hooks (the editor stays open, no commit is counted). +TEST_CASE("grid: the form's submit ends an open edit first", "[ui][grid]") { + GridFixture f{1}; + std::size_t commits = 0; + f.source->onCommitted([&] { ++commits; }); + f.grid->focusCell(at(1, "mass")); f.grid->type("7,5"); + REQUIRE(f.grid->editing().has_value()); + f.form->submit(); f.h.settle(); + CHECK_FALSE(f.grid->editing().has_value()); + CHECK(commits == 1); + REQUIRE(f.h.server.submits().size() == 1); + CHECK(f.h.server.lastBody().find(R"("mass":{"num":750,"den":100,"dp":2})") != std::string::npos); +} +``` + +`void FormGridSource::onCommitted(std::function observer)` is a public seam (one observer, called at the end of `committed()`); the lowering uses it for nothing, Task 20's rounds go through `FormSession::noteCommit`. + +`tests/grid_test_support.hpp` also gives `labelsOf(std::vector const&) -> std::vector` (each entry's label as bound now), `entry(std::vector const&, std::string_view label) -> ui::MenuItem const&` (`REQUIRE`s it exists) and `enabledOf(ui::MenuItem const&) -> bool`; Task 21 reuses them. + +Interpreter-level, same file, through `ui::testing::TableHarness` (index #42; `Lims_RecordSpecimens` added to its catalog with the schema above, `modelType` `Lims_SampleModel`, no effects and no records) and a whole document with `"models": {"sample": {"type": "Lims_SampleModel", "key": 4}}` holding `{"kind":"form","id":"rec","model":"sample","action":"Lims_RecordSpecimens","submit":"explicit"}`, a text input `before`, `{"kind":"table","id":"grid","testId":"grid","form":"rec","field":"specimens","columns":[{"id":"mass","field":"mass"},{"id":"note","field":"note"}]}` and a text input `after`: + +```cpp +// Mutation: the lowering's form_submit sending the body without running the session's before-submit hooks (the +// editor is still open after the click: `editing` is not null and "editor:0" still names the TextInput). +TEST_CASE("grid: submission commits the open editor and places field errors", "[ui][grid][interpreter]") { + // (the harness formats in `en`) prefill sampleId 4 and two blank specimens; focus (1, mass), type "7.5" with the + // editor open; click form_submit + // CHECK elementValue(h, "grid", "editing") == "null" and the row of key 1 records "editor:0" == "" + // CHECK the submitted body's specimens[0].mass == {"num":750,"den":100,"dp":2} + // fail the call with field error {"specimens[1].mass": "must be positive"} + // CHECK elementValue(h, "grid", "errorCount") == "1" and cellAccent(h, 2, "mass").tooltip == "must be positive" +} +// Mutation: the mount ignoring KeyOutcome::FocusNext. +TEST_CASE("grid: Tab on the last editable cell moves focus to the next control", "[ui][grid][interpreter]") { + // focus (2, note); h.backend.press(h.byTestId("Table","grid"), "Tab") + // CHECK h.backend.focused() == h.byTestId("TextInput","after") + // press "Shift+Tab" on (1, mass): CHECK focused() == byTestId("TextInput","before") +} +// Mutation: the loader checking a column's `field` only when the grid mounts (loadDocumentText succeeds). +TEST_CASE("grid: a column naming no member is refused when the document loads", "[ui][grid][interpreter]") { + // a column {"id":"x","field":"nosuch"}: loadDocumentText fails; the message names "nosuch" +} +// Mutation: the mount not wiring setOnFocusOut to GridController::leave (the draft stays uncommitted, "" not "3"). +TEST_CASE("grid: a click focuses a cell, a double click opens its editor, focus leaving commits", "[ui][grid][interpreter]") { + // int const table = h.byTestId("Table","grid"); + // (columns by index into Table::columns: mass 0, note 1) + // h.backend.clickCell(table, 0, 0): CHECK elementValue(h, "grid", "editing") == "null" and the recorded focus cell is (0, 0) + // h.backend.clickCell(table, 1, 0, true): CHECK elementValue(h, "grid", "editing") == R"({"key":2,"column":"mass"})" + // and the table's row 2 records "editor:0" naming a TextInput widget that has focus (h.backend.focused()) + // h.backend.edit(, "3"); h.backend.focusOut(table) + // CHECK the form field specimens[1].mass draft == "3", elementValue(h, "grid", "editing") == "null", "editor:0" recorded "" + // h.backend.typeInto(table, "8") with focus on (1, note): the editor opens on (1, note) holding "8" + // CHECK the table's declared keys are exactly {Enter, Tab, Shift+Tab, Escape, Ctrl+Enter} while it is open +} +``` + +Mount-level, same file, over `GridFixture` and a `RecordingBackend` mounting `f.grid->node(columnsOf(f), {})` (column indices into `Table::columns`, in schema order: `label` 0, `mass` 1, `volume` 2, `density` 3, `limit` 4, `note` 5): + +```cpp +// Mutations: the marks bound in the row's scope instead of the cell's (the pooled cell showing row 30 keeps row 1's +// "m"); setCellMarks skipped when a pooled cell joins another row widget with equal marks. +TEST_CASE("grid: a cell's marks are drawn by its cell view and follow the row it shows", "[ui][grid][mount]") { + // GridFixture f{40}; mounted with 20 realized rows. + // focus (1, mass), type "4", Enter: the row widget showing key 1 records marks:1 == "m" and modified == true; + // its marks:3 (density, computed) contains "r"; the row widget showing key 2 records marks:1 == "" and + // modified == false + // scroll to view row 25, so the row of key 1 leaves the window: the row widget showing key 30 records + // marks:1 == ""; Mounted::stats().cellsRebound > 0 and cellsCreated is unchanged (no cellView call) + // f.form->revert("specimens#1.mass"); scroll back to view row 0: the row widget showing key 1 records + // marks:1 == "" and modified == false +} +``` + +These five are written out in full Catch2 with the harness calls named in the comments; the comments are the assertions. + +A hidden column keeps its index (index #37), same file, mount level: + +```cpp +// Mutation: the mount passing a cell's place in the layout as `column` (with `label` hidden, mass reports 0). +TEST_CASE("grid: a cell's column is its index among every column, hidden ones included", "[ui][grid][mount]") { + // GridFixture f{2}; mounted; the arrangement hides `label` (index 0), so mass is the first visible column + // focus (1, mass), type "4", Enter: the row widget showing key 1 records marks:1 == "m" and no marks:0 change + // h.backend.clickCell(table, 0, 1, true): f.grid->editing() == at(1, "mass") and that row records editor:1 +} +``` + +Qt Quick, `tests/qt_quick/test_qt_quick_table.cpp`: + +```cpp +// Mutation: the QML cell ignoring setOnText. +TEST_CASE("qt_quick grid: typing on a focused cell opens its editor, Tab walks and leaves", "[qt_quick][grid]") { + // A mounted formGrid of two rows between two text inputs: QTest::keyClicks "5" on (1, mass) shows a TextField + // holding "5" in that cell; Tab commits it (field draft "5") and focuses (1, volume); Tab on (2, note) gives + // focus to the second text input's item. +} +// Mutation: the QML cell sending a double click as two single clicks (no editor opens). +TEST_CASE("qt_quick grid: a double click opens the editor in the cell and focus leaving commits", "[qt_quick][grid]") { + // QTest::mouseDClick on (2, mass): a TextField item lies inside that cell's rectangle and has active focus; + // keyClicks "7", then a click on the second text input: field draft "7", no TextField in the table. +} +``` + +Terminal, `tests/tui/test_tui_table.cpp`: + +```cpp +// Mutation: the terminal table ignoring setOnText (the keystroke moves nothing and opens no editor). +TEST_CASE("tui grid: typing on a focused cell opens its editor, Enter commits and moves down", "[tui][grid]") { + // A mounted formGrid of two rows: focus (1, mass), feed the key "5": the rendered row 1 shows "5" with the + // terminal cursor in the mass column; feed Enter: field draft "5", focus (2, mass); feed Tab on (2, note): + // focus leaves the table to the next control. +} +``` + +- [ ] **Step 3: Run to see them fail** + +Run: `cmake --build --preset cl-debug --target morph_tests` +Expected: compile errors — `morph/ui/grid.hpp` not found, `FormSession::modified` not declared. + +- [ ] **Step 4: Implement the focus chain** in `view.hpp`, `backend.hpp`, `mount.hpp` with the signatures above, `markedCell` and the mount's binding of a cell's marks in the cell's own scope, `TableRowLook::modified`, and the `RecordingBackend` drivers and records listed under Produces. Then move the scalar controls to `field_control.hpp` with no change of behaviour: `ctest --test-dir build/cl-debug -R "form" --output-on-failure` passes unchanged before anything else in `form_view.hpp` changes. + +- [ ] **Step 5: Implement per-cell snapshots** in `form_session.hpp`: `field()` by `#key`, `modified`, `rowModified`, `revert`, the load record; and the before-submit hooks (`addBeforeSubmit`, `removeBeforeSubmit`, called first in `submit()`). + +- [ ] **Step 6: Implement `form_rows.hpp` and `grid.hpp`** with the signatures above. The walk, which the signatures do not determine: + +```text +next(from, forward): // view positions at the moment of the call + start = positionOf(from.key) (or before the first / after the last when there is no focus) + cells = [0, rowCount()) × columns() in walk order (Rows: row-major; Columns: column-major), stepping from start + for each cell: keyAt(row) empty -> return Stop{row, column} // a row not fetched yet: never walked past + !readOnly && !covered -> return Found{cell} + return None +Stop{row, column}: place() becomes GridFocus{nullopt, row, column} and focus() empty (Task 10a's placeholder focus, + which keeps the row realized, so the window fetches it); Handled. When keyAt(row) answers, place() + takes the key and focus() names the cell; a Tab or Enter pressed before that is Handled and moves nothing. +Tab: commit an open editor; next(focus, true) -> Found: focus it, Handled; Stop: as above; None -> FocusNext +Shift+Tab: commit; next(focus, false) -> the same, None -> FocusPrevious +Enter (editor open): commit; Down: first editable cell in the same column below; Right: next(focus, true) within + the row; None: stay. Nothing found: stay; a row not fetched yet below: Stop. Enter, F2 or a double + click with no editor: activate(focus). +Space on a Boolean cell: toggles and commits, no editor. Delete with no editor: blanks the cell (write ""). +Arrows: move to any cell (read-only included, covered cells passed over); Ctrl+arrow to the last cell that way. +``` + +Commit and `Escape` follow **Where the editor's text lives** above: the draft is live, a commit closes the editor and calls `committed()` once when the draft changed, `Escape` writes the kept draft back. + +- [ ] **Step 7: Implement the lowering and the loader** in `src/ui/document.cpp`, `src/ui/interpreter.cpp`: `table` with `form`/`field` lowers to `makeFormGrid` over the form element's session, the `FormGrid` kept in the table's `ElementState`; the lowering's `form_submit` runs the session's before-submit hooks through `FormSession::submit`; the `grid` overlay adds `overrides.byField(id, …)` drawing the same; element values; refusals. `form_view.hpp` draws an `ObjectArray` whose `spec().widget == "grid"` with `ui::formGrid(session, state, , {}, ui::formatOf(session))`; the overlay's `grid` part replaces those columns and options. The lowering reads the `FormGrid`'s controller: it posts `GridController::message()` with its `messageEntries()` through `tableMessage`, writes `standing()`/`standingEntries()` into the table's `TableStatus`, and routes `setOnStatusEntry` to `chooseEntry`. + +- [ ] **Step 8: Implement editors in cells** in the Qt Quick and terminal tables: `setOnText`, `setOnCellClick`, `setOnFocusOut`, `setCellEditor` (the editor's item placed over the cell's rectangle and given focus; every `column` an index into `Table::columns`), `setCellMarks`, `setRowModified`, `Tab`/`Shift+Tab` delivered to a table that lists them. + +- [ ] **Step 9: Run the tests** + +Run: `cmake --build --preset cl-debug --target morph_tests && ctest --test-dir build/cl-debug -R "grid:" --output-on-failure` +Expected: all `grid:` cases pass. Then `ctest --test-dir build/cl-debug -R "form|table|mount" --output-on-failure` — no regressions. Qt Quick and terminal: `ctest --test-dir build/cl-qt-debug -R "qt_quick grid|tui grid" --output-on-failure` — pass. + +- [ ] **Step 10: Mutate** each named mutation once; record the failing lines. + +- [ ] **Step 11: Docs** per this task's Docs list; run the docs build (new public symbols). + +- [ ] **Step 12: Commit** + +```bash +git add include/morph/ui include/morph/forms/engine src/ui src/qt_quick src/tui tests docs/spec +git commit -m "feat(ui): grids of a form" +``` + +### Task 20: Derived values (editing.md step 2) + +**Spec:** editing.md "Derived values", "Columns are fields" (Per row), "The editor" (choices that depend on the row), Invariants 2, 3, 9; Failure modes rows "An evaluation or a derive call fails", "A reply arrives after a newer one", "A derive reply names a path that is not a derived member"; Delivery order step 2. + +**Files:** +- Create: `include/morph/forms/derive.hpp`, `tests/forms/test_forms_derive.cpp` (add to `morph_tests`) +- Modify: `include/morph/forms/forms.hpp`, `include/morph/forms/engine/field_model.hpp`, `include/morph/forms/engine/form_session.hpp`, `include/morph/core/registry.hpp`, `include/morph/ui/grid.hpp`, `src/ui/document.cpp`, `src/ui/interpreter.cpp`, `tests/test_ui_grid.cpp`, `tests/grid_test_support.hpp`, `tests/qt_quick/test_qt_quick_table.cpp` +- Docs: `docs/spec/forms/engine.md` (rounds, `loadDerived`, `deriveDebounce`, row-dependent Choices), `docs/spec/forms/forms.md` (`computedFields` on a row type as the exception to "top-level only"; `derived()` and `x-derived`, untouched by `recomputeAll`), `docs/spec/core/registry.md` (`DeriveOf`, `Derived`; `evaluate` recomputing row members; `clearDerived`), `docs/spec/ui/document.md` and `docs/spec/ui/interpreter.md` (`derive`, `deriveDebounce`; a column's `field` expression and per-row overlays). + +**Interfaces:** +- Consumes: Task 19's `GridColumn`, `FormGridSource`, `GridController`, `GridSource::committed`; `ActionDispatcher::evaluate`/`evaluateAction`/`prepareAction` (existing); `ModelChannel::execute(…, CallOptions{.evaluate = true})` (existing); `reactive::Scheduler::after` (existing). +- Produces: + - `derive.hpp`: `template struct DeriveOf { Action body; };` `struct Derived { struct Value { std::string path; glz::raw_json value; }; std::vector values; };` (JSON `{"values":[{"path":…,"value":…}]}`); `template [[nodiscard]] FieldMeta derived(std::string_view label = {}, std::string_view help = {}) noexcept` (= `describe(label, help).withDerived()`); `template void clearDerived(A& action)` (value-initialises every member whose `FieldMeta` is `derived`, in `A` and in each element of a `std::vector` member of a reflectable aggregate, recursively); `enum class DeriveState : std::uint8_t { Current, Running, Failed };` `struct DeriveOptions { std::function(std::string bodyJson)> evaluate; std::function(std::string deriveBodyJson)> derive; reactive::Scheduler* scheduler = nullptr; std::chrono::milliseconds debounce{150}; };` `struct DeriveRound { std::uint64_t sequence = 0; std::string body; std::map, std::less<>> rowKeys; };` `struct DeriveLoad { std::size_t loaded = 0; std::vector refused; };` + - `forms.hpp`: `bool FieldMeta::derived{false};` `constexpr FieldMeta withDerived() const noexcept`; the schema writes `"x-derived": true` and leaves the member out of `required`; `annotateNestedAggregate` writes `x-computed`/`x-readonly` for `Sub::computedFields`; `recomputeAll` recomputes each element of every `std::vector` member with `HasComputedFields` (recursively) **before** `A`'s own entries, so a top-level total reads recomputed rows. + - `field_model.hpp`: `bool FieldSpec::derived = false;` read from `x-derived`; `FieldState::readonly()` is true for a derived member. + - `registry.hpp`: `prepareAction` and `evaluateAction` call `forms::clearDerived(action)` before `recomputeAll`. + - `form_session.hpp`: `void deriveWith(DeriveOptions options)`; `void noteCommit()`; `void recalculate()`; `[[nodiscard]] DeriveState deriveState() const` (tracked); `[[nodiscard]] std::string partialBody() const` (every top-level field that encodes; an `Object` or `ObjectArray` member by member, leaving out blank and non-encoding members; every row written, in order, `{}` for a row with nothing); `[[nodiscard]] DeriveRound captureRound()` (next sequence, `partialBody()`, the row keys of every `ObjectArray` by `FieldState::path()`); `DeriveLoad loadDerived(DeriveRound const& round, Derived const& reply)` (derived members only); `DeriveLoad loadDerived(DeriveRound const& round, std::string_view evaluatedBody)` (computed members only, the reply's `errors` and `ready` ignored). Both resolve `name[i]` through `round.rowKeys[name][i]` and the row's current position by key, drop a row since removed, refuse a path that names no member of their kind, write programmatically and move no snapshot. `std::uint64_t FieldState::insertRow(std::size_t position)` (a user action; position past the end appends). + - Choices: a row member's `x-optionsDependsOn` names are looked up in its row, then among the top-level fields; a row member's options are fetched only after `void FieldState::openOptions()` (what a cell editor calls when it opens); identical `(optionsAction, request)` pairs share one fetch for the session's life, a failed fetch is not kept. + - `grid.hpp`: `GridColumn` gains `std::function fieldOf` (a member per row; tracked) and per-row overlays `decimals` (`std::function(forms::RowState const&)>`), `unit` (`std::function(…)>`), `readonly` (`std::function`), `options` (`std::function>(…)>`, option JSON literals kept), `placeholder` (`std::function`). A column with `fieldOf` has `ColumnKind::Text` in `FormRowsSource`, its cell the member's draft. Derived and computed cells draw `CellMarks::muted` while `deriveState()` is `Running` and `stale` while `Failed`. While `Failed`, `GridController::standing()` is `"Derived values could not be recalculated"` and `standingEntries()` is `{StatusEntry{"recalculate", "Recalculate"}}` (a standing state, index #19: it lasts until a round succeeds, through the message hold); `chooseEntry("recalculate")` calls `FormSession::recalculate()`. Both are empty in every other state. + - Document: `form` takes `derive` (an action id of the form's model) and `deriveDebounce` (a literal integer, milliseconds); a grid column's `field` may be an expression in the row's scope, and takes `decimals`, `unit`, `readonly`, `options`, `placeholder` as expressions in the row's scope. The lowering calls `deriveWith` with `evaluate` = the form alias's channel `execute(action, body, {.evaluate = true})` and `derive` = `execute(derive, R"({"body":)" + body + "}")`, and reports each refused path once. + +- [ ] **Step 1: Write the failing server tests** in `tests/forms/test_forms_derive.cpp`: + +```cpp +struct DeriveBox { + std::int64_t count = 0; + std::int64_t perBox = 0; + std::int64_t total = 0; // computed: count * perBox + std::int64_t limit = 0; // derived: the model's + static constexpr auto computedFields = morph::forms::computeList( + morph::forms::computed<&DeriveBox::total, &DeriveBox::count, &DeriveBox::perBox>( + [](auto const& box) { return box.count * box.perBox; })); + static const std::array fieldMetadata; +}; +inline const std::array DeriveBox::fieldMetadata{morph::forms::derived<&DeriveBox::limit>()}; + +struct RecordBoxes { + std::vector boxes; + std::int64_t sum = 0; // computed: the boxes' totals + static constexpr auto computedFields = morph::forms::computeList(morph::forms::computed<&RecordBoxes::sum, &RecordBoxes::boxes>( + [](auto const& record) { std::int64_t s = 0; for (auto const& b : record.boxes) s += b.total; return s; })); +}; +struct DeriveBoxModel { + static inline RecordBoxes last{}; + bool execute(RecordBoxes const& record) { last = record; return true; } // sets no derived member +}; +BRIDGE_REGISTER_MODEL(DeriveBoxModel, "T_DeriveBoxes") +BRIDGE_REGISTER_ACTION(DeriveBoxModel, RecordBoxes, "T_RecordBoxes") + +constexpr std::string_view kForged = R"({"boxes":[{"count":2,"perBox":3,"total":999,"limit":555}],"sum":999})"; + +// Mutation: recomputeAll skipping row members (total stays 999, sum 999); a second run with clearDerived removed +// from prepareAction (limit stays 555). +TEST_CASE("derive: the server keeps recomputeAll's values and the model's", "[forms][derive]") { + auto holder = morph::model::detail::defaultRegistry().create("T_DeriveBoxes"); + morph::model::detail::defaultDispatcher().dispatch("T_DeriveBoxes", "T_RecordBoxes", *holder, kForged); + RecordBoxes const& kept = DeriveBoxModel::last; + CHECK(kept.boxes.at(0).total == 6); + CHECK(kept.sum == 6); + CHECK(kept.boxes.at(0).limit == 0); // the client's 555 is cleared; the model set nothing + auto const evaluated = morph::model::detail::defaultDispatcher().evaluate("T_DeriveBoxes", "T_RecordBoxes", kForged); + CHECK(evaluated.body == R"({"boxes":[{"count":2,"perBox":3,"total":6,"limit":0}],"sum":6})"); +} + +// Mutation: annotateNestedAggregate not writing x-computed for a row type. +TEST_CASE("derive: a row type's schema marks computed and derived members", "[forms][derive]") { + auto dom = glz::read_json(morph::forms::schemaJson()).value(); + auto& box = dom["properties"]["boxes"]["items"]; // DeriveBox is used once: glaze inlines it + CHECK(glz::write_json(box["properties"]["total"]["x-readonly"]).value() == "true"); + CHECK(glz::write_json(box["properties"]["total"]["x-computed"]["inputs"]).value() == R"(["count","perBox"])"); + CHECK(glz::write_json(box["properties"]["limit"]["x-derived"]).value() == "true"); + CHECK(glz::write_json(box["required"]).value() == R"(["count","perBox"])"); +} +``` + +- [ ] **Step 2: Write the failing round tests** in `tests/test_ui_grid.cpp`. `GridFixture` gains `reactive::testing::ManualScheduler scheduler;` two `formsengine::FakeServer` recorders `evaluate` and `derive` whose responders return `std::nullopt` (every call stays pending until resolved by index), and `void enableDerive()`, which calls `form->deriveWith({.evaluate = …, .derive = …, .scheduler = &scheduler})` (debounce 150 ms) over them. + +```cpp +using namespace std::chrono_literals; +std::string const kNoValues = R"({"values":[]})"; + +// Mutation: loadDerived resolving `specimens[i]` against the current rows (the value lands on the inserted row). +TEST_CASE("grid: derived values", "[ui][grid][derive]") { + GridFixture f{3}; + f.enableDerive(); + f.grid->focusCell(at(1, "mass")); f.grid->type("4,00"); f.grid->press("Enter"); + f.grid->type("abc"); f.grid->press("Enter"); // (2, mass): does not encode, left out + f.scheduler.advance(149ms); f.h.settle(); + CHECK(f.evaluate.submits().empty()); + f.scheduler.advance(1ms); f.h.settle(); + REQUIRE(f.evaluate.submits().size() == 1); + REQUIRE(f.derive.submits().size() == 1); + CHECK(f.evaluate.submits().at(0).body == R"({"sampleId":1,"specimens":[{"mass":{"num":400,"den":100,"dp":2}},{},{}]})"); + CHECK(f.derive.submits().at(0).body == R"({"body":{"sampleId":1,"specimens":[{"mass":{"num":400,"den":100,"dp":2}},{},{}]}})"); + CHECK(f.form->deriveState() == forms::DeriveState::Running); + CHECK(f.source->marks(ui::Key{std::int64_t{1}}, "limit").muted); + + f.form->field("specimens").insertRow(1); // above rows 2 and 3 + f.grid->focusCell(at(2, "note")); f.grid->type("typed"); f.grid->press("Enter"); // a commit during the round + f.derive.resolveSubmit(0, R"({"values":[{"path":"specimens[1].limit","value":{"num":7,"den":1,"dp":2}}, + {"path":"specimens[1].note","value":"server"}]})"); + f.evaluate.resolveSubmit(0, R"({"sampleId":1,"specimens":[{"mass":{"num":400,"den":100,"dp":2}, + "density":{"num":2,"den":1,"dp":3}},{},{}],"errors":{},"ready":true})"); + f.h.settle(); + CHECK(f.json("specimens[2].limit") == R"({"num":700,"den":100,"dp":2})"); // row key 2, now at position 2 + CHECK(f.json("specimens[1].limit").empty()); // the inserted row is untouched + CHECK(f.json("specimens[0].density") == R"({"num":2000,"den":1000,"dp":3})"); + CHECK(f.form->field("specimens#2.note").draft() == "typed"); // not a derived member: refused + CHECK(f.form->modified("specimens#2.note")); + CHECK(f.evaluate.submits().size() == 2); // the stale round: one more, at once + CHECK(f.derive.submits().size() == 2); + f.evaluate.resolveSubmit(1, R"({"errors":{},"ready":false})"); + f.derive.resolveSubmit(1, kNoValues); + f.h.settle(); + CHECK(f.form->deriveState() == forms::DeriveState::Current); + + // A failed round keeps the values, marks them stale, and Recalculate runs one more. + f.grid->focusCell(at(1, "mass")); f.grid->type("5"); f.grid->press("Enter"); + f.scheduler.advance(150ms); f.h.settle(); + f.evaluate.rejectSubmit(2, "unreachable"); + f.derive.resolveSubmit(2, kNoValues); + f.h.settle(); + CHECK(f.form->deriveState() == forms::DeriveState::Failed); + CHECK(f.source->marks(ui::Key{std::int64_t{2}}, "limit").stale); + CHECK(f.json("specimens[2].limit") == R"({"num":700,"den":100,"dp":2})"); + CHECK(f.grid->standing() == "Derived values could not be recalculated"); + CHECK(f.grid->standingEntries() == std::vector{{"recalculate", "Recalculate"}}); + f.grid->chooseEntry("recalculate"); f.h.settle(); + CHECK(f.evaluate.submits().size() == 4); +} + +// Mutation: loadDerived without the sequence check (the late older reply overwrites 9 with 8). +TEST_CASE("grid: an older derive reply is ignored", "[ui][grid][derive]") { + GridFixture f{2}; + auto const older = f.form->captureRound(); + auto const newer = f.form->captureRound(); + auto const value = [](std::string json) { return forms::Derived{.values = {{"specimens[1].limit", glz::raw_json{std::move(json)}}}}; }; + CHECK(f.form->loadDerived(newer, value(R"({"num":9,"den":1,"dp":2})")).loaded == 1); + CHECK(f.form->loadDerived(older, value(R"({"num":8,"den":1,"dp":2})")).loaded == 0); + CHECK(f.json("specimens[1].limit") == R"({"num":900,"den":100,"dp":2})"); +} + +// Mutation: loadDerived resolving `specimens[i]` against the current rows (row 2's path falls past the end, which +// passes for the wrong reason, so the reply also names specimens[0], which must still land on row 1). +TEST_CASE("grid: a value for a row removed since the call is dropped", "[ui][grid][derive]") { + GridFixture f{2}; + auto const round = f.form->captureRound(); // rows 1, 2 at sending + f.form->field("specimens").removeRow(2); // then row 2 goes + auto const load = f.form->loadDerived(round, forms::Derived{.values = { + {"specimens[1].limit", glz::raw_json{R"({"num":1,"den":1,"dp":2})"}}, + {"specimens[0].limit", glz::raw_json{R"({"num":3,"den":1,"dp":2})"}}}}); + CHECK(load.loaded == 1); + CHECK(load.refused.empty()); // a removed row is dropped, not refused + CHECK(f.json("specimens[0].limit") == R"({"num":300,"den":100,"dp":2})"); + CHECK(f.form->field("specimens").rows().size() == 1); +} + +// Mutation: a derive reply that moves the loaded snapshot of the members it writes. +TEST_CASE("grid: a derive reply moves no snapshot", "[ui][grid][derive]") { + GridFixture f{1}; + f.grid->focusCell(at(1, "mass")); f.grid->type("4"); f.grid->press("Enter"); + auto const round = f.form->captureRound(); + auto const load = f.form->loadDerived(round, forms::Derived{.values = {{"specimens[0].limit", glz::raw_json{R"({"num":1,"den":1,"dp":2})"}}, + {"specimens[0].mass", glz::raw_json{R"({"num":5,"den":1,"dp":2})"}}}}); + CHECK(load.loaded == 1); + CHECK(load.refused == std::vector{"specimens[0].mass"}); + CHECK(f.form->modified("specimens#1.mass")); + CHECK(f.form->field("specimens[0].mass").draft() == "4"); + CHECK_FALSE(f.form->modified("specimens#1.limit")); // a derived member draws no modified mark +} + +// Mutation: the column's field resolved once for every row. +TEST_CASE("grid: kind per row", "[ui][grid][derive]") { + // schema: rows {isChoice: boolean, choice: enum ["low","high"], amount: decimal 1 place, mass: decimal 2 places}; + // column {id: "value", fieldOf: isChoice ? "choice" : "amount"}; column "mass" with decimals overlay row 1 -> 1, row 2 -> 3 + // rows: [{isChoice: true}, {isChoice: false}] + CHECK(f.source->field(ui::Key{std::int64_t{1}}, "value")->spec().kind == forms::FieldKind::Enum); + CHECK(f.source->field(ui::Key{std::int64_t{2}}, "value")->spec().kind == forms::FieldKind::Decimal); + f.grid->focusCell(at(2, "value")); f.grid->type("3,5"); f.grid->press("Enter"); + CHECK(f.json("rows[1].amount") == R"({"num":35,"den":10,"dp":1})"); + f.grid->focusCell(at(1, "mass")); f.grid->type("1,25"); f.grid->press("Enter"); + CHECK(f.form->field("rows[0].mass").error().peek()->code == "too-precise"); + f.grid->focusCell(at(2, "mass")); f.grid->type("1,255"); f.grid->press("Enter"); + CHECK(f.json("rows[1].mass") == R"({"num":1255,"den":1000,"dp":3})"); +} + +// Mutation: a fetch per row (no shared fetch). +TEST_CASE("grid: choices per row", "[ui][grid][derive]") { + // rows {material: string, grade: Choice "Lims_ListGrades", x-optionsDependsOn ["material","site"]}; top-level "site" + // prefill site "north", six rows with material A, A, B, B, C, A + CHECK(f.h.server.fetches().empty()); // nothing is fetched before an editor opens + for (std::int64_t key = 1; key <= 6; ++key) { f.grid->focusCell(at(key, "grade")); f.grid->press("F2"); f.grid->press("Escape"); } + REQUIRE(f.h.server.fetches().size() == 3); + CHECK(f.h.server.fetches().at(0).body == R"({"material":"A","site":"north"})"); + CHECK(f.h.server.fetches().at(1).body == R"({"material":"B","site":"north"})"); + CHECK(f.h.server.fetches().at(2).body == R"({"material":"C","site":"north"})"); +} +``` + +Qt Quick: `"qt_quick grid: a column's kind follows its row"` — row 1's `value` cell opens a ComboBox, row 2's a TextField. Mutation as "kind per row". + +- [ ] **Step 3: Run to see them fail** + +Run: `cmake --build --preset cl-debug --target morph_tests` +Expected: compile errors — `morph/forms/derive.hpp` not found; `FormSession::deriveWith` not declared. + +- [ ] **Step 4: Implement `derive.hpp`, `FieldMeta::derived`, the schema, `recomputeAll` over rows and `clearDerived` in `prepareAction`/`evaluateAction`.** + +- [ ] **Step 5: Implement rounds in `FormSession`.** The order the signatures do not determine: + +```text +noteCommit(): a round in flight: mark it stale. Else: no scheduler: startRound() now; else restart the timer + for options.debounce, whose expiry calls startRound() +startRound(): round = captureRound(); state = Running; send evaluate (if set) and derive (if set) with round.body +on a reply: loadDerived(round, reply). loadDerived itself ignores a round whose sequence is below the last one it + loaded for that kind of reply (evaluation or derive), and records the sequence it loads. +both settled: any failed: state = Failed, else Current; stale: clear it and startRound() at once +recalculate(): startRound() unless a round is in flight +``` + +- [ ] **Step 6: Implement row-scoped Choices** (`openOptions`, lookup order, the shared fetch) and the per-row column parts in `grid.hpp`; the lowering's `derive`, `deriveDebounce`, column expressions and overlays. + +- [ ] **Step 7: Run the tests** + +Run: `cmake --build --preset cl-debug --target morph_tests && ctest --test-dir build/cl-debug -R "derive|grid:|computed|evaluate|forms" --output-on-failure` +Expected: all pass, including the existing `test_computed_fields.cpp` and `test_ui_evaluate.cpp` cases. + +- [ ] **Step 8: Mutate**, **Step 9: Docs** (and the docs build), **Step 10: Commit** `feat(forms): derived values for grids`. + +### Task 21: Selecting cells, paste and rows of a grid (editing.md step 3) + +**Spec:** editing.md "Selecting cells, clipboard and fill", "Rows of a grid", Invariant 7; Failure modes rows on paste, insert and delete, `selectionMode: "cells"` on a model's table. + +**Files:** +- Modify: `include/morph/ui/view.hpp`, `include/morph/ui/backend.hpp`, `include/morph/ui/mount.hpp`, `include/morph/ui/testing/recording_backend.hpp`, `include/morph/ui/grid.hpp`, `include/morph/forms/engine/field_model.hpp`, `include/morph/forms/engine/form_session.hpp`, `src/ui/document.cpp`, `src/ui/interpreter.cpp`, `src/qt_quick/table.cpp` and QML, `src/tui/table_widget.cpp`; `tests/test_ui_grid.cpp`, `tests/test_ui_mount.cpp`, `tests/qt_quick/test_qt_quick_table.cpp` +- Docs: `docs/spec/ui/document.md`, `docs/spec/ui/interpreter.md` (`selectionMode: "cells"` and its value, `appendRows`, `rowsFixed`, the row menu entries, "Add row"), `docs/spec/ui/view_tree.md` and `docs/spec/ui/backend_contract.md` (`Table::cellSelection`, `setCellSelection`, `setOnCellSelect`). + +**Interfaces:** +- Consumes: Task 19's `GridController`, `GridSource`; Task 20's `FieldState::insertRow`; Task 12b's `IViewBackend::copyText` (the lowering hands it `GridController::copy()`) and Task 9d's `ScreenCore::tableMessage` with Task 17a's entries overload; Task 17d's `TableOptions::cellMenu`; Task 19's `cellEntries`, `messageEntries`, `chooseEntry`. +- Produces: + - `view.hpp`: `struct CellRange { CellRef anchor; CellRef focus; bool operator==(CellRange const&) const = default; };` (beside `CellRef`); `Table::cellSelection` (`std::optional>>`: when set, the table selects cells, not rows) and `Table::onCellSelect` (`std::function)>`). The mount maps between keys and view positions: it shows a range with `setCellSelection` at the corners' view positions and visible positions now (so a sort or a column move redraws the rectangle the same corners span), and turns a reported rectangle into a `CellRange` through the rows' keys and the layout's ids. A corner whose row is not in the view, or whose column is hidden, shows no rectangle; the range is kept. + - `backend.hpp` (defaults do nothing): `virtual void TableWidget::setCellSelection(std::optional> rect)` (`{firstRow, rowCount, firstPosition, positionCount}` in view rows and visible positions — a rectangle is of the layout, so these are positions, not `Table::columns` indices, index #37; empty: none; never calls the handler) and `virtual void TableWidget::setOnCellSelect(std::function onSelect)` (a drag from cell to cell, a `Shift`+click, a row header click — anchor `(row, 0)`, focus `(row, last position)` — and a column header's selection gesture — anchor `(0, position)`, focus `(last row, position)`). In cell mode the backend draws no row selection and reports no `onSelectionChange`. `Shift`+arrows and `Ctrl+A` are the grid's chords (declared with `setKeys`), not the backend's. + - `recording_backend.hpp`: records `setCellSelection` as property `cellSelection` (`"r+,c+"`, `""` for none; `c` counts visible positions); driver `void selectCells(int tableId, std::size_t anchorRow, std::size_t anchorPosition, std::size_t focusRow, std::size_t focusPosition)`. + - `field_model.hpp`: `std::optional FieldSpec::minItems, maxItems;` read from an array's `minItems`/`maxItems`. + - `form_session.hpp`: `struct RemovedRow { std::size_t position; std::shared_ptr row; };` `std::vector FieldState::removeRows(std::span keys);` `void FieldState::restoreRows(std::vector rows);` (each back at its position, ascending). + - `grid.hpp`: `GridOptions` gains `bool appendRows = false; bool rowsFixed = false;` `GridController` gains `[[nodiscard]] std::optional selection() const` (tracked), `void select(std::optional range)`, `[[nodiscard]] std::string copy() const` (tab-separated display text of the rectangle, view order, layout order; a tab or line break inside a cell written as a space), `PasteResult paste(std::string_view text)`, `void fillDown()`, `void clear()`, `void insertRow(bool below)`, `void deleteRows()`, `void undo()`, `[[nodiscard]] RowOps rowOps() const` (tracked); `struct PasteResult { std::size_t written = 0; std::size_t readOnly = 0; std::size_t pastRows = 0; std::size_t pastColumns = 0; };` `[[nodiscard]] std::string pasteMessage(PasteResult const& result);` `struct RowOps { bool insert; bool remove; std::string why; };` `GridSource` gains `appendRow() -> std::optional`, `insertRow(std::size_t position) -> std::optional`, `removeRows(std::span) -> bool` (true when one held a value), `undoRemove() -> void`, `bounds() -> std::pair>` (minItems, maxItems). + - Chords: `Shift`+arrows extend from the anchor; `Ctrl+A` the whole grid; `Ctrl+C` copy; `Ctrl+V` paste; `Ctrl+D` fill down; `Delete` clear; `Ctrl+Shift+=` insert below; `Ctrl+-` delete; a row header click selects its row, a column header's selection gesture its column. + - Copy, exact: paste message `"Pasted {written} values"`, then, when anything was dropped, `"; "` and the parts present joined by `" and "`: `"{readOnly} on read-only cells"`, `"{pastRows} past the last row"`, `"{pastColumns} past the last column"`, then `" were dropped"`. Deletion of rows holding values: the message `"Deleted {n} rows"` (`"Deleted 1 row"`) with `messageEntries()` `{StatusEntry{"undo", "Undo"}}` (index #19: a transient notice with a choice, posted through `tableMessage`'s entries overload); `chooseEntry("undo")` calls `undo()`, which restores the rows while no change has followed the deletion and does nothing after one (the next change also clears the entries). Disabled entries: at `maxItems` `"A grid holds at most {maxItems} rows"`, at `minItems` `"A grid holds at least {minItems} rows"`; with `rowsFixed` no entry is offered. + - Paste, which the signatures do not determine: lines split on `\n`, a trailing `\r` removed from each, a final empty line dropped; cells split on `\t`; each value trimmed of spaces. Start: the focused cell; in a grid with no rows, the first visible column of the first row the paste adds. Row `r0+i` past the last row: appended when `appendRows` and the count is below `maxItems`, else every value of that line counts in `pastRows`. Column `c0+j` past the last visible column counts in `pastColumns`. A read-only or covered target counts in `readOnly`. Every other value is written with `write` (the cell's draft, in the user's locale), all in one runtime batch, then `committed()` once. Fill and clear: editable cells of the rectangle only, one batch, one `committed()`. + - **One change per row operation.** `insertRow`, `deleteRows`, `undo`, a row appended by the walk and the "Add row" button each change the form once and call `committed()` exactly once, however many rows they touch, so each causes one derive round. + - **Menu entries.** `cellEntries(row, column)` gains, after "Revert cell" and "Revert row" and a separator: "Insert row above", "Insert row below", and "Delete row" — "Delete rows" when the cell selection spans more than one row, deleting every row it spans. "Insert row …" is disabled at `maxItems` and "Delete …" at `minItems` (or when the deletion would go below it), each with its `MenuItem::description` the reason (the copy above). With `rowsFixed` none of the three is offered. The lowering offers the same three in the table's own menu (Part E's `TableOptions::menu` with no column) for the focused row. With `appendRows`, `node()` draws an "Add row" button under the table (test id `
_addRow`), disabled at `maxItems` with the same reason as its tooltip; it appends a row and focuses its first editable cell. + - Document: `selectionMode: "cells"` (the default for a grid of a form; refused on a model's table), `selection`/`onSelectionChange` with `{"anchor": {"key", "column"}, "focus": {"key", "column"}}` or `null`; `appendRows`, `rowsFixed` (literal flags). + +- [ ] **Step 1: Write the failing tests** in `tests/test_ui_grid.cpp`: + +```cpp +// Mutation: CellRange stored as view positions (the sort moves the corners onto other rows). +TEST_CASE("grid: cell selection", "[ui][grid][cells]") { + GridFixture f{3}; + for (auto const& [key, text] : {std::pair{1, "3"}, {2, "1"}, {3, "2"}}) { + f.grid->focusCell(at(key, "mass")); f.grid->type(text); f.grid->press("Enter"); + } + f.grid->focusCell(at(1, "mass")); + f.grid->press("Shift+Down"); f.grid->press("Shift+Right"); + CHECK(f.grid->selection() == ui::CellRange{at(1, "mass"), at(2, "volume")}); + REQUIRE(f.source->view().setSort({table::SortKey{.column = "mass"}}).has_value()); + CHECK(f.grid->selection() == ui::CellRange{at(1, "mass"), at(2, "volume")}); // corners kept by key + CHECK(f.grid->copy() == "1,00\t\n2,00\t\n3,00\t"); // rows 2, 3, 1 now lie between the corners' positions +} +// Mutation: the loader accepting selectionMode "cells" on a model-backed table (loadDocumentText succeeds). +TEST_CASE("grid: cells on a model's table are refused when the document loads", "[ui][grid][cells]") { + // {"kind":"table","model":"m","table":"specimens","selectionMode":"cells"}: loadDocumentText fails, message names selectionMode +} + +// Mutation: a paste that shifts a value past a read-only cell into the next editable one. +TEST_CASE("grid: paste, fill, clear", "[ui][grid][cells]") { + std::string schema{kSpecimens}; + schema.replace(schema.find(R"("maxItems":5)"), 12, R"("maxItems":2)"); + GridFixture f{1, ui::GridOptions{.appendRows = true}, schema}; + f.enableDerive(); + f.grid->focusCell(at(1, "volume")); // columns: volume, density (read-only), limit (read-only), note + auto const result = f.grid->paste("1\t2\t3\ta\n4\t5\t6\tb\n7\t8\t9\tc"); // 3 rows × 4 columns + CHECK(result.written == 4); // volume and note of two rows + CHECK(result.readOnly == 4); + CHECK(result.pastRows == 4); + CHECK(f.grid->message() == "Pasted 4 values; 4 on read-only cells and 4 past the last row were dropped"); + CHECK(f.form->field("specimens[0].note").draft() == "a"); // the block keeps its shape + CHECK(f.form->field("specimens[1].volume").draft() == "4"); + CHECK(f.form->field("specimens").rows().size() == 2); // one row added, to maxItems + f.scheduler.advance(150ms); f.h.settle(); + CHECK(f.evaluate.submits().size() == 1); // one paste, one round + f.grid->select(ui::CellRange{at(1, "volume"), at(2, "note")}); + f.grid->fillDown(); + CHECK(f.form->field("specimens[1].volume").draft() == "1"); + CHECK(f.form->field("specimens[1].note").draft() == "a"); + f.grid->clear(); + CHECK(f.form->field("specimens[0].volume").draft().empty()); + CHECK(f.form->field("specimens[1].note").draft().empty()); + CHECK(f.form->field("specimens[0].density").draft().empty()); // read-only: never written +} + +// Review Focus 1, paste half. Mutation: an empty grid's paste starting nowhere and appending nothing. +TEST_CASE("grid: paste into an empty grid", "[ui][grid][cells]") { + SECTION("with appendRows") { + GridFixture f{0, ui::GridOptions{.appendRows = true}}; + auto const result = f.grid->paste("x\t1\ny\t2\nz\t3"); + CHECK(result.written == 6); + CHECK(f.form->field("specimens").rows().size() == 3); + CHECK(f.form->field("specimens[2].label").draft() == "z"); + CHECK(f.form->field("specimens[2].mass").draft() == "3"); + } + SECTION("without appendRows") { + GridFixture f{0}; + auto const result = f.grid->paste("x\t1\ny\t2"); + CHECK(result.written == 0); + CHECK(result.pastRows == 4); + CHECK(f.form->field("specimens").rows().empty()); + CHECK(f.grid->message() == "Pasted 0 values; 4 past the last row were dropped"); + } +} + +// Review Focus 3. Mutation: lines split on "\n" only, keeping "\r" and the trailing empty line. +TEST_CASE("grid: spreadsheet clipboard text pastes as typed values", "[ui][grid][cells]") { + GridFixture f{2, ui::GridOptions{.appendRows = true}}; + f.grid->focusCell(at(1, "mass")); + auto const result = f.grid->paste(" 12,5 \t1.234,5\r\n3\t4\r\n"); + CHECK(result.written == 4); + CHECK(result.pastRows == 0); + CHECK(f.form->field("specimens").rows().size() == 2); // no third row from the trailing line break + CHECK(f.json("specimens[0].mass") == R"({"num":1250,"den":100,"dp":2})"); + CHECK(f.json("specimens[0].volume") == R"({"num":12345,"den":10,"dp":1})"); + CHECK(f.form->field("specimens[1].volume").draft() == "4"); +} + +// Mutation: insert and delete without checking minItems and maxItems. +TEST_CASE("grid: rows of a grid", "[ui][grid][rows]") { + std::string schema{kSpecimens}; + schema.replace(schema.find(R"("minItems":0)"), 12, R"("minItems":1)"); + schema.replace(schema.find(R"("maxItems":5)"), 12, R"("maxItems":2)"); + GridFixture f{1, {}, schema}; + f.grid->focusCell(at(1, "label")); + CHECK_FALSE(f.grid->rowOps().remove); + CHECK(f.grid->rowOps().why == "A grid holds at least 1 rows"); + f.grid->press("Ctrl+Shift+="); + CHECK(f.form->field("specimens").rows().size() == 2); + CHECK_FALSE(f.grid->rowOps().insert); + CHECK(f.grid->rowOps().why == "A grid holds at most 2 rows"); + f.grid->type("kept"); f.grid->press("Enter"); // (1, label) + f.grid->focusCell(at(1, "label")); + f.grid->press("Ctrl+-"); + CHECK(f.form->field("specimens").rows().size() == 1); + CHECK(f.grid->message() == "Deleted 1 row"); + CHECK(f.grid->messageEntries() == std::vector{{"undo", "Undo"}}); + f.grid->chooseEntry("undo"); + CHECK(f.form->field("specimens[0].label").draft() == "kept"); + SECTION("rowsFixed offers none") { + GridFixture fixed{2, ui::GridOptions{.rowsFixed = true}}; + CHECK_FALSE(fixed.grid->rowOps().insert); + CHECK_FALSE(fixed.grid->rowOps().remove); + fixed.grid->focusCell(at(2, "note")); + CHECK(fixed.grid->press("Tab") == ui::KeyOutcome::FocusNext); + } + SECTION("appendRows adds a row on Tab past the end") { + GridFixture grow{1, ui::GridOptions{.appendRows = true}}; + grow.grid->focusCell(at(1, "note")); + CHECK(grow.grid->press("Tab") == ui::KeyOutcome::Handled); + CHECK(grow.form->field("specimens").rows().size() == 2); + CHECK(grow.grid->focus() == at(2, "label")); + } +} + +// Mutation: the row entries offered with no bound check (Insert enabled at maxItems). +TEST_CASE("grid: row entries in the cell's menu and Add row", "[ui][grid][rows]") { + std::string schema{kSpecimens}; + schema.replace(schema.find(R"("maxItems":5)"), 12, R"("maxItems":3)"); + GridFixture f{2, ui::GridOptions{.appendRows = true}, schema}; + auto entries = f.grid->cellEntries(ui::Key{std::int64_t{1}}, "label"); + CHECK(labelsOf(entries) == std::vector{"Revert cell", "Revert row", "", "Insert row above", + "Insert row below", "Delete row"}); // "" the separator + entry(entries, "Insert row above").onSelect(); + CHECK(keysOf(*f.source).size() == 3); + CHECK(keysOf(*f.source).at(1) == ui::Key{std::int64_t{1}}); // the new row stands above row 1 + entries = f.grid->cellEntries(ui::Key{std::int64_t{1}}, "label"); + CHECK_FALSE(enabledOf(entry(entries, "Insert row below"))); + CHECK(descriptionOf(entry(entries, "Insert row below")) == "A grid holds at most 3 rows"); + f.grid->select(ui::CellRange{at(1, "label"), at(2, "mass")}); + entries = f.grid->cellEntries(ui::Key{std::int64_t{1}}, "label"); + entry(entries, "Delete rows").onSelect(); + CHECK(keysOf(*f.source).size() == 1); + SECTION("rowsFixed offers no row entry") { + GridFixture fixed{2, ui::GridOptions{.rowsFixed = true}}; + CHECK(labelsOf(fixed.grid->cellEntries(ui::Key{std::int64_t{1}}, "label")) == + std::vector{"Revert cell", "Revert row"}); + } +} + +// Mutation: insertRow calling committed() once per member it creates (several rounds for one insertion). +TEST_CASE("grid: each row operation is one change", "[ui][grid][rows]") { + GridFixture f{3}; + f.enableDerive(); + f.grid->focusCell(at(1, "label")); + f.grid->insertRow(true); + f.scheduler.advance(150ms); f.h.settle(); + CHECK(f.evaluate.submits().size() == 1); + f.evaluate.resolveSubmit(0, R"({"errors":{},"ready":false})"); f.derive.resolveSubmit(0, kNoValues); f.h.settle(); + f.grid->focusCell(at(1, "label")); f.grid->type("x"); f.grid->press("Enter"); + f.scheduler.advance(150ms); f.h.settle(); + f.evaluate.resolveSubmit(1, R"({"errors":{},"ready":false})"); f.derive.resolveSubmit(1, kNoValues); f.h.settle(); + f.grid->select(ui::CellRange{at(1, "label"), at(4, "label")}); // view [1, 4, 2, 3]: rows 1 and 4 + f.grid->deleteRows(); // two rows, one holding a value + f.scheduler.advance(150ms); f.h.settle(); + CHECK(f.evaluate.submits().size() == 3); + f.evaluate.resolveSubmit(2, R"({"errors":{},"ready":false})"); f.derive.resolveSubmit(2, kNoValues); f.h.settle(); + f.grid->chooseEntry("undo"); + f.scheduler.advance(150ms); f.h.settle(); + CHECK(f.evaluate.submits().size() == 4); +} +``` + +`tests/grid_test_support.hpp` gains `descriptionOf(ui::MenuItem const&) -> std::string`. + +`tests/test_ui_mount.cpp`, over `RecordingBackend` and a client-mode table node with `cellSelection` bound to a signal and three rows keyed 1, 2, 3, columns `a`, `b`, `c`: + +```cpp +// Mutations: the mount sending the rectangle once at its first positions (the sort leaves "r0+2,c0+2" recorded); +// the mount reading a reported position as a `Table::columns` index (with `a` hidden, position 0 reports column a). +TEST_CASE("mount: a cell selection is shown by its corners' positions now", "[ui][mount][cells]") { + // selection {anchor (1, a), focus (2, b)}: CHECK the table records cellSelection == "r0+2,c0+2" + // re-sort the rows to 3, 1, 2: CHECK cellSelection == "r1+2,c0+2" + // h.backend.selectCells(table, 0, 1, 2, 2): onCellSelect receives {anchor (3, b), focus (2, c)} + // hide column a (index 0): CHECK cellSelection == "" (a corner's column is hidden; the range is kept); + // h.backend.selectCells(table, 0, 0, 0, 1) now reports {anchor (3, b), focus (3, c)}: positions, not indices + // the bound selection set to null: CHECK cellSelection == "" +} +``` + +Qt Quick: `"qt_quick grid: a drag selects a rectangle of cells and a row header click its row"` — a mouse press on (1, mass), a move to (2, volume) and a release report `onCellSelect(0, 1, 1, 2)`, and the QML draws the rectangle `setCellSelection` gives, not a row selection. Mutation: the QML table reporting the drag as a row selection. + +- [ ] **Step 2: Run to see them fail** — `cmake --build --preset cl-debug --target morph_tests`; expected: `GridController::paste` not declared. + +- [ ] **Step 3: Implement** `minItems`/`maxItems`, `removeRows`/`restoreRows`, then the selection, copy, paste, fill, clear and row operations in `grid.hpp`; then the lowering, the loader's refusal, and the backends' row header and column header selection gestures. + +- [ ] **Step 4: Run** `ctest --test-dir build/cl-debug -R "grid:" --output-on-failure` — all pass. + +- [ ] **Step 5: Mutate**, **Step 6: Docs**, **Step 7: Commit** `feat(ui): cell selection, paste and row operations in grids`. + +### Task 22: Bands, spans and summary rows (editing.md step 4) + +**Spec:** editing.md "Header bands", "Spans", "Summary rows", Invariant 8; Failure modes rows on bands, spans and `summaries`; table.md "Column groups" (a group draws as a one-level band). + +**Files:** +- Modify: `include/morph/table/description.hpp`, `include/morph/ui/view.hpp`, `include/morph/ui/mount.hpp`, `include/morph/ui/backend.hpp`, `include/morph/ui/grid.hpp`, `include/morph/ui/form_rows.hpp` (`setGroup`, `runRecords`), `include/morph/ui/testing/recording_backend.hpp`, `src/ui/document.cpp`, `src/ui/interpreter.cpp`, `include/morph/ui/interpreter.hpp`, `src/qt_quick/table.cpp` and QML, `src/tui/table_widget.cpp` +- Tests: `tests/test_ui_mount.cpp`, `tests/test_ui_grid.cpp`, `tests/table/test_table_description.cpp`, `tests/qt_quick/test_qt_quick_table.cpp`, `tests/tui/test_tui_table.cpp` +- Docs: `docs/spec/ui/document.md`, `docs/spec/ui/interpreter.md` (`bands`, a span part's `columns`, `summaries` on `table` and `group`), `docs/spec/ui/view_tree.md` (spans across columns, summary rows), `docs/spec/qt_quick/backend.md` (bands and spans). + +**Interfaces:** +- Consumes: `table::ColumnLayout` (Task 8d), `ui::TableColumn::id` and `Table::arrangement` (Task 9; the mount maps the arrangement's visible indices to ids for `bandRuns`), `ui::formatCell` (Task 15), Task 19's `GridSource::covered`, `GridRows`, `TableRows`. +- Produces: + - `description.hpp`: `struct BandInfo { std::string label; std::string unit; std::vector columns; std::vector bands; bool operator==(BandInfo const&) const = default; };` `std::vector TableDescription::bands;` `[[nodiscard]] std::expected checkBands(std::span bands, std::span columns);` — `SourceContract` for a nesting past 3 levels, a band naming no column, a child over a column its parent lacks, a column in two bands of one level, or a column id the table does not have; the message names the band's label. + - `view.hpp`: `struct BandRun { std::size_t level = 0; std::string label; std::string unit; std::size_t first = 0; std::size_t count = 0; bool pinned = false; bool operator==(BandRun const&) const = default; };` (`first` and `count` are visible positions, not `Table::columns` indices) `std::vector Table::bands;` `std::size_t RowSpan::columns = 1;` (covered columns to the right, by visible position, the cell's own included) `bool TableRowLook::summary = false;` (index #39: the flag is the row look's, beside Part D's `heading` and Task 17b's `marks`; `TableRowView`, the C++ `table()` path's, gains nothing). The mount calls `TableWidget::setRowSummary(row)` once, right after `setRowKey`, for a row whose `rowView` returned `summary == true`, as it calls `setRowHeading`; such a row builds its cells with `cellView` as any row does. + - `mount.hpp`: `[[nodiscard]] std::vector bandRuns(std::span bands, std::span visible, std::size_t pinned);` — `visible` the window's visible column ids in layout order; one run per maximal run of a band's columns standing together, split at the pinned edge; levels from 0 (outermost); a band with no visible column yields none. `[[nodiscard]] bool columnUnitShown(std::span bands, std::string_view columnId, std::string_view unit);` (false when an enclosing band's unit equals `unit`). `[[nodiscard]] std::string bandedHeaderName(std::span bands, std::string_view columnId, std::string_view label);` (outermost band first, joined by `", "`). `struct CellSpan { std::string column; std::size_t rows = 1; std::size_t columns = 1; };` `[[nodiscard]] std::size_t cutColumns(CellSpan const& span, std::span declared, std::span visible);` — the span covers its column, then each next visible column while it is the next declared one, up to `columns`. + - `backend.hpp`: `virtual void TableWidget::setBands(std::vector const& runs) {}`; `virtual void TableWidget::setRowSummary(Widget& row) {}` (a summary row: drawn on the theme's `cellSummary` surface, never selected, activated, focused for an edit or pasted into; copied when a copy covers it; called once, right after `setRowKey`). `setRowSpans` carries `RowSpan::columns`. `recording_backend.hpp` records `setRowSummary` as property `summary` (`"true"`) on the row, and a span as `":"` while `columns == 1` — the format `docs/spec/ui/backend_contract.md` gives and `test_ui_table_row_span.cpp` asserts, unchanged — and as `":x"` otherwise (`0:2x3`). + - `grid.hpp`: `[[nodiscard]] ValueList summaryScopeRows(TableRows const& rows, std::int64_t first, std::int64_t count);` — the records of `count` view rows of `rows` from `first`, in view order (a grid row's record holds each member's encoded value, `null` when blank or not encoding); `rows` is always the **data** rows (`GridSource::view()`, or a `rows` table's `EngineRows`), never the decorator below. + - **How a summary row reaches the mount.** `grid.hpp`: `struct SummarySpec { std::string key; bool top = false; };` and `class SummaryRows final : public TableRows` — `SummaryRows(std::shared_ptr data, std::vector table, std::vector perRun, std::function>()> runs)` — a forwarding decorator (index #40): it is what the mount is handed in place of `data`, it sets `data`'s one `onChange` slot itself and calls the mount's handler with the change translated to its own indices, and it forwards `visible`, `keysOf`, `setSort`, `setFilter`, `counts`, `states`, `moveKey` and `unloadedLevels` (indices translated). Its view is: the table's `top` summaries, then the data rows in view order with each run's `perRun` summaries after the run's last row (`runs()` gives each run's `{first, count}` in `data`'s view; empty for an ungrouped table), then the table's bottom summaries. A summary row's `row(index)` is `TableRowRef{key, record}` with the key below and the record `{"#summary": , "#first": , "#count": }`; `total().rows` and `counts().view` stay `data`'s (a summary is outside the count), and `keysOf` skips summary rows (outside the selection). `[[nodiscard]] std::optional mounted(std::int64_t dataRow) const` and `[[nodiscard]] std::optional data(std::int64_t mountedRow) const` map between the two index spaces. With a `SummaryRows` in place, the lowering passes `TableSource{.rows = the decorator, …}` as `GridController::node`'s `base`; `GridSource::rowCount`, `keyAt`, `positionOf`, the walk, paste and the cell rectangle stay over the data rows, the mount maps a `GridFocus::viewRow` and a rectangle's rows through `mounted()` before `setFocusCell` and `setCellSelection`, and a click, a `FocusMove` or a reported rectangle that lands on a summary row is mapped to the nearest data row by `data()`. `rowView` returns `TableRowLook{.summary = true}` for a record holding `#summary`; `cellView(c, row)` for such a record evaluates the spec's `cells[columns[c].id]` in a scope whose `rows` is `summaryScopeRows(data, #first, #count)` and `column` the column's id, shown by the column's display (`formatCell`), and an empty text cell for a column the spec does not name. A table with no `summaries` gets no decorator. + - **`group` on a grid of a form.** `form_rows.hpp`: `void FormRowsSource::setGroup(std::function by)` — as Task 11a's `ValueRowsSource::setGroup`: the source gains the column `kGroupRunColumn` (`ColumnKind::Integer`, not laid out), a row's cell its run index, runs counted over the array's order, a new run where `by` differs from the previous row's; `[[nodiscard]] std::span runRecords() const` gives the heading records. The lowering of a form grid with `group` puts `{kGroupRunColumn, Ascending}` before every sort chain and places the headings as Task 11b's lowering does for a `rows` table, through the same code; a heading row has no key in `GridSource` (it is not a data row), so `SummaryRows::runs` and the heading placement share one index translation. `void FormGridSource::setSpans(std::function(forms::RowState const&)> spansOf);` — `covered(key, column)` is true for a cell another row's span covers (rows below, columns right by `cutColumns`), while the grid is unsorted and under its windowing thresholds. + - Document: `bands` on `table` (parts `{label, unit, columns, bands}`, refused as `checkBands` refuses); a `rowSpans` part's `columns`; `summaries` on `table` and on a `group` part, parts `{key, label, position, cells}` (`position` `bottom` or `top`; `cells` maps column ids to expressions over `rows` and `column`), refused on a model-backed table when the document loads. A summary row's key is `Key{std::string}`: `"\x1Fsummary:"` + its key (a group's: `"\x1Fsummary:"` + the run's ordinal + `"/"` + its key). A summary cell's test id is `summary__` (a group's `summary___`). A user-formed or declared column group draws as a band of one level. + +- [ ] **Step 1: Write the failing tests.** `tests/test_ui_mount.cpp`: + +```cpp +namespace { +std::vector const kMassBand{{.label = "Mass retained", .unit = "g", .columns = {"m8", "m4", "m2"}}}; +std::vector const kIds{"name", "m8", "m4", "m2", "total"}; +} + +// Mutation: a band drawn from its first to its last column's place, which covers a foreign column. +TEST_CASE("bands: a band follows the layout", "[ui][mount][bands]") { + CHECK(ui::bandRuns(kMassBand, kIds, 0) == std::vector{{0, "Mass retained", "g", 1, 3, false}}); + std::vector const moved{"name", "m8", "m2", "total", "m4"}; + CHECK(ui::bandRuns(kMassBand, moved, 0) == + std::vector{{0, "Mass retained", "g", 1, 2, false}, {0, "Mass retained", "g", 4, 1, false}}); + CHECK(ui::bandRuns(kMassBand, kIds, 2) == + std::vector{{0, "Mass retained", "g", 1, 1, true}, {0, "Mass retained", "g", 2, 2, false}}); + CHECK(ui::bandRuns(kMassBand, std::vector{"name", "total"}, 0).empty()); + CHECK_FALSE(ui::columnUnitShown(kMassBand, "m8", "g")); + CHECK(ui::columnUnitShown(kMassBand, "total", "g")); + CHECK(ui::bandedHeaderName(kMassBand, "m4", "sieve 4 mm") == "Mass retained, sieve 4 mm"); +} + +// Review Focus 2. Mutation: bandRuns computed once from the declared order and not from the layout's visible columns. +TEST_CASE("bands: a stored layout hides then shows a band's column", "[ui][mount][bands]") { + table::ColumnLayout layout{kIds}; + table::ColumnLayout stored{kIds}; + for (auto const* id : {"m8", "m4", "m2"}) stored.setVisible(id, false); + layout.apply(stored.value()); + CHECK(ui::bandRuns(kMassBand, layout.visible(), layout.pinned()).empty()); + layout.setVisible("m4", true); + CHECK(ui::bandRuns(kMassBand, layout.visible(), layout.pinned()) == + std::vector{{0, "Mass retained", "g", 1, 1, false}}); + table::ColumnLayout pinnedAll{kIds}; + pinnedAll.setPinned(4); + CHECK(ui::bandRuns(kMassBand, pinnedAll.visible(), pinnedAll.pinned()) == + std::vector{{0, "Mass retained", "g", 1, 3, true}}); +} + +// Mutation: covered cells left focusable (the walk lands on one). +TEST_CASE("spans: a cell spanning rows and columns covers them", "[ui][mount][spans]") { + std::vector const declared{"a", "b", "c", "d"}; + CHECK(ui::cutColumns({.column = "a", .rows = 2, .columns = 3}, declared, declared) == 3); + CHECK(ui::cutColumns({.column = "a", .rows = 2, .columns = 3}, declared, std::vector{"a", "c", "b", "d"}) == 1); + CHECK(ui::cutColumns({.column = "a", .rows = 2, .columns = 3}, declared, std::vector{"a", "b", "d"}) == 2); +} + +// Mutation: the mount dropping RowSpan::columns before setRowSpans (the row records "0:2"). +TEST_CASE("spans: a span across columns reaches the backend", "[ui][mount][spans]") { + // a TableSource of three rows over columns a, b, c, d whose rowView gives row 1 + // spans = {RowSpan{.column = 0, .rows = 2, .columns = 3}} and row 3 spans = {RowSpan{.column = 1, .rows = 1}} + CHECK(h.backend.prop(rowOf(h, 1), "rowSpans") == "0:2x3"); + CHECK(h.backend.prop(rowOf(h, 3), "rowSpans") == "1:1"); // columns 1 keeps the existing format +} + +// Mutations: setRowSummary called for every row (row 1 records summary); summary rows counted in the realized +// window's total (total 4); the flag read from TableRowView (no row records summary). +TEST_CASE("summary: a summary row is drawn as one, outside the rows", "[ui][mount][summary]") { + // three data rows keyed 1..3 in an EngineRows `data`; SummaryRows{data, {{"stats"}, {"head", true}}, {}, none} + // mounted as TableSource{.rows = decorator}, rowView giving .summary for a record holding #summary + // CHECK the mounted keys in order: "\x1Fsummary:head", 1, 2, 3, "\x1Fsummary:stats" + // CHECK the two summary row widgets record summary == "true", set right after rowKey (the log's next line), + // and rows 1..3 record none + // CHECK decorator.total().rows == 3, decorator.mounted(0) == 1, decorator.data(4) == 2 (the nearest data row) + // CHECK keysOf(0, 5) completes with {1, 2, 3} + // data re-sorted to 3, 1, 2: the mount's one onChange handler ran (keys now head, 3, 1, 2, stats) +} +``` + +`tests/table/test_table_description.cpp`: + +```cpp +// Mutation: checkBands not walking child bands. +TEST_CASE("description: bands are checked", "[table][description][bands]") { + // columns m8, m4, m2, total + CHECK(table::checkBands(kMassBand, columns).has_value()); + // four levels deep; a band over no column; a child over "total" which its parent lacks; "m8" in two bands of one level + // each: CHECK(error().code == table::TableErrorCode::SourceContract) and the message contains the band's label +} +``` + +`tests/test_ui_grid.cpp`: + +```cpp +// Mutation: a paste writing into a covered cell (the spanning cell's value changes twice, or the covered field is written). +TEST_CASE("grid: spans pass the walk and drop pasted values", "[ui][grid][spans]") { + GridFixture f{3}; + f.source->setSpans([](forms::RowState const& row) { + return row.key() == 1 ? std::vector{{.column = "mass", .rows = 2, .columns = 2}} : std::vector{}; + }); + CHECK(f.source->covered(ui::Key{std::int64_t{2}}, "mass")); + CHECK(f.source->covered(ui::Key{std::int64_t{1}}, "volume")); + CHECK(f.source->covered(ui::Key{std::int64_t{2}}, "volume")); + f.grid->focusCell(at(1, "mass")); + f.grid->press("Tab"); + CHECK(f.grid->focus() == at(1, "note")); // volume covered, density and limit read-only + f.grid->focusCell(at(1, "mass")); f.grid->type("1"); f.grid->press("Enter"); + CHECK(f.grid->focus() == at(3, "mass")); // (2, mass) is covered + f.grid->focusCell(at(1, "mass")); + auto const result = f.grid->paste("1\n2\n3"); + CHECK(result.written == 2); + CHECK(result.readOnly == 1); + CHECK(f.form->field("specimens[1].mass").draft().empty()); + table::ColumnLayout layout{{"label", "mass", "volume", "density", "limit", "note"}}; + // moving volume away cuts the span: with volume after note, (1, volume) is no longer covered + layout.move("volume", 5); + f.source->setLayout(layout.visible()); // the grid's visible columns follow the layout + CHECK_FALSE(f.source->covered(ui::Key{std::int64_t{1}}, "volume")); +} + +// Mutation: the grid's walk and paste running over the decorator's rows (Tab lands on the summary row; a paste +// counts it as a read-only row instead of running past the last row). +TEST_CASE("summary: a grid's walk, paste and scope do not see summary rows", "[ui][grid][summary]") { + GridFixture f{2}; + auto const data = std::shared_ptr{std::shared_ptr{}, &f.source->view()}; + ui::SummaryRows rows{data, {{.key = "stats"}}, {}, [] { return std::vector>{}; }}; + CHECK(f.source->rowCount() == 2); + f.grid->focusCell(at(2, "note")); + CHECK(f.grid->press("Tab") == ui::KeyOutcome::FocusNext); // nothing below row 2 for the grid + f.grid->focusCell(at(2, "label")); + auto const result = f.grid->paste("a\nb"); + CHECK(result.written == 1); + CHECK(result.pastRows == 1); + CHECK(result.readOnly == 0); + CHECK(ui::summaryScopeRows(f.source->view(), 0, 2).size() == 2); + CHECK(rows.mounted(1) == std::optional{1}); + CHECK(rows.row(2)->key == ui::Key{std::string{"\x1Fsummary:stats"}}); +} + +// Mutation: summaryScopeRows reading the source's snapshot, which ignores the filter. +TEST_CASE("summary: rows follow the filter", "[ui][grid][summary]") { + GridFixture f{3}; + for (auto const& [key, text] : {std::pair{1, "10"}, {2, "12"}, {3, "14"}}) { + f.grid->focusCell(at(key, "mass")); f.grid->type(text); f.grid->press("Enter"); + } + REQUIRE(f.source->view().setFilter(table::FilterSpec{.columns = {{"mass", + table::ColumnFilter{.include = {table::FilterEntry{.gt = "11"}}}}}}).has_value()); + ValueList const rows = ui::summaryScopeRows(f.source->view(), 0, f.source->view().total().rows); + REQUIRE(rows.size() == 2); + CHECK(canonicalJson(*rows.at(0).field("mass")) == R"({"num":1200,"den":100,"dp":2})"); +} +``` + +Interpreter cases (`TableHarness`, which formats in `en`; a whole document with a `models` block: the `Lims_RecordSpecimens` form and a grid with `"summaries":[{"key":"stats","cells":{"mass":{"fn":"mean","args":[{"map":{"ref":"rows"},"as":"r","to":{"ref":"r.mass"}}]},"label":{"fn":"count","args":[{"ref":"rows"}]}}},{"key":"sd","cells":{"mass":{"fn":"stdev","args":[{"map":{"ref":"rows"},"as":"r","to":{"ref":"r.mass"}},2]}}}]`): + +```cpp +// Mutation: summaries evaluated once at lowering (they do not follow a committed value). +TEST_CASE("summary: mean and stdev follow every committed value", "[ui][grid][summary][interpreter]") { + // masses 10.00 / 12.00 / 14.00 typed through the grid + CHECK(h.text("summary_stats_mass") == "12.00"); + CHECK(h.text("summary_sd_mass") == "2.00"); + CHECK(h.text("summary_stats_label") == "3"); + // type 16.00 into row 3 + CHECK(h.text("summary_stats_mass") == "12.67"); // 38/3 at the column's 2 places +} +// Review Focus 1, summary half. Mutation: count over the source rows or mean of [] shown as "0". +TEST_CASE("summary: over no rows", "[ui][grid][summary][interpreter]") { + // the same document with no specimens + CHECK(h.text("summary_stats_label") == "0"); + CHECK(h.text("summary_stats_mass").empty()); +} +// Mutations: a group's summary evaluated over every row of the table (both runs show 12.00); FormRowsSource with +// no run column (the grid draws no heading and one run). +TEST_CASE("summary: group summaries are per run", "[ui][grid][summary][interpreter]") { + // the grid with "group": {"by": {"ref": "row.label"}, "heading": …, "summaries": [{key: "m", cells: {mass: mean}}]}; + // labels A, A, B; masses 10, 12, 14 + CHECK(h.text("summary_0_m_mass") == "11.00"); + CHECK(h.text("summary_1_m_mass") == "14.00"); + // rowKeys(h, "grid") in order: heading A, 1, 2, "\x1Fsummary:0/m", heading B, 3, "\x1Fsummary:1/m" + // sorting the grid by mass descending keeps the runs: A's rows are 2, 1 and its summary still 11.00 + // Enter on (2, mass) with enterMoves down lands on (3, mass): the heading and the summary are passed over +} +// Mutation: the loader checking `summaries` on the table node and not on its group part (the second loads). +TEST_CASE("summary: a model-backed table refuses summaries", "[ui][summary][interpreter]") { + // {"kind":"table","model":"m","table":"specimens","summaries":[…]} and a group part with summaries: both refused +} +``` + +Qt Quick: `"qt_quick table: a band draws over each run of its columns and across the pinned edge"` — after `setBands({{0,"Mass retained","g",1,2,false},{0,"Mass retained","g",4,1,false}})` the header holds two band items whose x and width equal the covered columns' extents. Mutation: the QML band item placed from its first run's x to its last run's end (one item, as wide as columns 1–4). TUI: `"tui table: bands draw above the header"` — the rendered header's first line holds `Mass retained [g]` over columns 1–3. Mutation: the terminal table drawing the band over the declared columns' widths instead of the runs `setBands` gave (the label starts over column 0). + +- [ ] **Step 2: Run to see them fail** — `cmake --build --preset cl-debug --target morph_tests`; expected: `ui::bandRuns` not declared. + +- [ ] **Step 3: Implement** `BandInfo`, `checkBands`, `bandRuns`, `columnUnitShown`, `bandedHeaderName`, `cutColumns`; the mount's bands (over the column window's columns), its column spans, `TableRowLook::summary` → `setRowSummary`; `SummaryRows`, `summaryScopeRows`, `FormRowsSource::setGroup`; the lowering (the decorator handed to the mount, the index mapping for focus and the cell rectangle) and loader; then the Qt Quick and terminal drawing. + +- [ ] **Step 4: Run** `ctest --test-dir build/cl-debug -R "bands|spans|summary|description" --output-on-failure` (and the Qt Quick and TUI patterns `qt_quick table` and `tui table`) — all pass; the existing row-span cases in `test_ui_table_row_span.cpp` still pass with `columns` 1. + +- [ ] **Step 5: Mutate**, **Step 6: Docs**, **Step 7: Commit** `feat(ui): header bands, spans and summary rows`. + +### Task 23: Fixed grids (editing.md step 5) + +**Spec:** editing.md "Fixed grids" (with blocks), Failure modes rows "Two `layoutRows` parts with one key" and "`form` and `rows` both on a table, `layoutRows` with `rows` or `field`, or a `{field}` cell in a fixed grid without `form`". + +**Files:** `include/morph/ui/grid.hpp`, `src/ui/document.cpp`, `src/ui/interpreter.cpp`, `include/morph/ui/interpreter.hpp`, `tests/ui_interpreter_support.hpp` (schema `Lims_SetLimits`), `tests/test_ui_grid.cpp`; docs `docs/spec/ui/document.md`, `docs/spec/ui/interpreter.md` (`layoutRows`, cell parts, blocks). + +**Interfaces:** +- Consumes: Task 19–21 `GridSource`, `GridController`, `cellReadOnly`; Task 22 `CellSpan`, `cutColumns`. +- Produces: `grid.hpp`: `struct FixedCell { std::string field; std::function value; std::string text; std::size_t rows = 1; std::size_t columns = 1; std::function readonly; std::function()> decimals; };` `struct FixedRow { std::string key; std::string label; std::map> cells; };` `struct FixedBlock { std::string forEach; std::vector rows; };` `class FixedGridSource final : public GridSource` — `FixedGridSource(forms::FormSession* form, std::vector> rows, std::vector columns, FormatContext format)` (`form` null for a fixed grid of `{text}` and `{value}` cells only, which the loader allows without `form`; a `{field}` cell with `form` null is the loader's refusal, so the source never meets one); every row is held, so `keyAt` is never empty below `rowCount`; row keys are `Key{std::string}`: a fixed row's `key`, a block row's `"/"`; a block's `{field}` path is relative to the specimen's row (`specimens#.`); a cell with `{text}` or `{value}` is read-only. Not sorted, filtered or rearranged by rows; columns may be hidden and resized. Its `view()` is an `EngineRows` over an internal `table::DataSource` the source owns (one `Text` column `#key`, one row per expanded row, in order, `Reset` on each change of a block's array rows), built with `table::EngineOptions{}` and never sorted or filtered, its `recordOf` giving `RowRecord{RowId{key}, {"#key": key}}`, which `keyOf` reads; `states()` and `moveKey` are `EngineRows`'; `editor(key, column)` is `scalarControl(*form, field)` for a `{field}` cell; `rowModified(key)` is true while a `{field}` cell of the row is `FormSession::modified`. + +- [ ] **Step 1: Write the failing tests** — the fixture, in `tests/grid_test_support.hpp`: + +```cpp +// A fixed grid over the Lims_SetLimits form: columns `min`, `max` (and `v` for the block case), in a comma locale. +struct FixedGridFixture { + morph::test::formsengine::Harness h; + std::unique_ptr form; + std::unique_ptr source; + std::unique_ptr grid; + // Prefills `body`, builds the source over `rows` and `columns` and the controller with default options. + FixedGridFixture(std::string_view body, std::vector> rows, + std::vector columns); + [[nodiscard]] std::string json(std::string_view path) const; +}; +``` + +Each case below declares `FixedGridFixture f{…}` with the rows its comment gives. `Lims_SetLimits` schema: `limits` object with `density {min, max}` (decimals, 3 places), `moisture {min, max}` (decimals, 1 place), `method` (enum `["A","B"]`), `count` (integer); and `specimens` (array of `{mass: decimal 2}`). + +```cpp +// Mutation: the walk asking the field's spec of the column's first row for every row (one kind per column). +TEST_CASE("fixed grid: four parameters walk, paste and validate per cell", "[ui][grid][fixed]") { + // rows: density {min: limits.density.min, max: limits.density.max}; moisture {min, max}; + // method {min: {field: limits.method, columns: 2}}; count {min: limits.count, max: {text: "—"}} + f.grid->focusCell(ui::CellRef{ui::Key{std::string{"density"}}, "min"}); + std::vector> walked; + for (int i = 0; i < 5; ++i) { f.grid->press("Tab"); walked.emplace_back(std::get(f.grid->focus()->key), f.grid->focus()->column); } + CHECK(walked == std::vector>{ + {"density", "max"}, {"moisture", "min"}, {"moisture", "max"}, {"method", "min"}, {"count", "min"}}); + CHECK(f.grid->press("Tab") == ui::KeyOutcome::FocusNext); // count.max is text: read-only + f.grid->focusCell(ui::CellRef{ui::Key{std::string{"density"}}, "min"}); + auto const result = f.grid->paste("1,2345\t2\n0,55\tx"); + CHECK(result.written == 4); + CHECK(f.form->field("limits.density.min").error().peek()->code == "too-precise"); // 3 places + CHECK(f.json("limits.density.max") == R"({"num":2000,"den":1000,"dp":3})"); + CHECK(f.form->field("limits.moisture.min").error().peek()->code == "too-precise"); // 1 place + CHECK(f.form->field("limits.moisture.max").error().peek()->code == "malformed"); +} + +// Mutation: block row keys by position, which move every row's state on insertion. +TEST_CASE("fixed grid: a forEach block repeats per specimen with stable keys", "[ui][grid][fixed]") { + // rows: [{forEach: "specimens", rows: [{key: "mass", cells: {v: {field: "mass"}}}]}], two specimens (keys 1, 2) + CHECK(keysOf(*f.source) == std::vector{ui::Key{std::string{"1/mass"}}, ui::Key{std::string{"2/mass"}}}); + f.grid->focusCell(ui::CellRef{ui::Key{std::string{"2/mass"}}, "v"}); f.grid->type("5"); f.grid->press("Enter"); + std::uint64_t const added = f.form->field("specimens").insertRow(0); + CHECK(keysOf(*f.source).front() == ui::Key{std::to_string(added) + "/mass"}); + CHECK(f.source->draft(ui::Key{std::string{"2/mass"}}, "v") == "5"); +} + +// Mutation: the loader's duplicate-key check comparing keys within one block only (two top-level "density" load). +TEST_CASE("fixed grid: the loader refuses what the spec refuses", "[ui][grid][fixed]") { + // each refused by loadDocumentText: two layoutRows parts with key "density"; layoutRows with rows; + // layoutRows with field; a {field} cell without form; form with rows +} +``` + +- [ ] **Step 2: Run to see them fail**; **Step 3: Implement** `FixedGridSource` and the lowering of `layoutRows` (expanding blocks on each change of the block's array rows); **Step 4: Run** `ctest --test-dir build/cl-debug -R "fixed grid" --output-on-failure` — pass; **Step 5: Mutate**; **Step 6: Docs**; **Step 7: Commit** `feat(ui): fixed grids`. + +### Task 24: Cells of a model's table (editing.md step 6) + +**Spec:** editing.md "Cells of a model's table", "Read-only and computed" (the model-table half), "Walking" (moving by view position), Invariant 6; Failure modes rows on edit kinds, `editMode`, refused edits, `FieldError`/`FailedRow`; table.md "Rows an action changed" (a key that changes), "Rows at work, rows that failed". Needs Tasks 9 and 17. + + +**Carried from Task 19's review:** `GridController::place()` resolves a placeholder's key (`keyAt(viewRow)`) untracked, so the `gridFocus` binding does not run again when the row arrives. It is dormant for a grid of a form, whose rows are all fetched, and is fixed here: `place()` reads the source's row arrival tracked (the view's change, or `keyAt` through a tracked read), with a case where the walk stops at an unfetched row, the row then arrives, and `focus()` names the cell with no further gesture (mutation: the read untracked again). + +**Files:** +- Modify: `include/morph/table/edits.hpp`, `include/morph/table/description.hpp`, `include/morph/forms/forms.hpp` (`annotateSchemaRoot`), `include/morph/ui/interpreter.hpp` and `src/ui/interpreter.cpp` (`TableInputKind::CellEdit` in `tableInputsOf`, read at the schema root, so a `CellEdit`/`RowEdit` run the session's mutations make marks its row busy through `RowStates`), `include/morph/ui/grid.hpp`, `include/morph/ui/table_rows.hpp` (`WindowRows::onRowsAbsent`), `tests/grid_test_support.hpp` (`FakeRows`, `ModelGridFixture`), `tests/ui_table_support.hpp` (the two edit actions in `TableHarness`'s catalog), `src/ui/document.cpp`, `src/ui/interpreter.cpp`, `include/morph/ui/interpreter.hpp`, `tests/ui_interpreter_support.hpp` (schemas `Lims_EditSpecimenCount`, `Lims_EditSpecimenRow`) +- Tests: `tests/table/test_table_pending.cpp` (the `CellEdits` cases, beside its existing ones), `tests/table/test_table_description.cpp`, `tests/test_ui_table_model.cpp`, `tests/net/test_push_tables.cpp` +- Docs: `docs/spec/ui/document.md`, `docs/spec/ui/interpreter.md` (`editMode`, an editable model column's lowering), `docs/spec/table/engine.md` (`CellEdits` row commits, drafts by key). + +**Interfaces:** +- Consumes: `TableRows`, `WindowRows::setDescription`, `onStaleDescription` (Task 9); `TableRows::states()` (`isBusy`, `failure`), `TableRows::moveKey`, `lockText`, `refusesEdit`, `FailedRow`, `ChangedRows::failed` (Task 17c); `DeclaresSchemaValue`, `model::recordRegistry()`, `TableInputKind`, `tableInputsOf` (Task 17a); `ScreenCore::tableMessage` (Task 9d); `Session::can(action)` (existing); `forms::FormModel::fromSchema`, `forms::FormSession` (existing); Task 19's `GridController`, `GridSource`, `cellReadOnly`; `ModelChannel::execute(actionId, body, CallOptions)` (existing, `interpreter.hpp:119`). +- Produces: + - `edits.hpp`: `template struct CellEdit { RowId key; T value; };` and `template struct RowEdit { RowId key; Values values; };`, each with a `static std::pair schemaValue()` (Task 17a's `DeclaresSchemaValue`) returning `{"x-cellEditOf", name}` / `{"x-rowEditOf", name}`, `name` the `RecordInfo::name` in `model::recordRegistry()` whose `type` is `typeid(TableOf)`, and an in-class glaze meta, `struct glaze { static constexpr auto value = glz::object("key", &CellEdit::key, "value", &CellEdit::value); };` (`RowEdit`: `glz::object("key", &RowEdit::key, "values", &RowEdit::values)`). The meta names the class by its injected name and declares no alias: `CellEdit`'s second template parameter is `T`, and a nested `using T = …` would redeclare it, which is ill-formed. An application's action derives from one (`struct EditSpecimenCount : table::CellEdit<&SpecimensModel::specimens, std::int64_t> {};`) so each action is its own type, and the derived type finds the meta through its base. Glaze's pure reflection cannot read such a type: it counts members by aggregate initialisation, and `D{any}` initialises the whole base from one placeholder, so it counts 1 member and then binds 1 name to a type with 2 (`glaze/reflection/to_tuple.hpp`, `count_members`, at glaze 7.4, `MORPH_GLAZE_VERSION`). This is inferred from reading glaze's source; no compiler run checked it here, so Step 1's first test is the check (if pure reflection does handle the base, the test still passes and the meta is harmless). + - `forms.hpp`: `template void annotateSchemaRoot(glz::generic_u64& dom)` — when `DeclaresSchemaValue`, `dom[first] = second` at the schema **root**; called in `mergeSchemaExtras` beside `annotateSubmitMode(dom)` (`forms.hpp:3332`). Task 17a's `annotateSchemaMarker` writes a member's keyword on its property; an edit action is the marked type itself, so its keyword has no property to sit on. + - `TableInputKind` gains `CellEdit`; `tableInputsOf` also reads the root: `x-cellEditOf` or `x-rowEditOf` there yields `TableInput{.member = "key", .record = name, .kind = TableInputKind::CellEdit}`, the busy key being the body's `key`. `description.hpp`: `struct EditInfo { std::string action; std::string member; std::string readonly; bool operator==(EditInfo const&) const = default; };`, declared before `TableColumn`, whose `edit` member holds it — not in `edits.hpp`, which must include `description.hpp` (for `TableOf`, `TableDescription` and `recordRegistry`), so the other way round would be a cycle; `edits.hpp` re-exports it by that include, and this task corrects the header named in editing.md's "API surface" row. `edits.hpp` (which also includes `forms/engine/field_model.hpp`, for `forms::FormModel::fromSchema` and `forms::FieldKind`; `field_model.hpp` includes nothing of `table/` or `ui/`): `[[nodiscard]] std::expected checkEdits(TableDescription const& description, std::function(std::string_view action)> const& schemaOf);` — `SourceContract` when a column's kind does not fit its field's kind, or `member` is not a member of `values`; the fits are `Integer` ↔ {Integer, Slider, Enum, Choice}, `Key` ↔ {Integer, Choice}, `Decimal` ↔ {Decimal}, `Quantity` ↔ {Quantity}, `Measure` ↔ {Quantity}, `Number` ↔ {Number, Slider}, `Text` ↔ {Text, Multiline, Enum, Choice}, `Date` ↔ {Date, EpochDate}, `DateTime` ↔ {DateTime, EpochDateTime}, `Bool` ↔ {Boolean}, `Custom` ↔ {Text, Enum, Choice}. Task 2's describe path calls it with the dispatcher's action schemas. + - `edits.hpp`, `CellEdits` additions: `struct EditCell { std::string column; std::string json; std::string member; };` (`member`: the name the action's `FieldError` uses for this cell — `"value"` for a `CellEdit`, the `EditInfo::member` for a `RowEdit`; empty means the column id) `struct RowEditRequest { RowId row; std::vector cells; };` `using RowEditDone = std::function>)>;` `using RowEditCommit = std::function;` `explicit CellEdits(RowEditCommit commit);` (a model's table: no patcher, no engine); `void commitRow(RowEditRequest request);` (queued with the row's other edits, in order); `void setDraft(RowId const& row, std::string_view column, std::string text, std::optional error);` `[[nodiscard]] std::optional draft(RowId const&, std::string_view) const;` `void clearDraft(RowId const&, std::string_view);` `[[nodiscard]] bool modified(RowId const&, std::string_view) const;` (from a success until `rowFetched`); `void rowFetched(RowId const& row);` (ends the row's modified marks and its settled drafts; a stale cell is left as it is); `void rowAbsent(RowId const& row);` (a fetch that named the row returned none — it was deleted, or no longer matches: drops the row's drafts, errors, modified marks and its edits not yet sent; an edit in flight settles as it would and leaves nothing behind); `void moveRow(RowId const& from, RowId const& to);` (drafts, errors, modified marks and queued edits); `void keepColumns(std::span columns);` (drops drafts, errors and marks of every other column); `[[nodiscard]] std::size_t errorCount() const;` `[[nodiscard]] std::size_t modifiedCount() const;` `stale` and `error` see row commits too. **Where a refusal lands**, in `CellEdits`' settle of a row commit: a `FieldError` whose `column` equals a cell's `member` (or, with `member` empty, its `column`) is that cell's error; one that matches no cell of the request, or names nothing, is the error of every cell of the request; a cell of the request no error reached keeps its draft and takes no error. `TableColumn::edit` (`std::optional`). + - `grid.hpp`: `struct ModelColumn { std::string id; std::optional edit; std::shared_ptr model; std::string path; };` — for an editable column, `model` is `forms::FormModel::fromSchema(edit->action, )` (a `FormModel` is made only by `fromSchema`, `field_model.hpp:799`) and `path` the field in it, `"value"` for a `CellEdit` and `"values." + edit->member` for a `RowEdit`; both empty for a column with no edit. `enum class EditMode : std::uint8_t { Cell, Row };` `struct ModelGridContext { reactive::Runtime* runtime; forms::ChoiceFetcher choices; forms::FormSessionOptions session; FormatContext format; std::function may; };` `class ModelGridSource final : public GridSource` — `ModelGridSource(std::shared_ptr rows, table::CellEdits& edits, std::vector columns, EditMode mode, ModelGridContext context)`. A cell's field is the field `path` of a `forms::FormSession{*context.runtime, *model, , context.choices, context.session}` the source makes per column on first use and keeps (one session per editable column, loaded with the row's value when an editor opens); `editor(key, column)` is `scalarControl(session, session.field(path))`, a draft is encoded by that field (`FieldState::encoded()`, which is `forms::encodeScalar` with the session's `ValueContext`), `toggles` is that field's kind being `Boolean`, and `text(key, column)` is the draft while one is held, else `formatCell(cell, description column, context.format)`; `rowCount()` is `rows->total().rows`, `keyAt(i)` the key of `rows->row(i)`, empty while that row is not fetched (Task 19's walk stops there, leaving `place()` on the placeholder); read-only through `cellReadOnly` with `hasEdit = edit && context.may(edit->action)`, `companionReadOnly` from the `EditInfo::readonly` column's `true`, `busy` and `locked` from `refusesEdit(rows, index, description)` (busy is `rows.states().isBusy(key)`, locked is `lockText(row, description)`); `unloaded` from the row's cell. `view()` is the source's **forwarding decorator** over `rows` (index #40): a `TableRows` that forwards every member to `rows`, sets `rows`' one `onChange` slot itself, and on each change first calls `edits.rowFetched(key)` for every row the change inserts or updates, advances the source's signal, and then calls the handler the mount set on it. The lowering hands the mount this decorator (as `base.rows`), never `rows`; nothing subscribes to `rows` a second time; `keyOf(record)` reads the record's field named by the key of the description `setDescription` last gave it, as a `RowId` (that column is always fetched, Task 9d's `alwaysFetched`); `rowModified(key)` is true while `edits` holds a modified mark or a draft for any of the row's columns. `marks(key, column)` is `{.readOnly = readOnly(key, column), .modified = edits.modified(row, column), .error = edits.error(row, column).has_value(), .stale = edits.stale(row, column)}` with `row` the key as a `RowId`. `CellEdits` is not reactive, so the source holds a `reactive::Signal` it advances after each call it makes on `edits` and in each `RowEditDone`; `marks` and `rowModified` read it first, which makes them tracked reads, and the lowering mounts the table through `GridController::node(columns, options, base)` with `base` the `TableSource` it builds for any model table (Task 9d's `cellView`, `rowView`, `alwaysFetched`, `levels`) and `base.rows` the decorator above, so every column keeps its `cell` template, tone, tooltip and accent (a cell is `markedCell(base.cellView(c, row), marks)`, index #39) and a model's table draws its marks per cell from each cell's own row signal, as a form grid does. **The source's own edits are not busy runs**: the lowering's `RowEditCommit` sends through `ModelChannel::execute(action, body, {})` directly, not through a `MutationRuntime`, so no `RunObserver` sees it and nothing registers it in `RowStates`; a row with its own edits queued or in flight takes further edits (queued behind them by `CellEdits`) and shows them stale. A `CellEdit`/`RowEdit` run made by a document mutation of the session, or by `Table.*` on another table, does go through `MutationRuntime`, so `tableInputsOf` marks its row busy and the cell refuses. `void ModelGridSource::rowsAbsent(std::span keys)` calls `edits.rowAbsent` for each; the lowering wires it to `WindowRows::onRowsAbsent`. Cell mode: a commit sends `RowEditRequest{key, {{column, json, member}}}` (`member` as `EditCell` defines it); row mode: a row's cells are collected while focus stays in the row and sent as one request when focus leaves it or on `Ctrl+Enter`; a refusal sets each `FieldError` on its cell and, while the table has focus, moves focus to the first refused cell. A success whose `ChangedRows` does not name the row calls `rowFetched` at once. `void ModelGridSource::moveKey(Key const& from, Key const& to)` calls `rows.moveKey(from, to)` and `edits.moveRow(from, to)`; the lowering of an editable table calls it where Task 17c's lowering calls `TableRows::moveKey` for a `ChangedRow::from`. `void ModelGridSource::setDescription(table::TableDescription const&)` calls `keepColumns` with its column ids; the lowering calls it wherever it calls `WindowRows::setDescription`. A `FailedRow` for the row is a `FieldError` on each cell of the request. + - `table_rows.hpp`: `void WindowRows::onRowsAbsent(std::function)> handler)` — called once per keyed fetch reply with the keys that fetch named and the reply holds no row for (a change event's refetch of a deleted row, or of one that left the filter). A Part D type; this task adds the member and its test, and Part D's plan names it as G's. + - Status-line copy (through `ScreenCore::tableMessage`): an edit refused at a cell: unloaded `"This value is not loaded yet"`, busy `"This row is being saved"`, locked: the row's lock text. + - Document: `editMode` (`cell`, the default, or `row`) on a model's table; refused on any other table. + +- [ ] **Step 1: Write the failing table tests** — `tests/table/test_table_pending.cpp`: + +```cpp +namespace { +struct RowCommits { + std::vector sent; + std::vector done; + table::RowEditCommit commit() { return [this](auto const& r, auto d) { sent.push_back(r); done.push_back(std::move(d)); }; } +}; +table::RowId const k1{std::int64_t{1}}; +} + +// Mutation: rowFetched clearing a stale cell's draft. +TEST_CASE("cell edits: stale until the reply, modified until the next fetch", "[table][edits]") { + RowCommits c; + table::CellEdits edits{c.commit()}; + edits.setDraft(k1, "count", "9", std::nullopt); + edits.commitRow({k1, {{"count", "9"}}}); + CHECK(edits.stale(k1, "count")); + c.done.at(0)(std::expected>{}); + CHECK_FALSE(edits.stale(k1, "count")); + CHECK(edits.modified(k1, "count")); + CHECK(edits.draft(k1, "count") == "9"); + edits.rowFetched(k1); + CHECK_FALSE(edits.modified(k1, "count")); + CHECK_FALSE(edits.draft(k1, "count").has_value()); +} + +// Review Focus 4. Mutation: rowFetched ending stale edits too. +TEST_CASE("cell edits: a fetch before the reply keeps the cell stale", "[table][edits]") { + RowCommits c; + table::CellEdits edits{c.commit()}; + edits.setDraft(k1, "count", "9", std::nullopt); + edits.commitRow({k1, {{"count", "9"}}}); + edits.rowFetched(k1); // the change event's refetch, before the reply + CHECK(edits.stale(k1, "count")); + CHECK(edits.draft(k1, "count") == "9"); + c.done.at(0)(std::expected>{}); + CHECK(edits.modified(k1, "count")); + edits.rowFetched(k1); + CHECK_FALSE(edits.modified(k1, "count")); +} + +// Mutation: a row's second request started before the first settles. +TEST_CASE("cell edits: a row's edits run one at a time, a refusal lands on each cell", "[table][edits]") { + RowCommits c; + table::CellEdits edits{c.commit()}; + edits.commitRow({k1, {{"label", R"("a")"}, {"note", R"("b")"}}}); + edits.commitRow({k1, {{"note", R"("c")"}}}); + CHECK(c.sent.size() == 1); + c.done.at(0)(std::unexpected(std::vector{{"label", "taken"}, {"note", "too long"}})); + CHECK(edits.error(k1, "label") == "taken"); + CHECK(edits.error(k1, "note") == "too long"); + CHECK(c.sent.size() == 2); + CHECK(edits.errorCount() == 2); +} + +// Mutation: settle filing an error under FieldError::column as given (the error sits on a column "value" or +// "remarkText" that the table does not have, and the cells show none). +TEST_CASE("cell edits: a refusal lands on the cell whose member it names", "[table][edits]") { + RowCommits c; + table::CellEdits edits{c.commit()}; + edits.commitRow({k1, {{.column = "count", .json = "11", .member = "value"}}}); + c.done.at(0)(std::unexpected(std::vector{{"value", "must be at most 10"}})); + CHECK(edits.error(k1, "count") == "must be at most 10"); + CHECK_FALSE(edits.error(k1, "value").has_value()); + table::RowId const k2{std::int64_t{2}}; + edits.commitRow({k2, {{.column = "label", .json = R"("a")", .member = "label"}, + {.column = "remark", .json = R"("b")", .member = "remarkText"}}}); + c.done.at(1)(std::unexpected(std::vector{{"remarkText", "too long"}})); + CHECK(edits.error(k2, "remark") == "too long"); + CHECK_FALSE(edits.error(k2, "label").has_value()); // no error reached it + table::RowId const k3{std::int64_t{3}}; + edits.commitRow({k3, {{.column = "label", .json = R"("a")", .member = "label"}, + {.column = "remark", .json = R"("b")", .member = "remarkText"}}}); + c.done.at(2)(std::unexpected(std::vector{{"", "The row is closed"}})); + CHECK(edits.error(k3, "label") == "The row is closed"); // names no cell: every cell of the request + CHECK(edits.error(k3, "remark") == "The row is closed"); +} + +// Mutation: moveRow moving only drafts (the error stays on the old key). +TEST_CASE("cell edits: drafts are held by key and follow a key change", "[table][edits]") { + table::CellEdits edits{[](auto const&, auto) {}}; + edits.setDraft(table::RowId{std::int64_t{5}}, "count", "abc", "Not a number"); + CHECK(edits.errorCount() == 1); + edits.moveRow(table::RowId{std::int64_t{5}}, table::RowId{std::int64_t{9}}); + CHECK_FALSE(edits.draft(table::RowId{std::int64_t{5}}, "count").has_value()); + CHECK(edits.draft(table::RowId{std::int64_t{9}}, "count") == "abc"); + CHECK(edits.errorCount() == 1); +} + +// Review Focus 5. Mutation: keepColumns dropping drafts but not their errors. +TEST_CASE("cell edits: a new revision drops drafts of a removed column", "[table][edits]") { + table::CellEdits edits{[](auto const&, auto) {}}; + edits.setDraft(k1, "count", "abc", "Not a number"); + edits.setDraft(k1, "note", "kept", std::nullopt); + std::vector const kept{"label", "note"}; + edits.keepColumns(kept); + CHECK_FALSE(edits.draft(k1, "count").has_value()); + CHECK(edits.draft(k1, "note") == "kept"); + CHECK(edits.errorCount() == 0); +} + +// Mutation: rowAbsent ignored (the deleted row's draft and error stay, errorCount 1). +TEST_CASE("cell edits: a row absent from a refetch loses its drafts", "[table][edits]") { + RowCommits c; + table::CellEdits edits{c.commit()}; + edits.setDraft(k1, "count", "abc", "Not a number"); + edits.setDraft(table::RowId{std::int64_t{2}}, "count", "7", std::nullopt); + edits.rowAbsent(k1); + CHECK_FALSE(edits.draft(k1, "count").has_value()); + CHECK_FALSE(edits.error(k1, "count").has_value()); + CHECK(edits.errorCount() == 0); + CHECK(edits.draft(table::RowId{std::int64_t{2}}, "count") == "7"); // other rows untouched +} +``` + +`tests/test_ui_table_model.cpp`, the action types over a model the file registers (`struct EditRowsModel { std::vector rows; table::ServedTable specimens(table::TableContext const&); };`, `BRIDGE_REGISTER_MODEL(EditRowsModel, "T_EditRows")`, `BRIDGE_REGISTER_TABLE(EditRowsModel, "specimens", &EditRowsModel::specimens)`, so the record is `T_EditRows.specimens`): + +```cpp +using SpecimensModel = EditRowsModel; +struct EditSpecimenCount : table::CellEdit<&SpecimensModel::specimens, std::int64_t> {}; +struct SpecimenValues { std::optional label; std::optional remark; }; +struct EditSpecimenRow : table::RowEdit<&SpecimensModel::specimens, SpecimenValues> {}; + +// Mutation: annotateSchemaRoot left out of mergeSchemaExtras (no root keyword; tableInputsOf finds no input). +TEST_CASE("cell edits: an edit action reads, writes and names its table at the schema root", "[ui][table][edit]") { + static_assert(glz::reflect::size == 2); + EditSpecimenCount edit{}; + REQUIRE_FALSE(glz::read_json(edit, R"({"key":4,"value":9})")); + CHECK(edit.value == 9); + CHECK(glz::write_json(edit).value() == R"({"key":4,"value":9})"); + auto dom = glz::read_json(forms::schemaJson()).value(); + CHECK(glz::write_json(dom["x-cellEditOf"]).value() == R"("T_EditRows.specimens")"); + CHECK_FALSE(dom["properties"]["key"].contains("x-cellEditOf")); + auto const inputs = ui::tableInputsOf(forms::schemaJson()); + REQUIRE(inputs.size() == 1); + CHECK(inputs.at(0).member == "key"); + CHECK(inputs.at(0).record == "T_EditRows.specimens"); + CHECK(inputs.at(0).kind == ui::TableInputKind::CellEdit); +} + +// Mutation: onRowsAbsent called with every key the fetch named (row 2, which came back, is reported too). +TEST_CASE("table rows: a keyed refetch that returns no row reports it absent", "[ui][table][edit]") { + // Task 9's Harness over a WindowRows of rows 1..3; onRowsAbsent records its calls + // a change event naming keys 2 and 3; the keyed fetch's reply holds row 2 only + // CHECK the handler was called once with exactly {3} +} +``` + +`tests/table/test_table_description.cpp`: + +```cpp +// Mutation: checkEdits not comparing kinds. +TEST_CASE("description: an edit whose field does not fit its column is a source contract", "[table][description][edits]") { + // column "count" (Integer) with edit {action "Lims_EditSpecimenCount"} whose value schema is {"type":"string"}: + CHECK(table::checkEdits(description, schemaOf).error().code == table::TableErrorCode::SourceContract); + // column "label" (Text) with edit {action "Lims_EditSpecimenRow", member "nosuch"}: SourceContract, message names "nosuch" + // with value {"type":"integer"} and member "label" present: has_value() +} +``` + +- [ ] **Step 2: Write the failing UI tests** — `tests/test_ui_table_model.cpp`, over the fixture below, declared in `tests/grid_test_support.hpp` (`RowCommits` moves there from the table test, which includes the header): + +```cpp +// Rows of a model's table held by the test: a view of keys, some not fetched, with states, locks and unloaded cells. +class FakeRows final : public ui::TableRows { +public: + struct Row { table::RowId key; Value record; bool fetched = true; std::set unloaded; }; + std::vector view; // in view order + ui::RowStates rowStates; + std::vector> moved; // moveKey's calls + void deliver(std::size_t index); // marks the row fetched; reports it Updated + void reorder(std::vector keys); // the view in this order; reports the moves + void drop(table::RowId const& key); // out of the view; restore(row, index) puts it back + void restore(Row row, std::size_t index); + void refetch(table::RowId const& key, Value record); // replaces the record; reports it Updated + // TableRows: total() {view.size(), Exact, true}; row(i) empty while !fetched; unloadedLevels from `unloaded`; + // visible/keysOf/setSort/setFilter trivial; states() -> rowStates; moveKey records; onChange keeps ONE handler. +}; + +struct ModelGridFixture { + morph::test::formsengine::Harness h; + std::shared_ptr rows = std::make_shared(); + RowCommits commits; + table::CellEdits edits{commits.commit()}; + std::set> permitted{"Lims_EditSpecimenCount", "Lims_EditSpecimenRow"}; + std::unique_ptr source; + std::unique_ptr grid; + // `keys` rows with label, remark, count, countFrozen, note, lockedBy fields; the description names `key` as + // the key and `lockedBy` as rowLock; ModelGridContext{&h.rt, h.server.fetcher(), {}, FormatContext{}, may} + // with `may` reading `permitted`; the columns' models are fromSchema of the two schemas below. + explicit ModelGridFixture(std::vector keys, ui::EditMode mode = ui::EditMode::Cell); +}; +``` + +Columns: `label` and `remark` (Text, edit `Lims_EditSpecimenRow`, members `label` and `remarkText` — the second differs from its column id on purpose), `count` (Integer, edit `Lims_EditSpecimenCount`, readonly companion `countFrozen`), `note` (no edit). Each case declares `ModelGridFixture f{{…}}`; `f.rows->rowStates` is what the comments call `states()`. The schemas, also added to `TableHarness`'s catalog: `Lims_EditSpecimenCount` `{"type":"object","x-cellEditOf":"Lims_SampleModel.samples","properties":{"key":{"type":"integer"},"value":{"type":"integer","maximum":10}},"required":["key","value"]}`, `Lims_EditSpecimenRow` `{"type":"object","x-rowEditOf":"Lims_SampleModel.samples","properties":{"key":{"type":"integer"},"values":{"type":"object","properties":{"label":{"type":["string","null"]},"remarkText":{"type":["string","null"]}}}},"required":["key"]}`, each with `effects` `updatesTable` of `Lims_SampleModel.samples` and that record in `records`. + +```cpp +// Mutation: the busy test left out of ModelGridSource::readOnly (row 3 takes the edit). +TEST_CASE("model table: read-only is one rule", "[ui][table][edit]") { + // rows 1..5; row 2 count unloaded; row 3 busy (states().busyKeys(7, {3}): another action's run); row 4's rowLock + // cell "Being edited by another user"; + // row 5 countFrozen true + for (std::int64_t key : {2, 3, 4, 5}) CHECK(f.source->readOnly(ui::Key{key}, "count")); + CHECK(f.source->readOnly(ui::Key{std::int64_t{1}}, "note")); // no edit action + f.grid->focusCell(at(2, "count")); // arrows and clicks reach read-only cells + f.grid->type("7"); + CHECK(f.grid->message() == "This value is not loaded yet"); + f.grid->focusCell(at(3, "count")); f.grid->type("7"); + CHECK(f.grid->message() == "This row is being saved"); + f.grid->focusCell(at(4, "count")); f.grid->type("7"); + CHECK(f.grid->message() == "Being edited by another user"); + CHECK(f.commits.sent.empty()); + f.grid->focusCell(at(1, "count")); f.grid->type("3"); f.grid->press("Enter"); + CHECK(f.commits.sent.size() == 1); + CHECK(f.grid->focus() == at(1, "count")); // Enter down passes rows 2–5, all read-only in count: it stays + f.permitted = {"Lims_EditSpecimenRow"}; // count's action refused + CHECK(f.source->readOnly(ui::Key{std::int64_t{1}}, "count")); +} + +// Mutation: the commit sent through MutationRuntime (its RunObserver marks row 1 busy and the second cell refuses). +TEST_CASE("model table: the table's own edits do not make its row busy", "[ui][table][edit]") { + // rows 1..2, all editable; EditMode::Cell + // focus (1, label), type "a", Enter: one request in flight; CHECK_FALSE f.rows.states().isBusy(1) + // focus (1, remark), type "b", Enter: CHECK f.grid->message() is empty, f.commits.sent.size() == 1 (queued), + // and the (1, remark) cell is stale + // settle the first: CHECK f.commits.sent.size() == 2 + // another action's run on row 2 (f.rows.states().busyKeys(7, {2})): type on (2, label): message + // "This row is being saved", nothing sent +} + +// Mutation: the walk passing over a row not fetched yet as if it were read-only (focus lands on row 5). +TEST_CASE("model table: the walk stops at a row not fetched yet", "[ui][table][edit]") { + // ModelGridFixture f{{1, 2, 3, 4, 5}}; f.rows->view[2].fetched = false; all editable + // focus (2, count), type "1", Enter: + // CHECK_FALSE(f.grid->focus().has_value()); + // CHECK(f.grid->place() == ui::GridFocus{std::nullopt, 2, "count"}); + // CHECK_FALSE(f.source->keyAt(2).has_value()); f.commits.sent.size() == 1 (row 2 only) + // Enter again before the row arrives: Handled, place() unchanged + // f.rows->deliver(2): CHECK(f.grid->focus() == at(3, "count")) and place() == GridFocus{Key{3}, 2, "count"} + // type "2", Enter: CHECK f.commits.sent.back().row == RowId{3} +} +``` + +Interpreter-level, same file, through `ui::testing::TableHarness` (index #42: a whole document with a `models` block and an alias over `Table.samples`; `Lims_EditSpecimenCount` and `Lims_EditSpecimenRow` in its catalog as above and in its permitted actions unless a case removes one), `replyDescribe`, `replyPage`, `statusOf`, `elementValue`, `cellText`, `cellAccent` and `cellMarks(h, key, column)` (index #42's helper; this task adds none of its own) — so the lowering is tested on Windows, where `morph_net_tests` does not build: + +```cpp +// Mutation: the lowering leaving a column with `edit` read-only (no request is sent). +TEST_CASE("model table: an editable column lowers to a cell edit", "[ui][table][edit][interpreter]") { + // a description whose `count` column has edit {action "Lims_EditSpecimenCount"}; a page of rows 1..3 + // the node gives `count` a `cell` template (a text with testId "count_") and a `tone` expression + // h.backend.clickCell(table, 0, , true); edit the editor to "4"; press Enter + // CHECK the template drew before the edit (h.text("count_1")) and cellAccent(h, 1, "count").tone is the + // expression's: an editable column keeps the lowering's cell view (second mutation: node() replacing + // base.cellView with a plain text cell) + // CHECK the channel received execute("Lims_EditSpecimenCount", {"key":1,"value":4}) and no MutationRuntime run + // started (statusOf(h).standing is empty: nothing "Saving") + // reply {"rows":{"rows":[{"key":1}]}} and a change event naming 1; replyPage with count 4 for row 1: + // before the page: CHECK cellMarks(h, 1, "count") == "m" (drawn by the cell's view); after it: + // CHECK cellText(h, 1, "count") == "4" and cellMarks(h, 1, "count") == "" +} +// Mutation: the lowering ignoring the catalog's permitted set (the refused principal's cell opens an editor). +TEST_CASE("model table: a column whose action is not permitted is read-only", "[ui][table][edit][interpreter]") { + // tableCatalog without Lims_EditSpecimenCount permitted: a double click on (1, count) opens no editor; + // typing "4" posts "This cell is read-only" (statusOf(h).message) +} +// Mutation: the loader accepting editMode on a `rows` table. +TEST_CASE("model table: editMode is refused on a table that is not a model's", "[ui][table][edit][interpreter]") { + // {"kind":"table","rows":{"ref":"items"},"editMode":"row"}: loadDocumentText fails, the message names editMode; + // {"kind":"table","model":"m","table":"specimens","editMode":"sideways"}: fails, naming the value; + // {"kind":"table","model":"m","table":"specimens","editMode":"row"}: loads, and a Tab from (1, label) to + // (1, remark) after typing sends nothing until focus leaves row 1 +} + +// Mutation: the walk following the edited row instead of the view position at the commit. +TEST_CASE("model table: Enter after an edit that moves its row lands on the row that was below", "[ui][table][edit]") { + // view [1, 2, 3], all editable; focus (1, count), type "9", Enter; f.rows->reorder({2, 3, 1}) + CHECK(f.grid->focus() == at(2, "count")); +} + +// Mutation: ModelGridSource setting rows->onChange itself beside the mount (whichever is set second wins: either +// the mounted row keeps the old text, or the modified mark never clears). +TEST_CASE("model table: the mount and the drafts share the rows' one change slot", "[ui][table][edit]") { + // ModelGridFixture f{{1, 2}}; mounted through f.grid->node(columns, {}, base) with base.rows = &f.source->view() + // focus (1, count), type "9", Enter; settle the request ok: the row of key 1 records marks: == "m" + // f.rows->refetch(1, ): CHECK the mounted cell's text is "9" (the mount's handler ran) and + // marks: == "" (rowFetched ran) +} + +// Mutation: drafts held by the window (FakeRows dropping row 5 loses them). +TEST_CASE("model table: cells of a model's table", "[ui][table][edit]") { + // cell mode: focus (1, count), type "9", Enter -> one RowEditRequest{1, {{"count","9"}}}; marks stale; + // reply ok with ChangedRows naming 1 -> marks modified; FakeRows refetches 1 -> not modified + // refusal: type "9" on (2, count) -> the request's cell is {"count", "9", "value"}; reply + // FieldError{"value","Row 2 is closed"} -> error "Row 2 is closed" on (2, count), draft "9" kept; + // type "11" on (3, count): the field's own maximum refuses it ("above-maximum"), nothing is sent + // scroll: type "abc" on (5, count) -> errorCount 1; FakeRows drops then restores row 5 -> draft "abc", error kept + // from: f.source->moveKey(5, 9) -> draft and error on (9, count); FakeRows recorded moveKey(5, 9) + // row mode: EditMode::Row; type "a" on (1, label), Tab, type "b" on (1, remark), Enter -> nothing sent; + // focusCell (2, label) -> one RowEditRequest{1, {{"label", "\"a\"", "label"}, + // {"remark", "\"b\"", "remarkText"}}}; + // a refusal FieldError{"remarkText", "too long"} -> error on (1, remark), none on (1, label), and + // focus back on (1, remark); + // on row 2, type "c" on (2, label) and press Ctrl+Enter -> one request for row 2 with focus still there +} +``` + +`tests/net/test_push_tables.cpp`, over Task 2's fixture with a model registering table `specimens`, `Lims_EditSpecimenCount : table::CellEdit<&SpecimensModel::specimens, std::int64_t>` declaring `effects::updatesTable<&SpecimensModel::specimens>` and returning `ChangedRows`: + +```cpp +// Mutation: the client sending {"key":…, "value":…} under the wrong action id (the model never sees it). +TEST_CASE("push tables: a cell edit reaches the model and the change event refetches the row", "[net][tables][edit]") { + // client commits count = 4 on row 1: the server model's row 1 count == 4; the other client's window refetches + // row 1; the editing client's cell is not modified after its refetch; the action's schema carries + // "x-cellEditOf":".specimens" +} +// Mutation: the server's catalog listing every action as permitted (the viewer's column stays editable). +TEST_CASE("push tables: a principal refused the edit action sees the column read-only", "[net][tables][edit]") { + // the authoriser refuses Lims_EditSpecimenCount for principal "viewer": the catalog's permitted set lacks it, and + // the lowered count column is read-only for that client +} +``` + +Write each commented case out in Catch2 with the fixture's calls; the comments are the assertions and their order. + +- [ ] **Step 3: Run to see them fail** — `cmake --build --preset cl-debug --target morph_table_tests`; expected: `table::RowEditRequest` not declared. + +- [ ] **Step 4: Implement** `EditInfo` and `TableColumn::edit` in `description.hpp`; `CellEdit`, `RowEdit`, `checkEdits` (called from Task 2's describe path) and the `CellEdits` additions in `edits.hpp`; busy rows from `x-cellEditOf`/`x-rowEditOf` inputs (the lowering's `RunObserver::started` reads `TableInputKind::CellEdit` as `busyKeys(run, {body.key})`); `ModelGridSource` with its decorator and per-column edit sessions; the lowering of editable model columns (each `ModelColumn::model` from the catalog's schema, the request's `member` from the column's `EditInfo`, the table mounted through `node(columns, options, base)`), `editMode` and its refusal. + +- [ ] **Step 5: Run** + +Run: `cmake --build --preset cl-debug --target morph_table_tests morph_tests && ctest --test-dir build/cl-debug -R "cell edits|description|model table|pending|table rows" --output-on-failure`, and on `linux-everything` (where `morph_net_tests` builds) `ctest --test-dir build/linux-everything -R "push tables" --output-on-failure` +Expected: all pass, including every existing case in `test_table_pending.cpp`, `test_table_reentrancy.cpp` and `test_table_selection.cpp`. + +- [ ] **Step 6: Mutate**, **Step 7: Docs** (docs build), **Step 8: Commit** `feat(table): edit cells of a model's table`. + +--- + +## Decisions where the spec leaves a choice + +Each is what this plan implements. The first, second, fourth and sixth are already stated in editing.md and table.md, so no task edits the spec for them; the task that lands each of the others states it in the spec it updates. + +- **A row busy with its own cell edits still takes edits.** editing.md queues edits to one row in order and refuses an edit in a busy row; a second cell of a row could never be entered while the first is saving if the table's own edits made the row busy. The table's own edits are therefore not busy runs, as editing.md ("A table's own edits make no row busy") and table.md ("Rows at work, rows that failed") state: they are sent through `ModelChannel::execute` directly, never registered in `RowStates`, and shown stale instead; a row busy with any other run (a document mutation, another table's action) refuses the edit (Task 24). +- **A row-mode refusal brings focus back.** editing.md commits a row when focus leaves it, so focus has left by the time a refusal arrives; it is moved back to the first refused cell while the table has focus, as editing.md ("A row at once") states (Task 24). +- **Computed and derived cells draw no modified mark.** editing.md line 300 marks any cell whose value differs from the loaded one; its test row (521) wants typing to mark "that cell and its row, not its neighbours", while a derive reply changes the neighbouring computed cells of that row. `FormSession::modified` is false for `x-computed` and `x-derived` members only; a cell the user typed in and a rule then froze stays modified (Task 19). +- **A deletion offers Undo; it does not ask first.** Rows are deleted at once and the status line says `"Deleted {n} rows"` with the entry "Undo", as editing.md ("Rows of a grid") states (Task 21). +- **Status-line copy the spec does not fix** is pinned in Tasks 19, 20, 21 and 24 (`"This cell is read-only"`, the standing `"Derived values could not be recalculated"` with the entry "Recalculate", the paste and row messages, the refusal messages). A failed derive round is a standing state, beside the ones index decision 19 lists, since it lasts until a round succeeds. +- **Busy rows from a `CellEdit` input** are listed in the roadmap's Task 17c, which lands before `CellEdit` exists; Task 24 adds `TableInputKind::CellEdit` (`x-cellEditOf`, `x-rowEditOf`) to Task 17a's `tableInputsOf`. `refusesEdit` stays as Part F defines it; the table's own edits never reach `RowStates`, so no exemption is needed on top of it. +- **A row absent from a refetch loses its drafts.** editing.md keeps a draft by key while its row scrolls away; a keyed fetch that names the row and returns none means the row was deleted or left the filter, and its drafts are dropped (`CellEdits::rowAbsent`, fed by `WindowRows::onRowsAbsent`, Task 24). +- **The editor's text is the cell's draft.** editing.md's `Escape` "restores the draft the cell had when it opened" (line 269) and its submit "first commits an open cell editor" (line 175) are both met with the draft written live: a commit closes the editor and is the one moment a change is meant (`committed()`, the derive round), so the form's submit runs the grids' commits first through `FormSession`'s before-submit hooks (Task 19). +- **A column group stays the group line, not a band.** editing.md says a group draws as a band of one level; the + group line carries the group's filter button, which a band cannot, so a group draws as a one-level heading on its + own line below the bands, over its columns while they stand together. editing.md ("Header bands") and table.md + ("Column groups") say so (Task 22). +- **Summary rows are rows of a decorator, not of the data.** editing.md puts them "outside the order, the filter and the selection" (line 414) and gives them no place in the pipeline. `SummaryRows` wraps the data rows for the mount alone; counts, key ranges, the walk, paste and the `rows` scope read the data rows (Task 22). +- **A refusal that names no cell marks every cell of its request**, and one cell's name is its `EditCell::member` (Task 24); editing.md only says a `FieldError` naming `value` settles the cell. +- **`EditInfo` is declared in `description.hpp`**, which `edits.hpp` includes; editing.md's API surface lists it under `edits.hpp`, which would make the two headers include each other. Task 24 corrects that row. +- **`CellEdits` cases live in `tests/table/test_table_pending.cpp`**, beside that class's existing cases, in addition to the roadmap's `tests/test_ui_table_model.cpp` and `tests/net/test_push_tables.cpp`. `tests/forms/` is a new directory whose files join `morph_tests`. + +## Self-review notes + +- **Coverage.** Every editing.md Tests row has a test: "A grid is a form", "Read-only is one rule (grid)", "The walk" (grid), "A sorted grid keeps its record", "Submission", "What changed" — Task 19; "Derived values", "The server decides", "Kind per row", "Choices per row" — Task 20; "Cell selection", "Paste, fill, clear", "Rows of a grid" — Task 21; "Bands", "Spans", "Summary rows" — Task 22; "Fixed grids" — Task 23; "Cells of a model's table", "Read-only is one rule (model table)", "The walk" (model table) — Task 24. Invariants: 1 (Task 19, the grid writes only through `FieldState`), 2 (Task 20 "derived values": a typed member survives the reply), 3 (Task 20: an older reply ignored, values land by row key), 4 (`cellReadOnly`, Tasks 19 and 24), 5 (Task 19 "a sorted grid keeps its record"), 6 (Task 24 "read-only is one rule"), 7 (Task 21 "paste, fill, clear"), 8 (Task 22 "spans"), 9 (Task 20 "the server decides"). Every Failure modes row has its refusal or its test in the task that lands the key. +- **Review findings applied.** The summary flag is `TableRowLook::summary` (index #39); summary rows reach the mount through `SummaryRows`, and `group` on a form grid through `FormRowsSource::setGroup` (Task 22); a placeholder focus is `GridController::place()` / `GridFocus` (Tasks 19, 24); `ModelGridSource` builds its edit sessions from the action's schema and a `ModelGridContext`, and shares the rows' one change slot through a forwarding decorator (index #40, Task 24); the `CellEdit` meta declares no alias; `scalarControl` takes the session; `GridSource` gives the editor and `toggles`, and `node()` takes the columns and a base `TableSource`; the editor's text is the live draft and submit runs before-submit hooks; `makeFormGrid` returns the grid's objects; `EditInfo` is `description.hpp`'s; a refusal lands by `EditCell::member`; the fixed and model grid fixtures are declared; a span across columns records `:x`; every `column` argument is a `Table::columns` index (index #37) and a rectangle's are positions; document tests use `TableHarness` (index #42). +- **Not covered by a test of its own:** the accessible band name is asserted only at function level (`bandedHeaderName`); the Qt Quick backend's live region and its reading order are left to `qt_quick/backend.md`'s existing conformance. diff --git a/docs/superpowers/plans/2026-11-17-one-table.md b/docs/superpowers/plans/2026-11-17-one-table.md new file mode 100644 index 000000000..517de2b9f --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-one-table.md @@ -0,0 +1,441 @@ +# The One Table, and Editing in It — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build the table of `docs/spec/table/table.md`, a table as a run-time description any model offers, one pipeline for every surface, slow columns and their caches, configuration, persisted state and acting on rows, and the editing of `docs/spec/table/editing.md`, grids of forms, cells of a model's table and the layouts entry grids need. Along the way, remove paging in a database. + +**Architecture:** The table engine (`include/morph/table`) gains the description, unloaded cells, levels, the level and view caches, column groups, values with units and row selections; the UI layer (`include/morph/ui`) gains `TableRows` with its two implementations, cell formatting, the column window, the configuration menus, persisted state and grids; the forms engine gains derived values and per-cell snapshots. Every task follows the spec's **Delivery order** (table.md steps 0 to 9c, then editing.md steps 1 to 6), and each lands with the tests and mutations the spec's **Tests** tables name. + +**Tech Stack:** C++23, CMake (Ninja, MSVC preset `cl-debug`), header-only morph, glaze, Catch2, Qt 6 Quick (offscreen test executables only), the terminal backend, Qt WebAssembly (single-threaded) for the browser gates. + +**Spec:** `docs/spec/table/table.md` and `docs/spec/table/editing.md`. Each task quotes the section it implements; the executor reads that section before writing a line. Where this plan and the spec differ, the spec wins and the plan is corrected. + +## Global Constraints + +- AGENTS.md "Comments and documentation": a comment or spec states what the code does now and why; no history, no issue numbers, no commit hashes. +- Every public symbol has complete Doxygen `@param`/`@tparam`/`@return`; the docs build runs `WARN_AS_ERROR = FAIL_ON_WARNINGS` (`cmake -S . -B build/doc -G Ninja -DMORPH_BUILD_DOCUMENTATION=ON -DMORPH_BUILD_TESTS=OFF -DMORPH_BUILD_EXAMPLES=OFF && cmake --build build/doc --target doc`). +- morph is public: no company, product or customer names in code, tests, specs or commit messages; examples use the neutral `lims` domain. +- Commits are authored `yaraslau ` and end with the session's attribution lines. +- No GUI application is launched by hand or by an agent; Qt Quick behaviour is tested through `morph_qt_quick_tests` (offscreen). +- AGENTS.md "Verify rather than assert": every test names the mutation it was seen to fail on, and the task runs that mutation once and records the failing output in its commit message body. +- Limits are the spec's, verbatim: `Virtualization{threshold = 2000, overscan = 10, columnThreshold = 40, cellThreshold = 20'000, columnOverscan = 4, realizePerFrame = 240}`; `QueryLimits::maxColumns = 512`, `maxKeys = 1000`, `maxSetValues = 10'000`, `maxQuerySetValues = 20'000`, `maxQuerySetBytes = 1 MiB`, `maxGroupColumns = 16`, `maxSortKeys = 8` (up to 32 by `limits`), `maxSelectedRows = 1'000'000`, `maxRetained = 10'000`; `SessionOptions::maxRangeRows = 10'000`, `maxCopyRows = 10'000`, `maxPasteCells = 10'000`, `tableStateTimeout = 300 ms`, `tableStateDebounce = 500 ms`, `retainHold = 2 s`; `TableStateOptions::segmentBytes = 12 KiB`; `PageWindow(pageSize = 200, maxPages = 8, maxKeys = 1000, maxColumns = 96)`; a form's `deriveDebounce` default 150 ms. +- A spec that describes code (the "Neighbouring specs" tables of both documents) takes its part in the task whose step its row names, and says nothing of it before. + +## The standard task loop + +Every task below runs this loop; a task lists only what is specific to it. + +1. Read the spec sections the task names, and its rows of the spec's **Tests** table. +2. Write the task's tests (names and assertions as the task gives them, the spec's values in them). Build the test target and run the new cases: they fail, or do not compile, for the reason the task says. +3. Implement the interfaces the task lists, in the files it lists. +4. Run the new cases and the whole target they live in: all pass. +5. Apply each named mutation by hand, run its test, see it fail, revert. Paste the failing line into the commit body. +6. Update the neighbouring specs the task names. Run the docs build when the task adds a public symbol. +7. Commit. + +Commands, with `` and `` from the task: + +```bash +cmake --preset cl-debug # once per tree +cmake --build --preset cl-debug --target +ctest --test-dir build/cl-debug -R "" --output-on-failure +``` + +## The detailed parts + +This document is the index. Each task is planned in full — signatures, test cases with their values, commands — in one of seven parts, which keep this document's task numbers: + +| Part | Tasks | File | +|---|---|---| +| A | 0, 0a, 1, 2 | `2026-11-17-one-table-a-foundation.md` | +| B | 3–7 | `2026-11-17-one-table-b-slow-columns.md` | +| C | 8a–8d | `2026-11-17-one-table-c-engine-config.md` | +| D | 9–11 | `2026-11-17-one-table-d-screen.md` | +| E | 12–14, 16 | `2026-11-17-one-table-e-configure.md` | +| F | 15, 17a–17d | `2026-11-17-one-table-f-display-and-acting.md` | +| G | 19–24 | `2026-11-17-one-table-g-editing.md` | + +## Cross-part decisions + +Where the parts, this index and the spec named one thing differently, this is the name every part uses. A part that disagrees with a line here is wrong. + +1. **Server options.** The code's `ServerConfig` (`core/remote.hpp`), as the spec names it: `ServerConfig::tableWork` (Task 2), `ServerConfig::views` (Task 6). +2. **`TableQuery::columns` and `QueryLimits::maxColumns` land in Task 1**, as Delivery step 1 says. Task 4 adds `TableQuery::keys`, `maxKeys` and the keyed reply only. +3. **`Page::{unloadedRows, undecided, awaiting, failed}` and `UnloadedRow` land in Task 3b**; Task 4 adds their generic-page members and `indices`. +4. **`effects::IChangeObserver`, `effects::AnnounceSink`, `table::changeKeys`, `table::rowIdOf` land in Task 5** (the level cache is an observer); Task 6 adds `announce` and `attach`. +5. **The answer path** is `table::detail::answerQuery(ServedTable const&, TableQuery const&, AnswerContext const& context = {})` in `description.hpp`. Task 2 defines it with an empty `struct AnswerContext {}`; Task 6 adds `ViewCache* views`. +6. **Where table work runs.** `table::TableRuntime{exec::IExecutor* work = nullptr;}`, `table::currentTableRuntime() -> TableRuntime const*` and the RAII `table::TableRuntimeScope`, installed by `RemoteServer` around a dispatch, are Task 2's (no `exec::detail::tlsTableWork`). Task 6 adds `ViewCache* views` to it; `QueryTable::invoke` builds `AnswerContext` from it; Task 17a's `resolve` uses it. +7. **The column layout's value** is Task 8d's `table::ColumnLayoutValue{order, hidden, pinned, widths, groups, units}`. +8. **`PageWindow`'s accessors** are Task 7's: `key(i)`, `cell(i, column)`, `holds(i, column)`, `revision()`. `WindowRows` reads through them. +9. **The cell formatter** is `ui::formatCell(table::Cell const&, table::TableColumn const&, ui::FormatContext const&, DisplayUnits const& = {}) -> std::string` (Task 15). There is no `Locale` type; `ui::FormatContext` (`ui/expression.hpp`) carries numbers, date patterns and zone. Until Task 15, Task 9's stand-in is `ui::detail::standInCellText(table::Cell const&, table::TableColumn const&)`. +10. **Row states** are Task 17c's `ui::RowStates` reached by `TableRows::states()`, with `isBusy(key)`, `failure(key)`, `busyCount()`, and `TableRows::moveKey(from, to)`; locks through `ui::lockText(row, description)` and `ui::refusesEdit(rows, index, description)`. Task 24 uses these and declares no `busy`, `lockedBy` or `onKeyMoved`. +11. **The status line** is Task 9d's (`TableStatus{counts, state, retry, message, shown}`, `TableWidget::setStatus`, `setOnRetry`, `Table::status`), and so is its message channel `ScreenCore::tableMessage(ElementState&, std::string)` with its 6 s hold (`kStatusMessageHold`) and the `status: false` routing to notifications. Task 12 and later tasks post through it; Task 17a adds the overload taking entries. +12. **Copy** goes through `IViewBackend::copyText(std::string_view)`, as the spec names it, Task 12b. +13. **Range selection in server mode** (`maxRangeRows`, the view-row report) is Task 10a's; Task 12f tests copy over it at its bound. +14. **`ui::TableColumn::id`, `TableArrangement`, a column part's `kind`, the `status` and `persist` keys** are Task 9's and 11b's, not Task 12's. +15. **"One order on every surface"** is tested for `rows` and model-backed tables in Task 11b; Task 13 extends the same test with a collection. +16. **Review Focus 1** is tested at Task 9 with what exists then (sort, filter, fetched columns); Task 17a extends it to a view selection and Task 24 to a cell draft. +17. **Order inside Task 8:** 8a → 8b → 8d (8b moves `ColumnGroupInfo` into `data_source.hpp`, which 8d's `ColumnLayout` uses); 8c needs Tasks 1, 2 and 5 and may land after 8b in either order with 8d. +18. **Build configurations.** Unit and interpreter tests are in `morph_tests`; Qt Quick and TUI tests need `cmake --preset cl-qt-debug -DMORPH_BUILD_QT_QUICK=ON -DMORPH_BUILD_TUI=ON`; `morph_net_tests` is POSIX-only and runs on `linux-everything`. +19. **Status-line entries and standing states.** Task 17a adds `ui::StatusEntry{std::string id; std::string label;}` (equality by value; handlers are held by the lowering, keyed by `id`) and `TableStatus::entries`, in `view.hpp` beside Task 9's `TableStatus`. Standing states — rows saving, rows that failed, retained rows that no longer match — are a persistent part of `TableStatus` derived from `RowStates::busyCount()`, `failedKeys()` and `counts().retained`, not posted through `tableMessage`, which carries transient refusals only; `tableMessage` has an overload taking entries. A grid adds one standing state of its own (Task 20): a failed derive round, "Derived values could not be recalculated" with the entry "Recalculate"; "Undo" after a deletion is a transient message with an entry. +20. **Test helpers** for table screens live in `tests/ui_table_support.hpp`. The first task that needs a helper adds it; every later task reuses it by its name and adds no second helper for the same thing. Task 9d adds `TableHarness` (decision 42), `tableCatalog`, `addAction` (a test's own catalog actions, consulted before `tableCatalog`), `replyDescribe`, `replyPage`, `lastQuery`, `statusOf`, `elementValue`; Task 12 the menu and column drivers (`menuOf`, `chooseMenu`, `clickFilter`, `clickGroupFilter`, `moveColumn`, `resizeColumn`, `pressCopy`, `clipboardText`; `clickHeader` is the existing `RecordingBackend` driver); Task 13 `rowKeys`; Task 15 `value`, `cellText`, `cellAccent`, `columnOf`; Task 17a `fireEvent`, `runMutation`, `settleMutation`, `refuseMutation`, `rowMarks`, `selectAll`, `rightClickCell`, `clickRow`, `ctrlClickRow`, `reportsOf`, `chooseStatusEntry`; Task 24 `cellMarks`. +21. **`EngineRows`** is constructed as Task 9 declares it (`EngineRows(std::shared_ptr, RecordOf, table::EngineOptions)`); grids build it over a `std::shared_ptr` to their source. +22. **Measures outside the engine.** `ValueRowsSource` reads a `{num, den, unit}` object as a `Measure` (Task 11a). A stored display unit that names a unit the registry no longer has is dropped when the layout is applied to a description (Task 12c, which has the registry; `ColumnLayout` has none). +23. **Calling a table function.** Table functions are non-const, as the spec declares them. Task 2 provides the one way to get a table's `ServedTable` from its model: `table::detail::serve(Model& model, TableContext const& context) -> ServedTable`, which handles both a plain function and a `typed` registration. `QueryTable::invoke`, `DescribeTable::invoke` and Task 17a's `resolve` all call it, on the strand; `resolve` takes `Model&`, as the spec declares it. +24. **Run ids** used for busy rows and held refetches are session-wide (one counter per `Session`), not per `MutationRuntime`. +25. **`TableQuery::retry`** (`bool retry = false`) lands in Task 4, with its wire round-trip; Task 5 passes it to every want it causes, order and display. +26. **A user-formed column group** (a layout group, not a declared one) has no values list: its menu offers conditions and the match line only, since `DistinctRequest::group` names a declared group. +27. **The clipboard driver** is `RecordingBackend::clipboardText()` (the last text copied), added by Task 12b. +28. **Cells are a mount concept from Task 9d.** `TableSource` gives a per-cell view (`cellView(column, rowSignal) -> Node`) and a row-level view, and names its always-fetched columns; a pooled cell (Task 10a) owns its scope and a row signal and is rebound by setting it. `RecordOf` returns an owning row record, memoised by `EngineRows`. `cellView`'s `column` is an index into `Table::columns`; the row-level view is `rowView(row) -> TableRowLook` (tone, label, spans, heading, `modified`, and a summary row's flag), and anything that varies per cell — accents, marks (modified, invalid, error) — is drawn by its cell view (Task 19's `MarkedCell{content, marks}` through `setCellMarks(row, column, marks)`), never carried on the row view. Task 9d defines `MountStats{cellBinds, rowBinds, cellsCreated, cellsRebound}`. +29. **A cell's load state** (`Loaded`, `Unloaded`, `Failed`, from `TableRows::unloadedLevels`) reaches the mount and both backends in Task 9d/10b: a fixed-width placeholder for unloaded, an error mark for failed. +30. **A window's fetches are read as text.** A `Value` holds no JSON number with a fraction or an exponent (`ui::valueFromJson` refuses them), so `Session::read` (Task 7b) resolves with the reply's JSON text: `async::Completion Session::read(std::shared_ptr const&, std::string const& actionId, Value const& body, ::core::async::StopToken stop = {})`. `WindowRows` (Task 9a) sends every page, keyed and typed fetch through it and decodes with `table::readGenericPage(text, *description())` (or Task 11c's `readTypedPage`); `readGenericPage` with no registry resolves units through `registryOf(description)` (Task 8c). The spec states the same signature and its reason. A page that reaches the client through the query cache (a document query of `Table.`) is decision 46's. +31. **`table::UnitInfo` and `ui::UnitInfo`.** `ui::UnitInfo` already exists (`include/morph/ui/expression.hpp`, for `x-unitAlternatives`); code in `morph::ui` names the table's type `table::UnitInfo`, always qualified. `UnitInfo`, `Measure` and `TypedMeasure` declare `operator== = default` (Task 8c). `writeGenericPage` returns a plain `GenericPage` (Task 1); a non-null registry for a `Measure` column is its precondition, and `detail::answerQuery` refuses with `SourceContract` before calling it. +32. **Persisted state's store seams.** Task 9c's `TableStates` has `ITableStateStore& store() const` and `void keep(TableStateKey const&, StoredTableState)` (Task 14b saves through the first and records a successful save with the second). `MemoryTableStateStore(exec::IExecutor&, Sharing = Sharing::Private)` (Task 14a adds the defaulted parameter). `ITableStateStore` has `publish` and the sentinel `kNoDocument` ("expect nothing stored"), which table.md already declares; Task 14a implements them. +33. **A user-formed group's filter on the wire** is a `GroupFilter` with `group` empty and `columns` set to the group's columns (Task 8b's `compileGroup` takes exactly one of the two). Task 9b's `fitState` and Task 12d's lowering find it by matching `columns`; removing the group removes its filter. +34. **Typed list actions** (`model` + `action`, table.md step 4's second half) are Task 11c, after 11a's kind inference: `readTypedPage`, `WindowRowsOptions::{action, queryMember}`. +35. **Rows a refetch did not return.** `WindowRows::onRowsAbsent(std::function)>)` is added by Task 24 (Part G); `ModelGridSource` drops those rows' drafts through `CellEdits::rowAbsent`. +36. **Edit actions name their table at the schema root.** Task 24 adds `forms::annotateSchemaRoot` (called in `mergeSchemaExtras`) and extends Task 17a's `tableInputsOf` to read `x-cellEditOf` and `x-rowEditOf` from the schema root, beside the top-level properties it already reads. + +37. **A column index** — the `column` argument of every `Table` handler, `TableWidget` call (`setCellLoad`, `setCellMarks`, `setCellAccent`, …), `TableSource::cellView` and `RecordingBackend` driver — is the index into `Table::columns`, which holds every column, hidden ones included, and is stable across layout changes. Only a `position` argument is a visible place. +38. **Equality.** Every struct that a defaulted `operator==` covers, or that sits in a compared `Prop`, declares `bool operator==(…) const = default;` in the task that adds it: `QuantityCell` (Task 0, so `Cell == Cell` compiles), `UnloadedRow` (3b), `FilterEntry`, `ColumnFilter`, `GroupFilter`, `ColumnCount` (8b), `UnitInfo`, `Measure`, `TypedMeasure` (8c), `CarriedState::Column` (9b), `ColumnDisplay`, `ValueLabel`, `CellAccent` (15), `StatusEntry`, `RowMarks`, `KeyMoves` (17). `Rational::operator==` ignores `decimalPlaces`, so a test that means "the same cell, places included" uses `tabletest::sameCell(Cell const&, Cell const&)` (Task 0, `tests/table/table_fixtures.hpp`). +39. **What a cell view and a row look carry** (extends #28). `cellView` returns `markedCell(accentedCell(content, accent), marks)`: `CellAccent{optional tone; std::string tooltip; bool invalid}` through `setCellAccent(row, column, accent)` (Task 15; an invalid cell is `invalid = true`, tooltip "The value could not be read"), `CellMarks` through `setCellMarks` (Task 19). `TableRowLook` gains `std::optional> marks` (busy, locked, unmatched; Task 17b, through `setRowMarks`) and `bool summary` (Task 22, through `setRowSummary` right after `setRowKey`). `RowStates` is not reactive: the lowering holds a `reactive::Signal` bumped on every `RowStates` change and every retained or unmatched change, which `rowView`'s marks read. `TableRows::unmatched(table::RowId const&)` is readable by key. No row-view struct carries per-cell or per-row state for a table mounted through `TableSource`; `TableRowView` stays the C++ `table()` path's only. +40. **`TableRows::onChange` is a single slot**, set by the mount. Anything else that needs a source's changes (a grid's drafts, a summary) wraps the `TableRows` in a forwarding decorator and hands the wrapper to the mount; nothing subscribes a second time. +41. **`ui::Table` and `TableOptions` are parallel structs** (`view.hpp`); every member a task adds to one it adds to the other, and the lowering fills both. +42. **The table test harness** is `ui::testing::TableHarness` in `tests/ui_table_support.hpp`, added by Task 9d over the screenless `RowsFixture` base Task 9a adds there: a new type beside the existing `Harness`, with its own catalog (`corpusCatalog()` plus `Table.samples`, `Table.samples.describe`, and each later task's actions, added in that task with their schema text, `effects` and `records`), and `session.setLocale("en")` in its constructor only. Tests mount whole documents with a `models` block and an alias. Helpers are free functions taking `TableHarness&` (`elementValue(h, id, name)`, `rowKeys`, `rowMarks`, `cellMarks`, `cellAccent`, `menuOf`, `clipboardText`, …). The header click is the existing `RecordingBackend::clickHeader(int, std::size_t)`; Task 12b adds a defaulted `HeaderClick click = HeaderClick::Plain` to it and to the conformance probe. +43. **Declared groups on the server.** A table's groups are its `DataSource::groups()`; `table::typed`'s `RowsSource::groups()` is built from `Row::columnGroups()` and copied into the description. Task 8b makes `detail::PinnedSource`, `LeveledSource` and the scoped source forward `groups()`, and `answerQuery` passes them to `validate`, `computeView`, `checkGroups` and `distinctValues`. +44. **The document loader** (`src/ui/document.cpp`) accepts a table's new keys in the task that lowers them: Task 9d the keys `table`, `status`, `persist` and `model` + `table` without `action` (checked against `Table.` and `Table..describe` in the catalog); Task 11b a column's `kind` and the `persist`-without-`id` refusal; later tasks their own keys. Each with a loader test. +45. **Phase B's prerequisites** are Tasks 9–11, 15, 17a, 17c and 17d. +46. **A page in the query cache.** `Session::settleReply` decodes the reply of an entry whose held record is opaque (a document query of `Table.`) with a table-aware variant of `valueFromJson`: a number with a fraction becomes the decimal `Value` its shortest round-trip text in fixed notation spells (`std::to_chars` with `std::chars_format::fixed`, read by `table::parseDecimal`, so `0.0001` is a decimal and not the text `1e-04`), and one `parseDecimal` refuses becomes its shortest text. Ordinary actions keep the strict rule. Task 7b. A `rows` column of fractional numbers therefore infers as `Decimal` (Task 11a). +47. **`WatchHolder`** is a copyable handle over a shared registration, released when the last copy dies (`Completion` delivers `const T&`, so a move-only holder cannot be handed over). Task 7b. +48. **`AnswerContext`** (decision 5) carries `std::string_view record` and `bool rowScoped` beside `views`, filled by `QueryTable::invoke` (Task 6 adds them). +49. **Units of a typed table.** A model whose `typed` table has a `MeasureValue` member declares `tableUnits(TableContext const&) -> std::shared_ptr`; `detail::serve` (Task 2) calls it when the model declares it, and Task 8c adds the call. Without it such a table is `SourceContract`. A typed table's group label is its id on the source and `inferTitle(id)` in the description; code comparing the two compares ids and columns only. `bench::WideTableModel` takes `description.groups` from its source's `groups()` (Task 8b). +50. **The view cache's seams.** `remote.hpp` includes no table header but `table/runtime.hpp`, so `ViewCacheOptions{maxBytes, onCompute}` (the hook a test reads a compute's thread from), `ViewCacheStats`, a forward-declared `ViewCache`, `makeViewCache` and `viewCacheStats` live there and are defined in `src/ui/process_state.cpp`; `RemoteServer::viewStats()` reads the server's cache. A cache entry is valid while its source's `RowSnapshot::identity()` is unchanged (a typed table's `RowsSnapshot` returns its rows vector's address), so a typed table reuses its views. Task 6. +51. **One revision per served table.** After Task 16 a served table's description is `table::servedDescription(served)` (the description with `capabilities.maxSortKeys` from the server's limits, through `describe`). Every server path that names a description revision — a page, the view cache's key, Task 17a's `resolve` — takes it from there, never from `describe(served.description)`. +52. **Grid seams on the table.** Task 19 changes `Table::focus` and `onFocusCell` (Task 10a's) from a `CellRef` to `GridFocus{std::optional key; std::size_t viewRow; std::string column}`, so focus can rest on a row not fetched yet. Task 22's `SummaryRows` is a forwarding `TableRows` decorator (decision 40); the mount maps a focused view row and a cell rectangle through `SummaryRows::mounted()`. Task 11b's heading placement is shared code a form grid's `group` reuses. Task 24 makes Task 17's `RunObserver::started` treat a `TableInputKind::CellEdit` input as `busyKeys(run, {body.key})`. +53. **Smaller shared names.** A highlighted row reaches the mount as `Table::highlight` (`TableHighlight{key, row}`, Task 10a), and a range report as `Table::onSelectRange`. `kGroupRunColumn` is `"" "group"`, an id no document can write. `ScriptedDispatcher::Call` records its `CallOptions::stop` (Task 7b; Task 9a's `h.stopped(i)` reads it). Lifting the `filters` refusal on `rows` tables is Task 12's. +## Review Focus + +1. **A description that changes revision while state is held.** A view selection, retained rows, a focused cell or a cell draft held when the description takes a new revision (a column removed): the client refetches the description, fits its layout, drops what names a removed column, and never sends a query naming it. Test goes to Task 9 ("revision mid-selection"). +2. **Negative and boundary values in the display.** `-0.125` at two places under `HalfUp` is `-0.13`, under `HalfEven` `-0.12`; `0` with `empty` set shows `0`, not the empty text; a comma locale with grouping shows `-12.500,50`. Test goes to Task 15. +3. **An empty grid.** A grid over an `ObjectArray` with no rows: the walk with no editable cell lets `Tab` leave at once; a paste into it with `appendRows` adds rows, without it drops everything and says so; summaries over no rows show `count` 0 and an empty `mean`. Tests go to Tasks 19, 21 and 22. +4. **A key change onto a key the client already holds.** A `ChangedRow{key: 7, from: 3}` while row 7 is already held and selected: the selection holds 7 once, and the old row 3 is fetched again. Test goes to Task 17c. +5. **Bands under a stored layout.** A stored layout that hides every column of a band and then shows one again: the band reappears over that one column, with its unit; a band whose columns are all pinned draws only in the pinned part. Test goes to Task 22. + +--- + +## Phase A — the table (`table.md`) + +### Task 0: The fixture and the baseline (table.md step 0) + +**Spec:** "Performance" (the fixture, the data, how figures are taken), Delivery order step 0. + +**Files:** +- Create: `tests/table/wide_table_model.hpp`, `tests/table/wide_table_model.cpp` (static library `morph_wide_table_model`, linked by `morph_table_tests`, `morph_tests`, `morph_net_tests`, `morph_qt_quick_tests`) +- Modify: `tests/CMakeLists.txt`, `tests/table/bench_table.cpp`; the WebAssembly CI job that builds `morph_table_tests` and runs it under Node. + +**Interfaces:** +- Produces: `bench::WideTableOptions{std::int64_t rows; int columns; std::uint64_t seed; std::chrono::microseconds loadDelay;}`, `bench::WideTableSource` (a column-store `table::DataSource` over generated typed arrays, handing columns out in runs), with the column mix of "The data" exactly. + +- [ ] Tests: `"wide table: the same seed gives the same cells"` (two sources of seed 7 agree cell for cell over 1,000 × 300), `"wide table: the column mix is the spec's"` (counts per kind for 300 columns: 100 integers, 60 decimals, 30 quantities, 10 measures, 70 texts, 20 dates, 10 booleans; one column in twelve has 10% empty cells). Gate S3. +- [ ] Record the baselines step 0 names (S1, S2, S7 as ten `apply` calls, S8, B1 at 10,000, 20,000 and 100,000 rows, B2, B5, U1 to U5, W7 as a typed page, F2 to F5 on a `rows` table of 2,000 × 300) into table.md's Performance tables. +- [ ] Commit: `test(table): wide-table fixture and baselines`. + +### Task 0a: Remove paging in a database (table.md step 0a) + +**Spec:** "A model's tables" ("Rows in a database are a source too"), "Alternatives considered" ("Paging in the database"), Delivery order step 0a. + +**Files:** +- Delete: `include/morph/table/plan_conformance.hpp`, `tests/table/test_table_database_pages.cpp`, `examples/lims/org/include/lims/org/core/plan_sql.hpp`, `docs/spec/table/database_pages.md` +- Modify: `include/morph/table/query.hpp` (remove the "Query plans" section: `PlanUse`, the planned types, `QueryPlan`, `detail::planned*`, `planQuery`, and `QueryLimits` members only plans use), `include/morph/table/filter.hpp` (its comment naming `planQuery`), `CMakeLists.txt`, `tests/CMakeLists.txt`, `docs/spec/table/engine.md` (header table rows and the database bullet), `docs/spec/README.md` (its `database_pages.md` entry) +- Modify: `examples/lims/lab/{include/lims/lab/models/sample_model.hpp,src/models/sample_model.cpp}`, `examples/lims/ledger/{include/lims/ledger/models/ledger_model.hpp,src/models/ledger_entries.cpp}`, `examples/lims/tests/{test_sample_pages.cpp,test_ledger_entries.cpp,lims_test_support.hpp}`, `examples/lims/README.md` + +**Interfaces:** +- Consumes: `table::apply` over a `DataSource` (existing), `RowsSource` / `VectorSource` (existing). +- Produces: nothing new; the lims sample and ledger list actions read their scoped rows with one plain `SELECT` and answer with `apply`. + +- [ ] Before deleting `test_table_database_pages.cpp`, move every case that tests `apply` or `validate` rather than a plan into `tests/table/test_table_query.cpp`. +- [ ] In the lims tests, delete cases that test SQL translation; keep the cases that test what a user sees (order, filters, totals, scope, paging). Add `"ledger entries: a principal never receives a row outside its scope"` if no kept case pins it. Mutation: the model reading every row unscoped. +- [ ] `grep -rn "planQuery\|QueryPlan\|PlanUse\|plan_conformance\|standardCorpus\|database_pages" include src tests examples docs/spec` prints nothing. +- [ ] Targets `morph_table_tests`, `ladder_lims_tests`; all green. Docs build green. +- [ ] Commit: `refactor(table): remove paging in a database`. + +### Task 1: The description and the generic page (table.md step 1, first half) + +**Spec:** "A table is a description", "Rows on the wire", "A table on the server". + +**Files:** +- Create: `include/morph/table/description.hpp`; `tests/table/test_table_description.cpp` (in `morph_table_tests`) + +**Interfaces:** +- Produces: `TableColumn{ColumnInfo info; std::string label, group; bool sortable, filterable, shown;}` (the display, tone and tooltip members are added by Task 15, `edit` by Task 24), `ColumnGroupInfo`, `TableCapabilities{bool keys, distinct; std::uint32_t maxSortKeys = 8;}`, `TableDescription{id, label, columns, key, groups, levels, units, revision}` with `revision` filled by `table::describe(TableDescription)` from its canonical JSON; `GenericRow = std::vector`; `GenericPage{revision, columns, keys, rows, total, totalKind, offset}`; `writeGenericPage(PageRows const&, DataSource const&, std::span columns) -> GenericPage` and `readGenericPage(std::string_view json, TableDescription const&) -> std::expected`. + +- [ ] Tests: `"description: equal descriptions have equal revisions"`; `"generic page: every cell kind round-trips"` (empty, integer, date, `Rational`, `double` in a `Number` column, text, bool, `QuantityCell` with and without a factor; JSON per the "Rows on the wire" table, e.g. `[3, 10, "kg"]` read only in a `Measure` column once Task 8c lands); `"generic page: a cell that does not read as its column's kind is invalid"`. Gates W5, W7. +- [ ] Commit: `feat(table): table descriptions and the generic page`. + +### Task 2: Tables of a model on the bridge (table.md step 1, second half) + +**Spec:** "A model's tables", "The table's record", "Typed rows are a convenience". + +**Files:** +- Modify: `include/morph/table/description.hpp` (`TableContext`, `ServedTable`, `ChangedRow`, `ChangedRows`, `TableOf`, `table::typed`, `table::scoped`, `table::rowScoped`, `table::derivedFrom`), `include/morph/core/registry.hpp` and `include/morph/core/effects.hpp` (`BRIDGE_REGISTER_TABLE`, `effects::updatesTable`, `effects::changesTable`, the result walk's slot for `ChangedRows`), `include/morph/core/remote.hpp` (`ServerConfig::tableWork`, `table::TableRuntime`), `include/morph/table/query.hpp` (`TableQuery::columns`, `QueryLimits::maxColumns` — Task 1) +- Modify: `tests/table/wide_table_model.*` (`bench::WideTableModel` with tables `wide`, `small`, `scoped`; actions `EditWideRow`, `ReplaceWideRows`) +- Create: `tests/net/test_push_tables.cpp` (in `morph_net_tests`) +- Docs: `docs/spec/core/registry.md`, `docs/spec/core/backend.md` ("Fan-out") per table.md's Neighbouring specs, step 1. + +**Interfaces:** +- Produces: `BRIDGE_REGISTER_TABLE(Model, "id", &Model::fn[, options…])` registering `Table.` (`TableQuery` → `GenericPage`) and `Table..describe` (→ `TableDescription`) and the record `.`; `ServedTable{description, source, levels, mayRead, scope, services, limits}`. + +- [ ] Tests (spec rows "A table from a description", "A model with several tables", "Columns by session"): a model with no row type serves a table; two tables of one model are authorised and changed apart; `updatesTable` without `ChangedRows` is refused when the registries resolve; two principals get different descriptions. Mutations as the spec names. +- [ ] Commit: `feat(core): register tables of a model`. + +### Task 3: Unloaded cells in the engine (table.md step 2a) + +**Spec:** "The unloaded cell", "Semantics of an unloaded cell", "Data levels" (`ColumnInfo::level`, `levelsNeeded`, `LevelLoaded`). + +**Files:** +- Modify: `include/morph/table/data_source.hpp`, `sort.hpp`, `filter.hpp`, `engine.hpp`, `query.hpp`, `edits.hpp` +- Create: `tests/table/test_table_unloaded_cells.cpp`; extend `test_table_filter.cpp`, `test_table_sort.cpp`, `test_table_query.cpp` + +**Interfaces:** +- Produces: `struct Unloaded {}` as a `Cell` alternative (after `QuantityCell`), `CellState::Unloaded`, `enum class Match { No, Yes, Unknown }`, `CompiledFilter::evaluate(...) -> Match`, `ColumnInfo::level`, `LevelsNeeded{order, display}`, `levelsNeeded(query, columns, mayRead)`, `LevelLoaded`, `Engine::undecidedRowCount()`, `undecidedRows()`, `onUndecidedChange`, `PageRows::{totalKind, undecided, awaiting, failed}`, `TableErrorCode::SourceContract`. + +- [ ] Tests: spec rows (a), (b) ×3, (c) and the engine half of (d); invariant 1 and 2 properties over random tables and completions. Gates S1 to S6. +- [ ] Commit: `feat(table): unloaded cells and data levels in the engine`. + +### Task 4: Partial pages and keyed queries on the wire (table.md step 2b) + +**Spec:** "Partial pages", "Keyed queries". + +**Files:** `include/morph/table/query.hpp`, `description.hpp` (generic page members); tests in `test_table_query.cpp`, `test_table_description.cpp`. + +**Interfaces:** +- Produces: `TableQuery::keys`, `QueryLimits::maxKeys`, `Page::indices`, `UnloadedLevels`, and on `GenericPage` the members Task 3b put on `Page`; `validate` bounds per the spec. + +- [ ] Tests: spec row "`TableQuery` on the wire"; a keyed reply carries the view's totals and each row's view row. Gates W3, W4. +- [ ] Commit: `feat(table): partial pages and keyed queries`. + +### Task 5: The level cache (table.md step 2c, first half) + +**Spec:** "The server level cache" (all eleven rules). + +**Files:** Create `include/morph/table/level_cache.hpp`, `tests/table/test_table_level_cache.cpp`; add the slow level `recipe` to the fixture. + +**Interfaces:** +- Produces: `LevelRead`, `LevelUse`, `LevelSnapshot`, `LevelSource`, `LevelCacheOptions`, `LevelCacheStats`, `LevelCache`, `CellLevelCache`. + +- [ ] Tests: spec rows "A value is loaded once" (cache half), "Concurrent queries share a load", "Reloaded once after invalidation", "A load in flight at invalidation", "Visible before told", "Eviction", "A level's layout is the cache's", "A cache's size is deep", "A reader blocks no one", "Order uses are leased", "A failed load". Gates L1 to L8. +- [ ] Commit: `feat(table): the level cache`. + +### Task 6: Announce, attach and the view cache (table.md step 2c, second half) + +**Spec:** "Arrival" steps 1 to 3, "The view cache". + +**Files:** Create `include/morph/table/view_cache.hpp`, `tests/table/test_table_view_cache.cpp`, `tests/net/test_push_unloaded_rows.cpp`; modify `include/morph/core/remote.hpp`, `include/morph/core/change_types.hpp`, `include/morph/table/runtime.hpp`, `src/ui/process_state.cpp`. + +**Interfaces:** +- Produces: `RemoteServer::announce(record, keys)`, `RemoteServer::attach(std::shared_ptr)`, `effects::IChangeObserver`, `effects::AnnounceSink`, `ViewCache` (`view_cache.hpp`); `ViewCacheOptions{maxBytes = 64 MiB, onCompute}`, `ViewCacheStats`, `makeViewCache`, `viewCacheStats` (`table/runtime.hpp`, decision 50); `RemoteServer::viewStats()`; `RowSnapshot::identity()`; `table::changeKeys`, `table::rowIdOf`. + +- [ ] Tests: spec rows "`announce`", "A cached view is the view", "One sort for many watchers", "No value crosses a scope", "A row-scoped table", and the bridge halves of (a), (c), (d). Gates S7, S9, C1 to C3. +- [ ] Commit: `feat(net): announce arrivals and cache views`. + +### Task 7: The window under changes (table.md step 2d) + +**Spec:** "The window under changes", "The client's caches". + +**Files:** `include/morph/table/query.hpp` (`PageWindow`), `include/morph/ui/interpreter.hpp` (`Session::read`, `Session::watchRecord`, the query cache's open, partial and opaque entries); tests `tests/table/test_table_server.cpp`, `tests/test_ui_interpreter_cache.cpp`. + +**Interfaces:** +- Produces: `PageFetch{request, columns, query, revision}`, `RowsFetch`, `Refresh`, `RefreshPlan`, `PageWindow(pageSize, maxPages, key, maxKeys, maxColumns)` with `visible(first, count, columns)`, `superseded()`, `cancelled`, `refresh(keys)`, `owed()`, `invalidate()`, `accept`, `patch`; `PageWindow`. + +- [ ] Tests: spec rows "An event that precedes its page reply", "An ordinary edit on the same record", "Invalidation faster than a round trip", "A reply holds the named columns only", "A row the window never held", "An open entry hears every change", "A partial entry is not merged into", "An opaque entry", "A read with no entry", the window half of (d). Gates K1 to K4, K6, K7, E1 to E4. +- [ ] Commit: `feat(table): the page window under changes`. + +### Task 8: Filters, groups, units and layout in the engine (table.md step 3) + +Four commits, one per subsystem, each its own reviewer gate. + +**8a — `oneOf` and distinct values.** Spec: "Filters from the header" (the value-set operator, distinct values). Files: `filter.hpp`, `engine.hpp`, `query.hpp`; `tests/table/test_table_distinct.cpp`. Produces: `FilterEntry::oneOf`, `DistinctRequest{column, group, search, bucket, offset, limit = 200}`, `DistinctValue{text, operand, count}`, `DistinctValues{values, distinct, distinctKind, blanks, invalid, partial}`, `DateBucket`, `distinctValues(source, query, request, options)`, `Engine::distinctValues`, `TableQuery::distinct`, `Page::distinct`. Tests: spec rows "`oneOf`", "Distinct values"; invariants 22, 23. Gates D1 to D6. Commit `feat(table): value sets and distinct values`. + +**8b — Column groups.** Spec: "Column groups". Files: `filter.hpp`, `data_source.hpp` (`DataSource::groups()`), `forms/views.hpp` (`x-group`). Produces: `GroupMode{Columns, Together}`, `ColumnCount{Any, All, AtLeast, Exactly; n}`, `GroupFilter{group, columns, mode, match, combine, include, exclude}`, the augmenting-path matching for `Together`. Tests: spec row "Column groups" (the truth table row by row, the three-valued table with unloaded cells); invariant 24. Gates G1 to G7. Commit `feat(table): column groups with quantifiers`. + +**8c — Values with units.** Spec: "Values with units". Files: `data_source.hpp`, `sort.hpp`, `filter.hpp`; `include/morph/ui/measure.hpp` (`parseMeasure`); `tests/table/test_table_measure.cpp`. Produces: `UnitInfo`, `UnitId`, `UnitRegistry` with `lineage()`, `UnitRegistryBuilder{previous}`, `addUnitsOf`, `Measure`, `ColumnKind::Measure`, `ColumnInfo::dimensions`, `Services::units`. Tests: spec rows "Values with units", "Unit numbers across registries"; invariant 25. Gates M1 to M5. Commit `feat(table): values with units`. + +**8d — Column layout.** Spec: "Columns: order, visibility, pinning, width" (the fitting rule). Files: `engine.hpp` (`ColumnLayout`); `tests/table/test_table_columns.cpp`. Produces: `ColumnLayout::setWidth(id, std::optional)`, `widths()`, `setPinned(n)`, `pinned()`, `value()`, `apply(value)`, `rebuild` placing a new column after its declared predecessor. Tests: spec row "Column layout" (the engine half). Commit `feat(table): widths, pinning and fitting in the column layout`. + +### Task 9: `TableRows` and the model-backed table on a screen (table.md step 4) + +**Spec:** "The client table model", "The document `table` node on the engine", "The status line" (counts), "Persisted state" (the interface, the framework's stores, loading before the first rows, saving for sort and filters). + +**Files:** +- Create: `include/morph/ui/table_rows.hpp`, `include/morph/table/state_store.hpp`, `include/morph/ui/table_state.hpp`, `include/morph/ui/table_state_model.hpp`; `tests/test_ui_table_model.cpp`, `tests/test_ui_table_state.cpp`, `tests/table/test_table_state.cpp` +- Modify: `include/morph/ui/interpreter.hpp` (the lowering of a model-backed `table` onto `WindowRows`; `SessionOptions::{tableState, tableStateTimeout, tableStateDebounce, tableSettle, tableAwaitedRefetch}`) +- Docs: `docs/spec/ui/interpreter.md`, `docs/spec/ui/document.md`, `docs/spec/ui/preferences.md`, `docs/spec/table/engine.md` per step 4. + +**Interfaces:** +- Produces: `ui::SortChain`, `TableTotal`, `TableRowRef`, `TableCountsView`, `class TableRows` (pure virtual, members as the spec's block), `EngineRows`, `WindowRows`; `TableStateKey{application, model, table, qualifier, part}`, `StoredTableState`, `SaveOutcome`, `SaveResult`, `ITableStateStore{load, save, remove}`, `MemoryTableStateStore`, `PreferencesTableStateStore`, `TableStateModel` (`morph.tableState`). + +- [ ] Tests: spec rows "Persisted state before the first query", "Stale state is fitted", "Saves are coalesced", "A slow or failed load", "The person is the store's", "Bound values win", "State of any size", "A scroll that passes", "An awaited order is throttled", "The status line" (counts). Review Focus 1: `"table rows: a new description revision drops what names a removed column"` (a held view selection and a cell draft naming column `c` are dropped when `c` leaves the description; the next query does not name `c`). Gates U6, K5, K8, F6, F7, T1, T3 to T5; W6's one request; F1 recorded. +- [ ] Commit: `feat(ui): table rows, model-backed tables and stored state`. + +### Task 10: The column window (table.md step 5) + +**Spec:** "The renderer" (all subsections). + +**Files:** `include/morph/ui/view.hpp`, `include/morph/ui/mount.hpp` (`Virtualization` additions, `ColumnExtents`, cell pools, the frame budget, focus by key and column), `include/morph/ui/backend.hpp` (the range-selection report by view rows); the Qt Quick `MorphTable` and the terminal table; tests `tests/test_ui_mount.cpp`, `tests/qt_quick/`. Docs: `docs/spec/qt_quick/backend.md`. + +- [ ] Tests: spec rows "Windows of the renderer", "Keyboard and focus under windowing", "Range selection in server mode", "Column layout" (gate D8: hiding and moving create no cell widgets). Gates F1 to F5, F8 to F10, U7, D8. **Exit criterion:** U8, the same scrolls in the WebAssembly build within F3's and F4's budgets. +- [ ] Commit: `feat(ui): the column window`. + +### Task 11: Tables over `rows` on the engine (table.md step 6) + +**Spec:** "A document's rows as a source", "What the interpreter does for a table". + +**Files:** `include/morph/ui/table_rows.hpp` (`ValueRowsSource`), `include/morph/ui/interpreter.hpp` (the interpreter's own sort and page go); tests `tests/test_ui_table_model.cpp`, `tests/test_ui_table.cpp`. + +- [ ] Tests: spec rows "A document's rows as a source", "One order on every surface". Gates U1 to U4; B1's 20,000-row step bound. +- [ ] Commit: `feat(ui): tables over rows on the engine`. + +### Task 12: The configuration interface (table.md step 7) + +**Spec:** "Configuring a table" (columns, sort chains, filters from the header, column groups' menu, copy), "Keyboard, focus and assistive technology" (range selection in server mode). + +**Files:** `include/morph/ui/interpreter.hpp` (`layout`, `onLayoutChange`, `configurable`, `locked`), the Qt Quick and terminal backends (header and table menus, drag, resize, the sort dialog, the column chooser, the filter menu, the status line), `IViewBackend::copyText`; tests `tests/test_ui_table_model.cpp`, `tests/qt_quick/`. + +- [ ] Tests: spec rows "Sort chains", "Copy", "The status line" (messages and refusals), the menu halves of "Column layout", "Distinct values" and "Column groups". Gates D7, D9, B3, B4. Screenshot baselines of existing screens change here, as intended; regenerate them in this commit. +- [ ] Commit: `feat(ui): configure a table from its header`. + +### Task 13: Collections through the same lowering (table.md step 8) + +**Spec:** "Collections and master-detail". + +**Files:** `include/morph/forms/engine/collection.hpp`, `include/morph/ui/interpreter.hpp`; tests `tests/test_ui_table_model.cpp`. + +- [ ] Tests: a collection and a `rows` table over the same rows show the same order and selection. Gate U5. +- [ ] Commit: `feat(ui): collections on the table pipeline`. + +### Task 14: Saved and shared views (table.md step 9) + +**Spec:** "Saved views", "Persisted state" ("Two windows, two devices", shared views, `defaultOnMount`). + +**Files:** `include/morph/table/state_store.hpp` (`ITableStateStore::shares()`), `include/morph/ui/table_state_model.hpp` (`morph.tableState.publish`); tests `tests/test_ui_table_state.cpp`, `tests/net/test_push_tables.cpp`. + +- [ ] Tests: spec rows "Views are not lost between windows", "Shared views". Gate T2. +- [ ] Commit: `feat(ui): saved and shared table views`. + +### Task 15: How a column shows its cells (table.md step 9a) + +**Spec:** "How a column shows its cells". + +**Files:** `include/morph/table/description.hpp` (`ColumnDisplay`, `Rounding{HalfEven, HalfUp}`, `ValueLabel`; `TableColumn::{display, tone, tooltip}`; `TableDescription::{rowTone, rowLock}`), create `include/morph/ui/cell_format.hpp` (`ui::formatCell(Cell const&, TableColumn const&, FormatContext const&, DisplayUnits const& = {}) -> std::string`), the mount and backends (tone surfaces, tooltips, the "more here" mark, header units); tests `tests/test_ui_cell_format.cpp`, `test_table_description.cpp`, `tests/test_ui_table_model.cpp`. + +**Interfaces:** +- Consumes: `ui::locale_table` (number and date facts per locale). +- Produces: `ui::formatCell`, used by every backend, copy, the status line and the filter menu. + +- [ ] Tests: spec rows "A column's display", "Companion columns travel with their column", "Locked rows and companions" (the companion half). Review Focus 2: `"format cell: negative halves and empty text"` (`-0.125` at 2 places: `HalfUp` → `"-0.13"`, `HalfEven` → `"-0.12"`; `0` with `empty = "–"` → `"0"`; empty cell → `"–"`; locale `de` with grouping → `"-12.500,50"`). +- [ ] If Task 9 has landed first, replace its stand-in formatter with `formatCell` in this commit. +- [ ] Commit: `feat(table): column display, tone and tooltip`. + +### Task 16: A raised sort bound (table.md step 9c) + +**Spec:** "Sort chains" (the bound). + +**Files:** `include/morph/table/description.hpp` (`TableCapabilities::maxSortKeys` filled from `ServedTable::limits`), `include/morph/ui/interpreter.hpp` (`maxSortKeys` on a `rows` table). + +- [ ] Tests: spec row "A raised sort bound". +- [ ] Commit: `feat(table): a sort bound up to 32 keys`. + +### Task 17: Acting on rows (table.md step 9b) + +**Spec:** "Acting on rows" (all subsections). Needs Tasks 9 and 15. Four commits. + +**17a — A selection of the view.** Files: create `include/morph/table/row_selection.hpp` (`RowSelection` with `x-selectionOf`, `SelectionPolicy`, `SelectedRows`, `resolve(model, selection, context, policy)`, `ResolveRequest`, `RowRef` with `x-rowOf`); `view_cache.hpp` (the membership digest); `query.hpp` (`Page::viewRevision`, `TableErrorCode::ViewChanged`, `QueryLimits::maxSelectedRows`); `BRIDGE_REGISTER_TABLE` adds `Table..resolve`; `WindowRows` (select-all as a view, `except`, `selectedCountKind`, the copy of a view selection); tests `tests/table/test_table_selection.cpp`, `tests/net/test_push_tables.cpp`, `tests/test_ui_table_model.cpp`. Tests: spec rows "A selection of the view", "Resolving from elsewhere", "The view revision is membership", "Copy of a selection of the view"; invariants 33, 34. Commit `feat(table): select the whole view and resolve it on the server`. + +**17b — Rows kept in view.** Files: `query.hpp` (`TableQuery::retain`, `Page::unmatched`, `QueryLimits::maxRetained`), `view_cache.hpp` (merging retained rows per request), `engine.hpp` (`Engine::retain`), `WindowRows` (the retained set, `retainHold`). Tests: spec rows "Retained rows", "Retained rows and the event"; invariant 35. Commit `feat(table): keep rows an action changed in view`. + +**17c — Key changes, busy, failed and locked rows.** Files: `description.hpp` (`ChangedRow::from`, `FailedRow`, `ChangedRows::failed`, `rowLock`), `core/changes.hpp` (`addUpdatesChange`, the walk collecting `from`), `WindowRows`/`EngineRows` (moving state by `from`, busy rows from `RowSelection`/`RowRef`/`CellEdit` inputs, failed marks and "Clear marks", locked rows). Tests: spec rows "A key that changes", "Busy and failed rows", "Locked rows and companions" (the lock half). Review Focus 4: `"key change: onto a key already held"` (`ChangedRow{key: 7, from: 3}` with 7 held and selected: the selection holds 7 once; row 3 is fetched again). Commit `feat(table): key changes, busy, failed and locked rows`. + +**17d — The application's menu entries and a disabled header.** Files: `ui/interpreter.hpp` (`cellMenu`, `headerMenu`, `headerEnabled`, `retainChanged`, element values `selectionSet`, `busyCount`), the backends' menus. Tests: spec rows "The application's menu entries", "A disabled header". Commit `feat(ui): application entries in table menus and a disabled header`. + +### Task 18: Step 10, as measured + +Not a task until a figure justifies it (table.md step 10: repairing a cached view, local work when a window holds the whole view, a persistent tier). Each, when its benchmark shows the need, gets its own plan. + +--- + +## Phase B — editing (`editing.md`) + +### Task 19: The focus chain and a grid of a form (editing.md step 1) + +**Spec:** editing.md "A grid of a form" (binding, columns are fields, submission), "The cell" (editor, entering and leaving, validation, read-only, what changed), "Walking". Needs Tasks 9, 11, 15. + +**Files:** +- Modify: `include/morph/ui/view.hpp`, `include/morph/ui/backend.hpp`, `include/morph/ui/mount.hpp` (a focus chain in document order; `focusNext(node)`, `focusPrevious(node)`) +- Create: `include/morph/ui/form_rows.hpp` (`FormRowsSource`), `include/morph/ui/grid.hpp` (the cell editor host, the walk), `tests/test_ui_grid.cpp` +- Modify: `include/morph/forms/engine/form_session.hpp` (per-cell snapshots of `ObjectArray` rows by row key; `modified(path) -> bool`, `revert(path)`), `include/morph/ui/interpreter.hpp` (a `table` with `form` and `field`; the overlay `{"widget": "grid", "grid": {…}}`; `enterMoves`, `walk`, element values `modifiedCount`, `modifiedRows`, `errorCount`, `editing`) +- Docs: `docs/spec/ui/view_tree.md`, `docs/spec/ui/backend_contract.md`, `docs/spec/forms/engine.md` (the grid widget leaves "Not supported"; per-cell snapshots), `docs/spec/ui/document.md`, `docs/spec/ui/interpreter.md`. + +- [ ] Tests: editing.md rows "A grid is a form", "Read-only is one rule (grid)", "The walk" (grid cases), "A sorted grid keeps its record", "Submission", "What changed". Review Focus 3 (walk half): `"grid: an empty grid lets Tab leave at once"`. +- [ ] Commit: `feat(ui): grids of a form`. + +### Task 20: Derived values (editing.md step 2) + +**Spec:** editing.md "Derived values". + +**Files:** +- Create: `include/morph/forms/derive.hpp` (`DeriveOf`, `Derived{values: [{path, value}]}`, the `derived()` field metadata writing `x-derived`) +- Modify: `include/morph/forms/forms.hpp` (`computedFields` on a row type, recomputed by `recomputeAll` inside `ObjectArray` rows), `include/morph/core/registry.hpp` (`evaluate` recomputing row members), `include/morph/forms/engine/form_session.hpp` (`loadDerived(Derived const&)` and `loadDerived` from an evaluation body; the round's debounce, sequence and row-key mapping), `include/morph/forms/choice.hpp` (options depending on the row), `include/morph/ui/grid.hpp` (kind and overlays per row) +- Create: `tests/forms/test_forms_derive.cpp` +- Docs: `docs/spec/forms/forms.md`, `docs/spec/forms/engine.md`, `docs/spec/core/registry.md`. + +- [ ] Tests: editing.md rows "Derived values", "The server decides", "Kind per row", "Choices per row"; invariants 2, 3, 9. +- [ ] Commit: `feat(forms): derived values for grids`. + +### Task 21: Selecting cells, paste and rows of a grid (editing.md step 3) + +**Spec:** editing.md "Selecting cells, clipboard and fill", "Rows of a grid". + +**Files:** `include/morph/ui/grid.hpp`, `include/morph/ui/interpreter.hpp` (`selectionMode: "cells"` and its value, `appendRows`, `rowsFixed`), the backends; tests `tests/test_ui_grid.cpp`. + +- [ ] Tests: editing.md rows "Cell selection", "Paste, fill, clear", "Rows of a grid"; invariant 7. Review Focus 3 (paste half): `"grid: paste into an empty grid"` (with `appendRows` it adds the block's rows up to `maxItems`; without, it drops every value and the status line counts them). +- [ ] Commit: `feat(ui): cell selection, paste and row operations in grids`. + +### Task 22: Bands, spans and summary rows (editing.md step 4) + +**Spec:** editing.md "Header bands", "Spans", "Summary rows". + +**Files:** `include/morph/table/description.hpp` (`BandInfo{label, unit, columns, bands}`, `TableDescription::bands`), `include/morph/ui/view.hpp`, `include/morph/ui/mount.hpp`, `include/morph/ui/interpreter.hpp` (`bands`, a span part's `columns`, `summaries` on `table` and `group`), the backends; tests `tests/test_ui_mount.cpp`, `tests/test_ui_grid.cpp`, `tests/qt_quick/`. + +- [ ] Tests: editing.md rows "Bands", "Spans", "Summary rows"; invariant 8. Review Focus 5: `"bands: a stored layout hides then shows a band's column"` (the band reappears over the one shown column with its unit; a band whose columns are all pinned draws only in the pinned part). Review Focus 3 (summary half): `"summary: over no rows"` (`count` 0, `mean` empty). +- [ ] Commit: `feat(ui): header bands, spans and summary rows`. + +### Task 23: Fixed grids (editing.md step 5) + +**Spec:** editing.md "Fixed grids". + +**Files:** `include/morph/ui/grid.hpp`, `include/morph/ui/interpreter.hpp` (`layoutRows` with `form`, blocks by `forEach`); tests `tests/test_ui_grid.cpp`. + +- [ ] Tests: editing.md row "Fixed grids". +- [ ] Commit: `feat(ui): fixed grids`. + +### Task 24: Cells of a model's table (editing.md step 6) + +**Spec:** editing.md "Cells of a model's table". Needs Tasks 9 and 17. + +**Files:** `include/morph/table/edits.hpp` (`CellEdit` with `x-cellEditOf`, `RowEdit` with `x-rowEditOf`, `EditInfo{action, member, readonly}`, `CellEdits` committing a `RowEdit` per row and holding drafts by row key and column), `include/morph/table/description.hpp` (`TableColumn::edit`), `include/morph/ui/table_rows.hpp`, `include/morph/ui/interpreter.hpp` (`editMode`); tests `tests/test_ui_table_model.cpp`, `tests/net/test_push_tables.cpp`. + +- [ ] Tests: editing.md rows "Cells of a model's table", "Read-only is one rule (model table)", "The walk" (model-table case); invariant 6. +- [ ] Commit: `feat(table): edit cells of a model's table`. + +--- + +## Order and parallelism + +Tasks run in the order above, except: + +- Task 0a has no dependency and may run first or beside Task 0. +- Task 8 runs 8a, 8b, then 8d; 8c needs Tasks 1, 2 and 5 and follows 8b. They share `filter.hpp`, so they merge one at a time. +- Task 15 may land before Task 9 (then Task 9 uses `formatCell` directly). +- Task 12 runs 12a, 12b, 12c, 12e, then 12d; 12f may follow anywhere after 12c. +- Task 16 depends only on Task 12. +- Phase B starts after Tasks 9–11, 15, 17a, 17c and 17d (decision 45). diff --git a/examples/common/testkit/screen_harness.hpp b/examples/common/testkit/screen_harness.hpp index 6f9c07f44..054c78918 100644 --- a/examples/common/testkit/screen_harness.hpp +++ b/examples/common/testkit/screen_harness.hpp @@ -397,6 +397,10 @@ class ScreenHarness { return true; } + /// @brief Runs the work already queued on the owner, and what that work queues: a table over `rows` takes its + /// rows into the engine from a posted task, so a screen that has just mounted shows them after this. + void settle() { _context.owner().drain(); } + /// @brief Advances the scheduler's clock by @p delta, firing the timers then due, such as a query's /// `refreshEvery`. The harness's scheduler is manual: no timer fires unless a test advances it. /// @param delta How far. diff --git a/examples/lims/README.md b/examples/lims/README.md index 92d3ae792..9e7f5102a 100644 --- a/examples/lims/README.md +++ b/examples/lims/README.md @@ -1786,37 +1786,16 @@ returned took 140 ms. A trial balance over 10^7 posted lines (5 * 10^6 entries o 168,209 ms and peaked at 10,857 MB; its totals equal the independently accumulated `int64` sums exactly, so it answers, but by loading every line, which is not the production criterion. The inference in decision 30 (about 11 s at 10^7) was a time estimate that assumed the lines fit in memory; the measured time is 168 s and the memory it left out is -10.9 GB. `ListEntries` makes about five queries per entry, so most of its time is that pattern; one flat read of the -narrow rows was not measured. Writing the rows took 25 s and 121 s. Not measured: other hardware, other databases. +10.9 GB. `ListEntries` then made about five queries per entry, so most of its time was that pattern. It now reads the headers +in one query, the accounts once and the lines 500 entries per query: on the Windows `cl-qt-release` build with +SQLite's ODBC driver, a `ListEntriesPage` of 50 at offset 500,000 of 10^6 entries took 34,902 ms. Writing the rows took 25 s and 121 s. Not measured: other hardware, other databases. The first case's run was 592 s against a 600 s ctest limit, so a case named for a 10^6 or 10^7 table has a 1,800 s limit (`cmake/morph_add_rung.cmake`); both are `Stress:` cases and outside `ctest -L ladder -LE stress`. -morph gained the database-page seam (`docs/spec/table/database_pages.md`): `table::planQuery`, a validated plan a model -translates into its own query; `Page::totalKind`, a total that is the count or a lower bound; and -`table::conformanceFailures`, which holds the translation to `apply`'s pages. It covers the journal's list. The trial -balance is a sum, not a page: it computes its rows in the store and pages them with `apply` or with a plan over the -aggregate, which the seam does not describe. - -On the seam, the same page (`ListEntriesPage`: 50 rows at offset 500,000 of 10^6 entries) took 180 ms with resident -memory 46 MB to 48 MB (peak 47 MB to 51 MB), and the trial balance over 10^7 lines took 3,885 ms with peak memory 41 MB -(40 MB before), summed in the database, exact or refused as `OutOfRange`. Same build and machine as above, one run each; -the totals equal the independently accumulated sums exactly. The sample list pages on it too. Stock movements are the -second instance, which is the stock movements of the inventory module. - -How it is held to the engine. `ListEntriesPage` and `ListSamples` translate the plan into one `SELECT` (the plan's -filters to a `WHERE`, its sort to an `ORDER BY` ending in the row id, offset and limit) and count the filtered view -with one `COUNT` in the same read transaction, so the total is `Exact` at any size. That read transaction holds SQLite's shared lock until the page's rows are loaded (2.7 s for the filtered page at 10^6 entries), so a concurrent writer can be turned away for that window; a busy or locked database is reported as `Conflict`. The tests run -`conformanceFailures` over `standardCorpus` of each list's own rows, against SQLite, with the total cap lowered to 10, -plus date-time queries the corpus cannot derive; each mutation named beside those tests fails them. Three -rules of the spec decided the translation. Text: the default collator folds ASCII and Latin-1 letters, SQLite's `lower` -folds ASCII, so the statement lowers and replaces the 29 Latin-1 capitals itself and compares and orders the result -bytewise; the conformance data carries accents, a Greek capital and `?`, `{`, `'` and `%` to hold that. Dates: a -`DateTime` column is the whole UTC second of a millisecond column, floored, so sub-second instants tie and `eq` is a -second. Integers: an operand is never rounded, `eq 1.5` matches nothing and `lt 1.5` is `<= 1`. Empty cells sort last, -and an exclude keeps them. `lines` and `rate` of the journal are refused with `Unavailable`: `lines` is another table -serialised, and `rate` is a numerator and denominator whose exact comparison multiplies two `int64` values, which -SQLite turns into a real on overflow. +The sample and ledger lists (`ListSamples`, `ListEntriesPage`) read the caller's rows with one query and answer +with `table::apply`, so their order, filters and total are the engine's on every surface. The total is the count up +to `QueryLimits::totalCap` (100,000 rows) and omitted above it, so the 10^6-entry page has none. The trial balance sums `company_num` per account, side and denominator in the database and adds the few sums per account exactly. This is not the brief's sum of minor units: the ledger's own tests hold 5 * 10^18 whole units as a @@ -1824,28 +1803,11 @@ figure that reports exactly, which is 5 * 10^20 minor units and does not fit `in one up to the denominator: a sum of numerators of one denominator past `int64` is refused even where it would reduce to a representable value. SQLite's `SUM` raises `integer overflow` rather than wrapping (measured by a test, not read from the manual), and the ledger reports that as `OutOfRange`. +The trial balance over 10^7 lines took 3,885 ms with peak memory 41 MB, one run on the same build and machine as +above; its totals equal the independently accumulated sums exactly. ## Findings raised by this rung -- **Paging a table in the database is raw SQL.** Lightweight's query builder has no `COALESCE`, `CASE`, `NULLIF`, - `instr`, `replace` or computed `ORDER BY`, which the engine's meaning of empty cells, enum names and the collator's - fold need, so `org/core/plan_sql.hpp` writes the statement text and runs it with `SqlStatement::Prepare` and - `ExecuteWithVariants`: IMPLEMENTATION.md rule 4's escape tier. The statement text holds only the model's own column - mapping, enumerator names and the plan's clamped numbers; every operand a client sent is a `?` with a value bound - at run time, so no escaping is involved. A text operand holding a NUL byte is refused in words, since SQLite's - `length` and `instr` stop at it. Tests run quotes, a statement terminator, `%`, `_`, backslashes, `?` and a driver - escape through the page and compare it with the engine's. Not verified: other databases (the `lower` and `replace` - fold is SQLite's), a SQLite built with ICU (its `lower` would fold more than the collator and the conformance run - would fail). Upstream: no Lightweight issue was searched for or filed. - -- **The standard conformance corpus built date operands that never parsed. Fixed in morph.** Its operands were the - cells' own text, and a date-time cell shows as whole seconds (`1793437200`), which the default date parser does not - read, so `apply` and the plan refused such a query identically and the helper counted that as agreement. Measured: a - translation that truncated a negative millisecond instant toward zero instead of flooring it passed the corpus and - failed only when the lims tests built the operands from the rows' own seconds by hand. `standardCorpus` now writes - ISO operands, `conformanceFailures` reports a column whose queries were all refused identically, and a framework - test holds the truncating model. - - **A data migration that copies rows needs raw SQL.** Lightweight's migration builder inserts literal rows only, so moving `lims_operators` into `org_role_assignments` is one `RawSql` `INSERT ... SELECT` (`lab/src/db/schema.cpp`, migration `20261109000004`), under IMPLEMENTATION.md rule 4's escape tier. Upstream: a diff --git a/examples/lims/lab/include/lims/lab/models/sample_model.hpp b/examples/lims/lab/include/lims/lab/models/sample_model.hpp index fec672961..612b47f01 100644 --- a/examples/lims/lab/include/lims/lab/models/sample_model.hpp +++ b/examples/lims/lab/include/lims/lab/models/sample_model.hpp @@ -94,20 +94,19 @@ class SampleModel { /// @throws ValidationError if the query names a column the rows do not have, or exceeds the limits. ::morph::table::Page execute(const ListSamples& action); - /// @brief Whether the database can sort or filter the sample list by @p column. - /// @param column The column's id. - /// @param use What the column is wanted for. - /// @return `true` for every column of `SampleView`; `false` for a name that is no column. - [[nodiscard]] static bool canTranslateSampleColumn(std::string_view column, ::morph::table::PlanUse use); - - /// @brief Reads a page of the samples at @p sites for a validated plan. + /// @brief Answers @p query over the samples at @p sites: reads those rows and runs the query over them with + /// `table::apply`; the total is the count up to `QueryLimits::totalCap` and omitted above it. /// @param sites The sites whose samples are listed. - /// @param plan The plan from `table::planQuery`, made with `canTranslateSampleColumn`. - /// @return The page, with an exact total. - /// @throws ValidationError if the plan holds an operand the database cannot compare. + /// @param query The sort, filters and page. + /// @param action The action named in a refusal. + /// @param options How `apply` runs; its `limits.totalCap` decides above which count the total is omitted. + /// @return The page. + /// @throws ValidationError if the query names a column the rows do not have, holds an operand its column cannot + /// parse, or exceeds the limits. /// @throws Lightweight::SqlException if a statement fails. - [[nodiscard]] static ::morph::table::Page pageSamples(std::vector const& sites, - ::morph::table::QueryPlan const& plan); + [[nodiscard]] static ::morph::table::Page pageSamples( + std::vector const& sites, ::morph::table::TableQuery const& query, + std::string_view action = "ListSamples", ::morph::table::ApplyOptions const& options = {}); /// @brief `Registered → Received`. /// @param action Carries no fields of its own. diff --git a/examples/lims/lab/src/models/sample_model.cpp b/examples/lims/lab/src/models/sample_model.cpp index b51bcfb67..84571eaf4 100644 --- a/examples/lims/lab/src/models/sample_model.cpp +++ b/examples/lims/lab/src/models/sample_model.cpp @@ -5,11 +5,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -20,7 +22,6 @@ #include "lims/lab/events/lab_outbox_store.hpp" #include "lims/org/core/errors.hpp" #include "lims/org/core/model_support.hpp" -#include "lims/org/core/plan_sql.hpp" #include "lims/org/models/org_model.hpp" namespace lims { @@ -277,63 +278,46 @@ namespace { return columns; } -/// @brief How the database reads each sample column. The state is the enumerator's name, as the table engine holds it. -/// @return The columns by id. -[[nodiscard]] plansql::Columns const& sampleSqlColumns() { - static plansql::Columns const columns{ - {"id", plansql::integer("id")}, - {"siteId", plansql::integer("site_id")}, - {"clientId", plansql::integer("client_id")}, - {"reference", plansql::storedText("reference")}, - {"state", plansql::text(plansql::enumName("state", static_cast(SampleState::Rejected) + 1))}, - {"version", plansql::integer("version")}, - {"registeredAt", plansql::dateTime(plansql::wholeSeconds("registered_at"))}, - }; - return columns; -} - } // namespace -bool SampleModel::canTranslateSampleColumn(std::string_view column, ::morph::table::PlanUse /*use*/) { - return plansql::translatable(sampleSqlColumns(), column); -} - ::morph::table::Page SampleModel::pageSamples(std::vector const& sites, - ::morph::table::QueryPlan const& plan) { - auto const translation = plansql::translate(plan, sampleSqlColumns(), "id"); - if (!translation) { - throw ValidationError{"ListSamples: " + translation.error().message}; + ::morph::table::TableQuery const& query, + std::string_view action, + ::morph::table::ApplyOptions const& options) { + // Refuse a bad query before reading every row in scope. + if (auto const checked = ::morph::table::validate(query, sampleColumns(), options.limits, options.mayRead); + !checked) { + throw ValidationError{std::string{action} + ": " + checked.error().message}; } - std::string scope; + std::vector siteIds; for (SiteId const site : sites) { if (site.hasValue()) { - scope += (scope.empty() ? "site_id IN (" : ", ") + std::to_string(*site); + siteIds.push_back(*site); } } - scope = scope.empty() ? "0" : scope + ")"; - Lightweight::DataMapper mapper; - // One read transaction for the count and the page, so the total agrees with the rows. It is rolled back, never - // committed, and no write happens inside it. - Lightweight::SqlTransaction const reading{mapper.Connection(), Lightweight::SqlTransactionMode::ROLLBACK}; - auto const fetched = plansql::fetch(mapper, db::SampleRecord::TableName, "id", scope, *translation, plan); - ::morph::table::Page page; - page.offset = plan.offset; - page.total = fetched.total; - page.totalKind = ::morph::table::TotalKind::Exact; - for (std::int64_t const id : fetched.ids) { - page.rows.push_back(toView(loadSample(mapper, id))); + std::vector rows; + if (!siteIds.empty()) { + Lightweight::DataMapper mapper; + auto const records = mapper.Query() + .WhereIn(::Lightweight::FieldNameOf<&db::SampleRecord::siteId>, siteIds) + .All(); + rows.reserve(records.size()); + for (auto const& record : records) { + rows.push_back(toView(record)); + } } - return page; + auto page = ::morph::table::apply( + rows, [](SampleView const& sample) { return ::morph::table::RowId{*sample.id}; }, query, options); + if (!page) { + throw ValidationError{std::string{action} + ": " + page.error().message}; + } + return std::move(*page); } // An action handler: the registry calls it on the instance, like every other. // NOLINTNEXTLINE(readability-convert-member-functions-to-static) ::morph::table::Page SampleModel::execute(const ListSamples& action) { - auto const plan = ::morph::table::planQuery(action.query, sampleColumns(), {}, {}, {}, canTranslateSampleColumn); - if (!plan) { - throw ValidationError{"ListSamples: " + plan.error().message}; - } - return pageSamples(OrgModel::visibleSites(currentPrincipal()), *plan); + return pageSamples(OrgModel::visibleSites(currentPrincipal()), action.query); } namespace { @@ -353,26 +337,25 @@ namespace { } /// @brief The samples the caller can see at @p company that meet one condition on one column. +/// @param action The action named in a refusal. /// @param company The company. /// @param column The column's id. /// @param condition The condition. -/// @param limit How many rows the page holds; the page's total counts every match. -/// @return The page. -/// @throws ValidationError if the database cannot compare the operand. -[[nodiscard]] ::morph::table::Page samplesWhere(CompanyId company, std::string column, - ::morph::table::FilterEntry condition, +/// @param limit How many rows the page holds; the page's total counts every match, at any size. +/// @return The page, whose total is always present. +/// @throws ValidationError if the operand does not parse for the column. +[[nodiscard]] ::morph::table::Page samplesWhere(std::string_view action, CompanyId company, + std::string column, ::morph::table::FilterEntry condition, std::int64_t limit) { ::morph::table::TableQuery query; ::morph::table::ColumnFilter filter; filter.include.push_back(std::move(condition)); query.filters.columns.emplace(std::move(column), std::move(filter)); query.page.limit = limit; - auto const plan = - ::morph::table::planQuery(query, sampleColumns(), {}, {}, {}, SampleModel::canTranslateSampleColumn); - if (!plan) { - throw ValidationError{"samples: " + plan.error().message}; - } - return SampleModel::pageSamples(callerSitesAt(company), *plan); + // A count is exact at any size, so the total is never capped here. + ::morph::table::ApplyOptions options; + options.limits.totalCap = std::numeric_limits::max(); + return SampleModel::pageSamples(callerSitesAt(company), query, action, options); } } // namespace @@ -383,9 +366,10 @@ OpenWork SampleDirectoryModel::execute(const CountSamplesToVerify& a if (!action.validate()) { throw ValidationError{"CountSamplesToVerify: a company is required"}; } - auto const page = - samplesWhere(action.company, "state", ::morph::table::FilterEntry{.eq = std::string{"ToBeVerified"}}, 1); - return openWork(page.total.value_or(0)); + auto const page = samplesWhere("CountSamplesToVerify", action.company, "state", + ::morph::table::FilterEntry{.eq = std::string{"ToBeVerified"}}, 1); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): `samplesWhere` lifts the total cap, so the page carries its total. + return openWork(page.total.value()); } // An action handler: the registry calls it on the instance, like every other. @@ -397,9 +381,9 @@ SearchHits SampleDirectoryModel::execute(const SearchSamples& action if (action.query.empty()) { return hitsOf({}); } - auto const page = - samplesWhere(action.company, "reference", ::morph::table::FilterEntry{.startsWith = action.query}, - static_cast(kSearchHitLimit)); + auto const page = samplesWhere("SearchSamples", action.company, "reference", + ::morph::table::FilterEntry{.startsWith = action.query}, + static_cast(kSearchHitLimit)); std::vector found; for (SampleView const& sample : page.rows) { auto const site = OrgModel::findSite(sample.siteId); @@ -408,7 +392,8 @@ SearchHits SampleDirectoryModel::execute(const SearchSamples& action .screen = std::string{hit_screens::kSample}, .params = {{"sampleId", *sample.id}}}); } - return hitsOf(std::move(found), page.total.value_or(0)); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): `samplesWhere` lifts the total cap, so the page carries its total. + return hitsOf(std::move(found), page.total.value()); } SampleView SampleModel::execute(const ReceiveSample& action) { return transition(action, SampleState::Received); } diff --git a/examples/lims/ledger/include/lims/ledger/models/ledger_model.hpp b/examples/lims/ledger/include/lims/ledger/models/ledger_model.hpp index 0dc793d29..a79410733 100644 --- a/examples/lims/ledger/include/lims/ledger/models/ledger_model.hpp +++ b/examples/lims/ledger/include/lims/ledger/models/ledger_model.hpp @@ -163,31 +163,22 @@ class LedgerModel { /// @throws ValidationError if no company is named. ListEntriesResult execute(const ListEntries& action); - /// @brief Lists a page of a company's entries, sorted, filtered and counted in the database. - /// - /// The query is planned by `table::planQuery` and translated into one `SELECT` over the entries table, so the - /// cost follows the page, not the journal. The order ends with the entry's id. A sort or filter on `lines` or - /// `rate`, which the database cannot compare as the table engine does, is refused. The count and the page are - /// read in one transaction and the total is exact. + /// @brief Lists a page of a company's entries, sorted, filtered and counted by `table::apply`. /// @param action The company and the query. /// @return The page; none for a company the caller cannot see. /// @throws ValidationError if no company is named or the query is refused. ::morph::table::Page execute(const ListEntriesPage& action); - /// @brief Whether the database can sort or filter the journal by @p column. - /// @param column The column's id. - /// @param use What the column is wanted for. - /// @return `false` for `lines` and `rate`, and for a name that is no column. - [[nodiscard]] static bool canTranslateEntryColumn(std::string_view column, ::morph::table::PlanUse use); - - /// @brief Reads a page of @p company's entries for a validated plan, without checking who may see the company. + /// @brief Answers @p query over @p company's entries, without checking who may see the company: reads the + /// company's rows and runs the query over them with `table::apply`; the total is the count up to + /// `QueryLimits::totalCap` and omitted above it. /// @param company The company. - /// @param plan The plan from `table::planQuery`, made with `canTranslateEntryColumn`. - /// @return The page, with an exact total. - /// @throws ValidationError if the plan holds an operand the database cannot compare. + /// @param query The sort, filters and page. + /// @return The page. + /// @throws ValidationError if the query names a column the rows do not have, or exceeds the limits. /// @throws Lightweight::SqlException if a statement fails. [[nodiscard]] static ::morph::table::Page pageEntries(CompanyId company, - ::morph::table::QueryPlan const& plan); + ::morph::table::TableQuery const& query); /// @brief Records a posting the app's posting client sends, once per company and source key. /// @param action The request. diff --git a/examples/lims/ledger/src/models/ledger_entries.cpp b/examples/lims/ledger/src/models/ledger_entries.cpp index 4a5e3a3f8..f06600935 100644 --- a/examples/lims/ledger/src/models/ledger_entries.cpp +++ b/examples/lims/ledger/src/models/ledger_entries.cpp @@ -27,7 +27,6 @@ #include "lims/org/core/errors.hpp" #include "lims/org/core/model_support.hpp" #include "lims/org/core/money.hpp" -#include "lims/org/core/plan_sql.hpp" #include "lims/org/models/org_model.hpp" namespace lims { @@ -100,12 +99,14 @@ struct LoadedEntry { } /// @brief Maps an entry's rows to its view. -/// @param mapper The open mapper, for the account codes. /// @param entry The rows. +/// @param base The company's base currency. +/// @param accountCode The code of an account by id, or nothing for an account that does not exist. /// @return The view. /// @throws ValidationError if a row holds a state, currency or side outside its enumeration, or a line names an /// account that does not exist. -[[nodiscard]] JournalEntryView toView(Lightweight::DataMapper& mapper, LoadedEntry const& entry) { +template +[[nodiscard]] JournalEntryView toView(LoadedEntry const& entry, CurrencyCode base, AccountCode const& accountCode) { auto const& row = entry.header; int const state = row.state.Value(); int const currency = row.currency.Value(); @@ -114,7 +115,6 @@ struct LoadedEntry { } CompanyId const company{row.companyId.Value()}; auto const transaction = static_cast(currency); - CurrencyCode const base = companyCurrency(company); JournalEntryView view{ .id = JournalEntryId{static_cast(row.id.Value())}, .company = company, @@ -137,15 +137,13 @@ struct LoadedEntry { if (side != static_cast(PostingSide::Debit) && side != static_cast(PostingSide::Credit)) { throw ValidationError{"entry " + std::to_string(row.id.Value()) + " stores a line side out of range"}; } - auto const accounts = mapper.Query() - .Where(::Lightweight::FieldNameOf<&db::AccountRecord::id>, "=", line.account.Value()) - .All(); - if (accounts.empty()) { + std::optional code = accountCode(line.account.Value()); + if (!code.has_value()) { throw ValidationError{"entry " + std::to_string(row.id.Value()) + " has a line on account " + std::to_string(line.account.Value()) + ", which does not exist"}; } view.lines.push_back(PostingLine{ - .accountCode = std::string{accounts.front().code.Value().ToStringView()}, + .accountCode = std::move(*code), .side = static_cast(side), .amount = amountOf(line.amountNum.Value(), line.amountDen.Value(), transaction), .companyAmount = amountOf(line.companyNum.Value(), line.companyDen.Value(), base), @@ -154,6 +152,25 @@ struct LoadedEntry { return view; } +/// @brief Maps one entry's rows to its view, reading its company and its lines' accounts. +/// @param mapper The open mapper, for the account codes. +/// @param entry The rows. +/// @return The view. +/// @throws ValidationError as the overload above. +/// @throws NotFound if the entry's company does not exist. +[[nodiscard]] JournalEntryView toView(Lightweight::DataMapper& mapper, LoadedEntry const& entry) { + CurrencyCode const base = companyCurrency(CompanyId{entry.header.companyId.Value()}); + return toView(entry, base, [&mapper](std::int64_t account) -> std::optional { + auto const accounts = mapper.Query() + .Where(::Lightweight::FieldNameOf<&db::AccountRecord::id>, "=", account) + .All(); + if (accounts.empty()) { + return std::nullopt; + } + return std::string{accounts.front().code.Value().ToStringView()}; + }); +} + /// @brief The journal's columns as the table engine reflects them from `JournalEntryView`. /// @return One column per member, in member order. [[nodiscard]] std::vector<::morph::table::ColumnInfo> const& journalColumns() { @@ -167,29 +184,56 @@ struct LoadedEntry { return columns; } -/// @brief How the database reads each journal column it can filter and order by. -/// -/// `lines` is a serialisation of another table and `rate` is a quantity held as a numerator and denominator, whose -/// exact comparison would multiply two `int64` values in SQLite, which turns an overflowing product into a real; both -/// are refused. The enum columns are mapped to the enumerator's name, which is how the table engine holds them. -/// @return The columns by id. -[[nodiscard]] plansql::Columns const& journalSqlColumns() { - static plansql::Columns const columns{ - {"id", plansql::integer("id")}, - {"company", plansql::integer("company_id")}, - {"period", plansql::integer("period_id")}, - {"date", plansql::dateTime(plansql::wholeSeconds("date_ms"))}, - {"state", plansql::text(plansql::enumName("state", kMaxEntryState + 1))}, - {"sourceKey", plansql::storedText("source_key")}, - {"sourceReference", plansql::storedText("source_reference")}, - {"memo", plansql::storedText("memo")}, - {"currency", plansql::text(plansql::enumName("currency", kMaxCurrencyCode + 1))}, - {"reverses", plansql::integer("reverses_id")}, - {"reversedBy", plansql::integer("reversed_by_id")}, - {"createdBy", plansql::storedText("created_by")}, - {"postedBy", plansql::storedText("posted_by")}, +/// @brief Reads every entry of @p company with a fixed number of statements per chunk of entries, not per entry: +/// the headers in one query, the lines in chunks of entry ids, and the accounts once. +/// @param company The company. +/// @return Its entries, in the order the database returns the headers. +/// @throws NotFound if the company has entries and does not exist. +/// @throws ValidationError as `toView`. +[[nodiscard]] std::vector companyEntries(CompanyId company) { + // Bounded so one statement's parameter list stays well under the driver's limit. + constexpr std::size_t kIdsPerQuery = 500; + Lightweight::DataMapper mapper; + auto headers = mapper.Query() + .Where(::Lightweight::FieldNameOf<&db::EntryRecord::companyId>, "=", *company) + .All(); + std::vector entries; + if (headers.empty()) { + return entries; + } + CurrencyCode const base = companyCurrency(company); + std::map codes; + for (auto const& account : mapper.Query().All()) { + codes.emplace(static_cast(account.id.Value()), std::string{account.code.Value().ToStringView()}); + } + std::map> lines; + std::vector ids; + ids.reserve(kIdsPerQuery); + for (std::size_t first = 0; first < headers.size(); first += kIdsPerQuery) { + ids.clear(); + for (std::size_t i = first; i < std::min(first + kIdsPerQuery, headers.size()); ++i) { + ids.push_back(static_cast(headers.at(i).id.Value())); + } + for (auto const& line : mapper.Query() + .WhereIn(::Lightweight::FieldNameOf<&db::EntryLineRecord::entry>, ids) + .All()) { + lines[line.entry.Value()].push_back(line); + } + } + auto const accountCode = [&codes](std::int64_t account) -> std::optional { + auto const found = codes.find(account); + return found == codes.end() ? std::nullopt : std::optional{found->second}; }; - return columns; + entries.reserve(headers.size()); + for (auto const& header : headers) { + LoadedEntry entry{.header = header, .lines = {}}; + if (auto const found = lines.find(static_cast(entry.header.id.Value())); found != lines.end()) { + entry.lines = std::move(found->second); + std::ranges::sort(entry.lines, {}, [](db::EntryLineRecord const& line) { return line.position.Value(); }); + } + entries.push_back(toView(entry, base, accountCode)); + } + return entries; } /// @brief Changes the entry row @p entryId only where it still holds the state the caller read. @@ -522,40 +566,20 @@ ListEntriesResult LedgerModel::execute(const ListEntries& action) { if (std::ranges::find(visibleCompanies, action.company) == visibleCompanies.end()) { return result; } - Lightweight::DataMapper mapper; - for (auto const& header : mapper.Query() - .Where(::Lightweight::FieldNameOf<&db::EntryRecord::companyId>, "=", *action.company) - .All()) { - result.entries.push_back(toView(mapper, loadWritten(mapper, static_cast(header.id.Value())))); - } + result.entries = companyEntries(action.company); std::ranges::sort(result.entries, {}, [](JournalEntryView const& entry) { return *entry.id; }); return result; } -bool LedgerModel::canTranslateEntryColumn(std::string_view column, ::morph::table::PlanUse /*use*/) { - return plansql::translatable(journalSqlColumns(), column); -} - ::morph::table::Page LedgerModel::pageEntries(CompanyId company, - ::morph::table::QueryPlan const& plan) { - auto const translation = plansql::translate(plan, journalSqlColumns(), "id"); - if (!translation) { - throw ValidationError{"ListEntriesPage: " + translation.error().message}; - } - Lightweight::DataMapper mapper; - // One read transaction for the count and the page, so the total agrees with the rows. It is rolled back, never - // committed, and no write happens inside it. - Lightweight::SqlTransaction const reading{mapper.Connection(), Lightweight::SqlTransactionMode::ROLLBACK}; - auto const fetched = plansql::fetch(mapper, db::EntryRecord::TableName, "id", - "company_id = " + std::to_string(*company), *translation, plan); - ::morph::table::Page page; - page.offset = plan.offset; - page.total = fetched.total; - page.totalKind = ::morph::table::TotalKind::Exact; - for (std::int64_t const id : fetched.ids) { - page.rows.push_back(toView(mapper, loadWritten(mapper, id))); - } - return page; + ::morph::table::TableQuery const& query) { + auto const rows = companyEntries(company); + auto page = ::morph::table::apply( + rows, [](JournalEntryView const& entry) { return ::morph::table::RowId{*entry.id}; }, query); + if (!page) { + throw ValidationError{"ListEntriesPage: " + page.error().message}; + } + return std::move(*page); } // An action handler: the registry calls it on the instance, like every other. @@ -564,18 +588,18 @@ ::morph::table::Page LedgerModel::execute(const ListEntriesPag if (!action.validate()) { throw ValidationError{"ListEntriesPage: a company is required"}; } - auto const plan = ::morph::table::planQuery(action.query, journalColumns(), {}, {}, {}, canTranslateEntryColumn); - if (!plan) { - throw ValidationError{"ListEntriesPage: " + plan.error().message}; + auto const checked = ::morph::table::validate(action.query, journalColumns()); + if (!checked) { + throw ValidationError{"ListEntriesPage: " + checked.error().message}; } auto const visibleCompanies = OrgModel::visibleCompanies(currentPrincipal()); if (std::ranges::find(visibleCompanies, action.company) == visibleCompanies.end()) { ::morph::table::Page empty; - empty.offset = plan->offset; + empty.offset = checked->page.offset; empty.total = 0; return empty; } - return pageEntries(action.company, *plan); + return pageEntries(action.company, action.query); } // An action handler: the registry calls it on the instance, like every other. diff --git a/examples/lims/org/include/lims/org/core/plan_sql.hpp b/examples/lims/org/include/lims/org/core/plan_sql.hpp deleted file mode 100644 index 0d7f72a05..000000000 --- a/examples/lims/org/include/lims/org/core/plan_sql.hpp +++ /dev/null @@ -1,657 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "lims/org/core/errors.hpp" -#include "lims/org/core/model_support.hpp" - -/// @file -/// Translates a `morph::table::QueryPlan` into SQLite for the lims models that page a table in the database. -/// -/// The translation keeps the table engine's meaning of a query (docs/spec/table/database_pages.md): empty cells sort -/// after valid ones in either direction, no operator but `IsEmpty` and `NotEmpty` matches an empty cell, an exclude -/// keeps the rows whose cell is empty, integer operands are never rounded, a date-time is compared by its whole UTC -/// second, and text is compared and ordered by the default collator's fold. SQLite has no such fold, so it is spelled -/// out in the statement; a text column whose store comparison cannot be made to match is left out of the column map -/// and so refused. -/// -/// The statement text is built from the model's own column mapping, enumerator names and the clamped numbers of the -/// plan; nothing a client sent is written into it. Every operand a client sent is a `?` in the statement and a -/// value in `Translation::params`, bound when the statement runs. A text operand holding a NUL byte is refused, since -/// SQLite's `length` and `instr` stop at it and would not compare what the table engine compares. - -namespace lims::plansql { - -/// @brief How one reflected column of a row type is read in SQL. -struct Column { - /// @brief The kind the table engine gives the column: `Integer`, `DateTime` or `Text`. - ::morph::table::ColumnKind kind = ::morph::table::ColumnKind::Integer; - /// @brief The SQL expression of the cell, `NULL` when the cell is empty. An integer column's value is an integer, - /// a - /// date-time column's value is whole UTC seconds, and a text column's value is the text, `NULL` for the - /// empty string. - std::string expr; -}; - -/// @brief The translatable columns of a row type, by column id. -using Columns = std::map>; - -/// @brief A plan as the parts of a `SELECT`. -struct Translation { - /// @brief The filter, a SQL boolean that is never `NULL`. - std::string where; - /// @brief The `ORDER BY` clause, total: it ends with the row key. - std::string order; - /// @brief The values of the `?` markers in `where`, in the order the markers appear. - std::vector params; - /// @brief The text expressions `where` and `order` compare by the collator's fold. `fetch` computes the fold of - /// the one at index `i` as the column `detail::foldedName(i)`, which is what `where` and `order` name. - std::vector folded; -}; - -/// @brief The ids a page holds and the size of the filtered view. -struct Fetched { - /// @brief The page's row keys, in order. - std::vector ids; - /// @brief The rows in the whole filtered view. - std::int64_t total = 0; -}; - -namespace detail { - -/// @brief @p text as a SQL string literal, for text the code itself supplies (the fold's byte pairs and enumerator -/// names). An operand a client sent is never written this way; it is bound. -/// @param text The text, without a NUL byte. -/// @return The literal. -[[nodiscard]] inline std::string literal(std::string_view text) { - std::string out = "'"; - for (char const character : text) { - if (character == '\'') { - out += '\''; - } - out += character; - } - out += '\''; - return out; -} - -/// @brief The default collator's fold, as `replace` calls over SQLite's `lower`. -/// -/// The collator lowers ASCII `A`-`Z` and Latin-1 `À`-`Þ` except `×`, and copies every other byte. SQLite's `lower` -/// lowers ASCII only, and each Latin-1 letter is a two-byte UTF-8 sequence `C3 80` to `C3 9E`, which one `replace` -/// each lowers. A SQLite built with ICU lowers more than the collator does; the conformance run in the tests is what -/// notices that. -/// @return The capital's bytes and the small letter's bytes, one pair per `replace`. -[[nodiscard]] inline std::vector> const& foldPairs() { - static std::vector> const pairs = [] { - std::vector> out; - for (int second = 0x80; second <= 0x9E; ++second) { - if (second == 0x97) { - continue; - } - out.emplace_back(std::string{'\xC3', static_cast(second)}, - std::string{'\xC3', static_cast(second + 0x20)}); - } - return out; - }(); - return pairs; -} - -/// @brief The most `replace` calls one stage of the fold nests. -/// -/// SQLite before 3.46 parses with a fixed stack of 100 entries and a nested call takes three or four of them, so the -/// thirty calls of the fold do not parse as one expression there; written in stages of ten, each stage nests eleven. -inline constexpr std::size_t kFoldStep = 10; - -/// @brief The number of stages the fold is written in. -/// @return The count. -[[nodiscard]] inline std::size_t foldStages() { return (foldPairs().size() + kFoldStep - 1) / kFoldStep; } - -/// @brief The column one stage of the fold computes for one folded expression. -/// @param index The expression's index in `Translation::folded`. -/// @param stage The stage. -/// @return The column name. -[[nodiscard]] inline std::string foldColumn(std::size_t index, std::size_t stage) { - return "fold" + std::to_string(index) + "_" + std::to_string(stage); -} - -/// @brief The column holding the whole fold of one folded expression: its column in the last stage. -/// @param index The expression's index in `Translation::folded`. -/// @return The column name. -[[nodiscard]] inline std::string foldedName(std::size_t index) { return foldColumn(index, foldStages() - 1); } - -/// @brief The `WITH` clause that adds the fold of each of @p folded to the rows of @p table, as `foldedName(i)`. -/// @param table The table. -/// @param folded The text expressions over the table's columns. -/// @param source Receives the name of the last stage, which the statement reads instead of @p table. -/// @return The clause, ending with a space. -[[nodiscard]] inline std::string foldClause(std::string_view table, std::vector const& folded, - std::string& source) { - auto const& pairs = foldPairs(); - std::string clause = "WITH "; - std::string previous{table}; - for (std::size_t stage = 0; stage < foldStages(); ++stage) { - std::string const name = "fold_stage" + std::to_string(stage); - clause += (stage == 0 ? "" : ", ") + name + " AS (SELECT *"; - std::size_t index = 0; - for (std::string const& expression : folded) { - std::string expr = stage == 0 ? "lower(" + expression + ")" : foldColumn(index, stage - 1); - for (auto const& [capital, lowered] : - pairs | std::views::drop(stage * kFoldStep) | std::views::take(kFoldStep)) { - std::string wrapped = "replace("; - wrapped += expr; - wrapped += ", "; - wrapped += literal(capital); - wrapped += ", "; - wrapped += literal(lowered); - wrapped += ')'; - expr = std::move(wrapped); - } - clause += ", " + expr + " AS " + foldColumn(index, stage); - ++index; - } - clause += " FROM " + previous + ")"; - previous = name; - } - source = previous; - return clause + " "; -} - -/// @brief Collects the operands of a statement as it is written: each call returns the `?` marker and keeps the value. -/// -/// The markers appear in the statement in the order the calls are made, so a caller sequences the calls in the order -/// the pieces are concatenated. -class Binds { -public: - /// @brief Adds an integer operand. - /// @param value The value. - /// @return `?`. - [[nodiscard]] std::string integer(std::int64_t value) { - _values.emplace_back(Lightweight::SqlVariant::InnerType{std::in_place_type, value}); - return "?"; - } - - /// @brief Adds a text operand. - /// @param value The text. - /// @return `?`. - [[nodiscard]] std::string text(std::string value) { - _values.emplace_back(Lightweight::SqlVariant::InnerType{std::in_place_type, std::move(value)}); - return "?"; - } - - /// @brief Hands over the collected values. - /// @return They, in marker order. - [[nodiscard]] std::vector take() { return std::move(_values); } - - /// @brief Adds a text expression to compare by the collator's fold. - /// @param expr The text expression. - /// @return The name of the column `fetch` computes the fold into. - [[nodiscard]] std::string folded(std::string const& expr) { - auto const found = std::ranges::find(_folded, expr); - auto const index = static_cast(found - _folded.begin()); - if (found == _folded.end()) { - _folded.push_back(expr); - } - return foldedName(index); - } - - /// @brief Hands over the expressions added by `folded`. - /// @return They, in the order of their column indices. - [[nodiscard]] std::vector takeFolded() { return std::move(_folded); } - -private: - std::vector _values; - std::vector _folded; -}; - -/// @brief Floor of @p numerator over @p denominator. -/// @param numerator The numerator. -/// @param denominator The denominator, positive. -/// @return The greatest integer not above the quotient. -[[nodiscard]] constexpr std::int64_t floorDivide(std::int64_t numerator, std::int64_t denominator) noexcept { - std::int64_t quotient = numerator / denominator; - if (numerator % denominator != 0 && numerator < 0) { - --quotient; - } - return quotient; -} - -/// @brief An integer column compared with an exact operand, without rounding the operand. -/// -/// An integral operand compares as it is. A non-integral one lies between two integers: nothing equals it, and -/// "below" and "above" are decided by its floor. -/// @param op The operator: `Eq`, `Ne`, `Lt`, `Le`, `Gt` or `Ge`. -/// @param operand The operand. -/// @param expr The column's integer expression. -/// @param binds Receives the operand. -/// @return The SQL boolean, `NULL` for an empty cell. -[[nodiscard]] inline std::string integerCompare(::morph::table::FilterOp op, ::morph::math::Rational const& operand, - std::string const& expr, Binds& binds) { - using Op = ::morph::table::FilterOp; - bool const whole = operand.denominator == 1; - std::int64_t const floored = floorDivide(operand.numerator, operand.denominator); - switch (op) { - case Op::Eq: - return whole ? "(" + expr + " = " + binds.integer(operand.numerator) + ")" : "0"; - case Op::Ne: - return whole ? "(" + expr + " <> " + binds.integer(operand.numerator) + ")" : "(" + expr + " IS NOT NULL)"; - case Op::Lt: - return whole ? "(" + expr + " < " + binds.integer(operand.numerator) + ")" - : "(" + expr + " <= " + binds.integer(floored) + ")"; - case Op::Le: - return "(" + expr + " <= " + binds.integer(floored) + ")"; - case Op::Gt: - return "(" + expr + " > " + binds.integer(floored) + ")"; - case Op::Ge: - return whole ? "(" + expr + " >= " + binds.integer(operand.numerator) + ")" - : "(" + expr + " > " + binds.integer(floored) + ")"; - case Op::Between: - case Op::Contains: - case Op::StartsWith: - case Op::EndsWith: - case Op::IsEmpty: - case Op::NotEmpty: - default: - return "0"; - } -} - -/// @brief A text column compared with an operand. -/// @param condition The condition; its value is the folded operand, or the raw one when case-sensitive. -/// @param column The column. -/// @param binds Receives the operand. -/// @return The SQL boolean, `NULL` for an empty cell; or the error when the operand cannot be compared. -[[nodiscard]] inline std::expected textCondition( - ::morph::table::PlannedCondition const& condition, Column const& column, Binds& binds) { - using Op = ::morph::table::FilterOp; - auto const* const needle = std::get_if(&condition.value); - if (needle == nullptr) { - return std::unexpected(::morph::table::TableError{.code = ::morph::table::TableErrorCode::InvalidValue, - .column = condition.column, - .message = "a text condition has no text operand"}); - } - if (needle->find('\0') != std::string::npos) { - return std::unexpected( - ::morph::table::TableError{.code = ::morph::table::TableErrorCode::InvalidValue, - .column = condition.column, - .message = "a text operand holds a NUL byte, which the store cannot compare"}); - } - if (needle->empty()) { - // Every non-empty cell contains, starts with and ends with the empty text; none equals it. - return condition.op == Op::Eq ? std::string{"0"} : "(" + column.expr + " IS NOT NULL)"; - } - std::string const cell = condition.caseSensitive ? column.expr : binds.folded(column.expr); - switch (condition.op) { - case Op::Eq: - return "(" + cell + " = " + binds.text(*needle) + ")"; - case Op::Ne: - return "(" + cell + " <> " + binds.text(*needle) + ")"; - case Op::Contains: - return "(instr(" + cell + ", " + binds.text(*needle) + ") > 0)"; - case Op::StartsWith: { - // The markers are taken in the order they are written. - std::string const length = binds.text(*needle); - std::string const text = binds.text(*needle); - return "(substr(" + cell + ", 1, length(" + length + ")) = " + text + ")"; - } - case Op::EndsWith: { - std::string const atLeast = binds.text(*needle); - std::string const from = binds.text(*needle); - std::string const text = binds.text(*needle); - return "(length(" + cell + ") >= length(" + atLeast + ") AND substr(" + cell + ", -length(" + from + - ")) = " + text + ")"; - } - case Op::Lt: - case Op::Le: - case Op::Gt: - case Op::Ge: - case Op::Between: - case Op::IsEmpty: - case Op::NotEmpty: - default: - return std::unexpected( - ::morph::table::TableError{.code = ::morph::table::TableErrorCode::UnsupportedOperator, - .column = condition.column, - .message = "operator not defined for column " + condition.column}); - } -} - -/// @brief One condition as a SQL boolean that is never `NULL`: true when the cell is present and meets it. -/// @param condition The condition. -/// @param columns The translatable columns. -/// @param binds Receives the operands. -/// @return The boolean, or the error naming the column. -[[nodiscard]] inline std::expected conditionSql( - ::morph::table::PlannedCondition const& condition, Columns const& columns, Binds& binds) { - using Op = ::morph::table::FilterOp; - auto const found = columns.find(condition.column); - if (found == columns.end()) { - return std::unexpected(::morph::table::TableError{ - .code = ::morph::table::TableErrorCode::Unavailable, - .column = condition.column, - .message = "column " + condition.column + " cannot be filtered in the database"}); - } - Column const& column = found->second; - if (condition.op == Op::IsEmpty) { - return "(" + column.expr + " IS NULL)"; - } - if (condition.op == Op::NotEmpty) { - return "(" + column.expr + " IS NOT NULL)"; - } - std::string sql; - switch (column.kind) { - case ::morph::table::ColumnKind::Integer: - case ::morph::table::ColumnKind::Key: { - auto const* const value = std::get_if<::morph::math::Rational>(&condition.value); - auto const* const upper = std::get_if<::morph::math::Rational>(&condition.upper); - if (value == nullptr || (condition.op == Op::Between && upper == nullptr)) { - return std::unexpected(::morph::table::TableError{.code = ::morph::table::TableErrorCode::InvalidValue, - .column = condition.column, - .message = "an integer condition has no operand"}); - } - if (condition.op == Op::Between) { - std::string const low = integerCompare(Op::Ge, *value, column.expr, binds); - std::string const high = integerCompare(Op::Le, *upper, column.expr, binds); - sql = "(" + low + " AND " + high + ")"; - } else { - sql = integerCompare(condition.op, *value, column.expr, binds); - } - break; - } - case ::morph::table::ColumnKind::DateTime: { - auto const* const value = std::get_if(&condition.value); - auto const* const upper = std::get_if(&condition.upper); - if (value == nullptr || (condition.op == Op::Between && upper == nullptr)) { - return std::unexpected(::morph::table::TableError{.code = ::morph::table::TableErrorCode::InvalidValue, - .column = condition.column, - .message = "a date-time condition has no operand"}); - } - switch (condition.op) { - case Op::Eq: - sql = "(" + column.expr + " = " + binds.integer(*value) + ")"; - break; - case Op::Ne: - sql = "(" + column.expr + " <> " + binds.integer(*value) + ")"; - break; - case Op::Lt: - sql = "(" + column.expr + " < " + binds.integer(*value) + ")"; - break; - case Op::Le: - sql = "(" + column.expr + " <= " + binds.integer(*value) + ")"; - break; - case Op::Gt: - sql = "(" + column.expr + " > " + binds.integer(*value) + ")"; - break; - case Op::Ge: - sql = "(" + column.expr + " >= " + binds.integer(*value) + ")"; - break; - case Op::Between: { - std::string const low = binds.integer(*value); - std::string const high = binds.integer(*upper); - sql = "(" + column.expr + " BETWEEN " + low + " AND " + high + ")"; - break; - } - case Op::Contains: - case Op::StartsWith: - case Op::EndsWith: - case Op::IsEmpty: - case Op::NotEmpty: - default: - sql = "0"; - break; - } - break; - } - case ::morph::table::ColumnKind::Text: { - auto text = textCondition(condition, column, binds); - if (!text) { - return std::unexpected(std::move(text.error())); - } - sql = std::move(*text); - break; - } - case ::morph::table::ColumnKind::Decimal: - case ::morph::table::ColumnKind::Quantity: - case ::morph::table::ColumnKind::Number: - case ::morph::table::ColumnKind::Date: - case ::morph::table::ColumnKind::Bool: - case ::morph::table::ColumnKind::Custom: - default: - return std::unexpected(::morph::table::TableError{ - .code = ::morph::table::TableErrorCode::Unavailable, - .column = condition.column, - .message = "column " + condition.column + " cannot be filtered in the database"}); - } - // A cell that is empty makes the comparison NULL, and an empty cell meets no condition. - return "COALESCE(" + sql + ", 0)"; -} - -/// @brief One column's filter as a SQL boolean that is never `NULL`. -/// @param filter The filter. -/// @param columns The translatable columns. -/// @return The boolean, or the error naming the column. -[[nodiscard]] inline std::expected columnFilter( - ::morph::table::PlannedColumnFilter const& filter, Columns const& columns, Binds& binds) { - std::vector parts; - if (!filter.include.empty()) { - std::string joined; - for (auto const& entry : filter.include) { - auto sql = conditionSql(entry, columns, binds); - if (!sql) { - return std::unexpected(std::move(sql.error())); - } - if (!joined.empty()) { - joined += filter.combine == ::morph::table::Combine::All ? " AND " : " OR "; - } - joined += *sql; - } - parts.push_back("(" + joined + ")"); - } - for (auto const& entry : filter.exclude) { - auto sql = conditionSql(entry, columns, binds); - if (!sql) { - return std::unexpected(std::move(sql.error())); - } - // The row is rejected when the cell is present and meets the condition; an empty cell is kept. - parts.push_back("NOT " + *sql); - } - std::string out; - for (auto const& part : parts) { - out += out.empty() ? part : " AND " + part; - } - return out.empty() ? std::string{"1"} : "(" + out + ")"; -} - -} // namespace detail - -/// @brief The SQL expression of an integer-valued enum column as the enumerator's name. -/// -/// The table engine holds an enum as the name glaze writes for it, so a column filtered or ordered as text is mapped -/// to that name rather than ordered by its ordinal. -/// @tparam Enum An enumeration with a glaze name for each value in `[0, count)`. -/// @param column The column holding the ordinal. -/// @param count The number of enumerators. -/// @return The `CASE` expression; `NULL` for an ordinal outside the enumeration. -template -[[nodiscard]] std::string enumName(std::string_view column, int count) { - std::string out = "CASE " + std::string{column}; - for (int ordinal = 0; ordinal < count; ++ordinal) { - std::string json; - if (glz::write_json(static_cast(ordinal), json)) { - continue; - } - std::string_view name = json; - name.remove_prefix(1); - name.remove_suffix(1); - out += " WHEN " + std::to_string(ordinal) + " THEN " + detail::literal(name); - } - return out + " END"; -} - -/// @brief The whole UTC second of an instant held in epoch milliseconds, as the table engine floors it. -/// @param column The column holding milliseconds. -/// @return The SQL expression. -[[nodiscard]] inline std::string wholeSeconds(std::string_view column) { - std::string const ms{column}; - return "((" + ms + " - (((" + ms + " % 1000) + 1000) % 1000)) / 1000)"; -} - -/// @brief An integer column. -/// @param expr Its SQL expression, `NULL` when the cell is empty. -/// @return The column. -[[nodiscard]] inline Column integer(std::string expr) { - return Column{.kind = ::morph::table::ColumnKind::Integer, .expr = std::move(expr)}; -} - -/// @brief A date-time column. -/// @param expr Its SQL expression in whole UTC seconds. -/// @return The column. -[[nodiscard]] inline Column dateTime(std::string expr) { - return Column{.kind = ::morph::table::ColumnKind::DateTime, .expr = std::move(expr)}; -} - -/// @brief A text column. -/// @param expr Its SQL expression, `NULL` for the empty text. -/// @return The column. -[[nodiscard]] inline Column text(std::string expr) { - return Column{.kind = ::morph::table::ColumnKind::Text, .expr = std::move(expr)}; -} - -/// @brief The text of a stored string column, with the empty string as an empty cell. -/// @param column The column. -/// @return The column. -[[nodiscard]] inline Column storedText(std::string_view column) { - return text("NULLIF(" + std::string{column} + ", '')"); -} - -/// @brief Whether the database can filter and order by @p column. -/// @param columns The translatable columns. -/// @param column The column's id. -/// @return `true` when it is one of them. -[[nodiscard]] inline bool translatable(Columns const& columns, std::string_view column) { - return columns.contains(column); -} - -/// @brief Translates @p plan. -/// @param plan The validated plan. -/// @param columns The translatable columns; the plan names no other. -/// @param rowKey The SQL name of the unique row key, which ends the ordering ascending. -/// @return The filter and the ordering, or the error naming a column or operand that cannot be written. -[[nodiscard]] inline std::expected translate( - ::morph::table::QueryPlan const& plan, Columns const& columns, std::string_view rowKey) { - Translation out; - detail::Binds binds; - std::vector clauses; - for (auto const& filter : plan.filters) { - auto sql = detail::columnFilter(filter, columns, binds); - if (!sql) { - return std::unexpected(std::move(sql.error())); - } - clauses.push_back(std::move(*sql)); - } - for (auto const& group : plan.groups) { - // A row meets a group when its entries are met on any of the group's columns; no usable column meets none. - std::string any; - for (auto const& filter : group.columns) { - auto sql = detail::columnFilter(filter, columns, binds); - if (!sql) { - return std::unexpected(std::move(sql.error())); - } - any += any.empty() ? *sql : " OR " + *sql; - } - clauses.push_back(any.empty() ? std::string{"0"} : "(" + any + ")"); - } - for (auto const& clause : clauses) { - out.where += out.where.empty() ? clause : " AND " + clause; - } - if (out.where.empty()) { - out.where = "1"; - } - out.order = "ORDER BY "; - for (auto const& key : plan.sort) { - auto const found = columns.find(key.column); - if (found == columns.end()) { - return std::unexpected( - ::morph::table::TableError{.code = ::morph::table::TableErrorCode::Unavailable, - .column = key.column, - .message = "column " + key.column + " cannot be ordered in the database"}); - } - Column const& column = found->second; - std::string const value = - column.kind == ::morph::table::ColumnKind::Text ? binds.folded(column.expr) : column.expr; - // Empty cells come last in either direction, then the value. - out.order += "(" + column.expr + " IS NULL), " + value + - (key.dir == ::morph::table::SortDirection::Ascending ? " ASC, " : " DESC, "); - } - out.order += std::string{rowKey} + " ASC"; - out.params = binds.take(); - out.folded = binds.takeFolded(); - return out; -} - -/// @brief Counts the filtered view and reads one page of its row keys, from one connection. -/// -/// The caller opens a transaction on @p mapper before calling, so the count and the page see one state of the table. -/// @param mapper The open mapper. -/// @param table The table. -/// @param rowKey The unique row key column. -/// @param scope A SQL boolean the model's own scope (company, visibility) contributes; it holds no operand markers. -/// @param translation The translated plan. -/// @param plan The plan, for its offset and limit. -/// @return The count of the filtered view and the keys of the page; no keys when the limit is zero. -/// @throws Conflict if the database is busy or locked. -/// @throws Lightweight::SqlException if a statement fails for another reason. -[[nodiscard]] inline Fetched fetch(Lightweight::DataMapper& mapper, std::string_view table, std::string_view rowKey, - std::string_view scope, Translation const& translation, - ::morph::table::QueryPlan const& plan) { - std::string source{table}; - std::string const with = - translation.folded.empty() ? std::string{} : detail::foldClause(table, translation.folded, source); - std::string const from = " FROM " + source + " WHERE (" + std::string{scope} + ") AND " + translation.where; - Fetched out; - try { - { - Lightweight::SqlStatement counting{mapper.Connection()}; - counting.Prepare(with + "SELECT COUNT(*)" + from); - auto cursor = counting.ExecuteWithVariants(translation.params); - if (cursor.FetchRow()) { - out.total = cursor.GetColumn(1); - } - } - if (plan.limit <= 0) { - return out; - } - Lightweight::SqlStatement paging{mapper.Connection()}; - paging.Prepare(with + "SELECT " + std::string{rowKey} + from + " " + translation.order + " LIMIT " + - std::to_string(plan.limit) + " OFFSET " + std::to_string(plan.offset)); - auto cursor = paging.ExecuteWithVariants(translation.params); - while (cursor.FetchRow()) { - out.ids.push_back(cursor.GetColumn(1)); - } - } catch (Lightweight::SqlException const& error) { - if (!isBusy(error)) { - throw; - } - throw Conflict{"the database is busy with another write; try again"}; - } - return out; -} - -} // namespace lims::plansql diff --git a/examples/lims/tests/lims_test_support.hpp b/examples/lims/tests/lims_test_support.hpp index efedd3757..c2314f42d 100644 --- a/examples/lims/tests/lims_test_support.hpp +++ b/examples/lims/tests/lims_test_support.hpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -120,14 +119,6 @@ class LabFixture : public ::morph::ladder::testkit::DbFixture { std::chrono::hours{hour}, std::chrono::minutes{0}, std::chrono::seconds{0}}; } -/// @brief The whole UTC second of @p at as ISO 8601 text, the form the table engine's date parser reads; an operand -/// built from it falls exactly on the second the engine floors the instant to. -/// @param at The instant. -/// @return For example `2026-11-10T09:00:00Z`. -[[nodiscard]] inline std::string isoSecond(morph::time::Timestamp const& at) { - return std::format("{:%Y-%m-%dT%H:%M:%SZ}", std::chrono::floor((*at).value)); -} - /// @brief A signed session for @p principal. /// @param issuer The issuer. /// @param principal The principal. diff --git a/examples/lims/tests/migration_probe.hpp b/examples/lims/tests/migration_probe.hpp index 3a7b3a4d1..1d390ed41 100644 --- a/examples/lims/tests/migration_probe.hpp +++ b/examples/lims/tests/migration_probe.hpp @@ -3,10 +3,14 @@ #include #include +#include +#include +#include #include #include #include #include +#include #include #include "testkit/db_fixture.hpp" @@ -28,7 +32,7 @@ class MigrationProbe { explicit MigrationProbe(std::uint64_t lastApplied) { removeFile(); ::Lightweight::SqlConnection::SetDefaultConnectionString( - ::Lightweight::SqlConnectionString{std::string{"DRIVER=SQLite3;Database="} + kFile}); + ::Lightweight::SqlConnectionString{probeConnectionString()}); auto& migrations = ::Lightweight::SqlMigration::MigrationManager::GetInstance(); migrations.CloseDataMapper(); migrations.CreateMigrationHistory(); @@ -59,6 +63,33 @@ class MigrationProbe { private: static constexpr char const* kFile = "lims_migration_probe.db"; + /// @brief The shared test database's connection string with its database replaced by the probe file, so the probe + /// uses the driver `ODBC_CONNECTION_STRING` names, as `DbFixture` does. + /// @return The connection string. + [[nodiscard]] static std::string probeConnectionString() { + std::string const shared = ::morph::ladder::testkit::DbFixture::computeConnectionString( + std::getenv("ODBC_CONNECTION_STRING")); // NOLINT(concurrency-mt-unsafe): nothing sets it + std::string out; + std::size_t begin = 0; + while (begin < shared.size()) { + auto end = shared.find(';', begin); + if (end == std::string::npos) { + end = shared.size(); + } + std::string const part = shared.substr(begin, end - begin); + auto const key = part.substr(0, part.find('=')); + bool const isDatabase = + key.size() == 8 && std::ranges::equal(key, std::string_view{"database"}, [](char lhs, char rhs) { + return std::tolower(static_cast(lhs)) == rhs; + }); + if (!isDatabase && !part.empty()) { + out += part + ";"; + } + begin = end + 1; + } + return out + "Database=" + kFile; + } + /// @brief Deletes the probe file; a file still open elsewhere is left for the next probe to replace. static void removeFile() { std::error_code ignored; diff --git a/examples/lims/tests/test_ledger_entries.cpp b/examples/lims/tests/test_ledger_entries.cpp index 2dd908250..8165cd965 100644 --- a/examples/lims/tests/test_ledger_entries.cpp +++ b/examples/lims/tests/test_ledger_entries.cpp @@ -7,20 +7,16 @@ #include #include #include -#include #include #include #include #include #include #include -#include #include #include -#include #include #include -#include #include #include #include @@ -1448,343 +1444,10 @@ void writeJournal(lims::PeriodId period, std::vector const& rows) { } } -/// @brief The date-time queries the standard corpus cannot make: its operands are the cells' own text, and a date-time -/// cell's text is not a date the parser reads. The operands are the whole seconds of the rows' own dates, so -/// every equality, bound and tie falls on a boundary, and a few instants that match no row. -/// @param entries The journal. -/// @return The queries. -[[nodiscard]] std::vector dateQueries(std::vector const& entries) { - using morph::table::ColumnFilter; - using morph::table::FilterEntry; - using morph::table::SortDirection; - using morph::table::SortKey; - using morph::table::TableQuery; - std::vector queries; - auto const filtered = [&](std::string const& column, FilterEntry entry, bool asExclude) { - TableQuery query; - ColumnFilter filter; - (asExclude ? filter.exclude : filter.include).push_back(std::move(entry)); - query.filters.columns.emplace(column, std::move(filter)); - query.sort = {SortKey{.column = "date", .dir = SortDirection::Descending}}; - queries.push_back(std::move(query)); - }; - std::vector instants{"2026-11-10T09:00:00.500Z", "2026-11-11", "1969-12-08T00:00:00Z"}; - for (auto const& entry : entries) { - auto const second = lims::test::isoSecond(entry.date); - if (std::ranges::find(instants, second) == instants.end()) { - instants.push_back(second); - } - } - for (bool const asExclude : {false, true}) { - for (std::string const& instant : instants) { - filtered("date", FilterEntry{.eq = instant}, asExclude); - filtered("date", FilterEntry{.ne = instant}, asExclude); - filtered("date", FilterEntry{.lt = instant}, asExclude); - filtered("date", FilterEntry{.le = instant}, asExclude); - filtered("date", FilterEntry{.gt = instant}, asExclude); - filtered("date", FilterEntry{.ge = instant}, asExclude); - filtered("date", FilterEntry{.between = std::array{instant, "2026-11-12"}}, asExclude); - } - } - TableQuery ties; - ties.sort = {SortKey{.column = "date", .dir = SortDirection::Ascending}}; - queries.push_back(ties); - ties.sort = {SortKey{.column = "memo", .dir = SortDirection::Descending}, - SortKey{.column = "date", .dir = SortDirection::Ascending}}; - queries.push_back(ties); - return queries; -} - -/// @brief Quick-search group queries over the journal's text columns that the database can compare. The standard -/// corpus's group spans every text column, `lines` among them, and is refused whole. -/// @return The queries. -[[nodiscard]] std::vector groupQueries() { - using morph::table::FilterEntry; - using morph::table::GroupFilter; - using morph::table::TableQuery; - std::vector queries; - std::vector const columns{"sourceKey", "sourceReference", "memo", "state", - "currency", "createdBy", "postedBy"}; - auto const grouped = [&](morph::table::Combine combine, std::vector entries) { - TableQuery query; - query.filters.groups.push_back( - GroupFilter{.columns = columns, .combine = combine, .include = std::move(entries)}); - queries.push_back(std::move(query)); - }; - grouped(morph::table::Combine::Any, {FilterEntry{.contains = "a"}}); - grouped(morph::table::Combine::Any, {FilterEntry{.contains = "E"}}); - grouped(morph::table::Combine::Any, {FilterEntry{.startsWith = "r"}, FilterEntry{.eq = "usd"}}); - grouped(morph::table::Combine::All, {FilterEntry{.contains = "e"}, FilterEntry{.contains = "r"}}); - grouped(morph::table::Combine::Any, {FilterEntry{.endsWith = "%"}, FilterEntry{.contains = "'"}}); - return queries; -} - -/// @brief The seeded company's whole journal as the engine's source rows. -/// @return The entries by id. -[[nodiscard]] std::shared_ptr const> journalRowsFromLedger() { - auto const listed = lims::LedgerModel{}.execute(lims::ListEntries{.company = lims::test::seededCompany()}); - return std::make_shared const>(listed.entries); -} - -} // namespace - -// The page the database returns is the page the table engine returns over the same rows, for every sort and filter the -// standard corpus derives from the rows and for the date queries it cannot derive, with the total cap lowered so the -// above-cap rule runs on a small journal. -// Mutations: drop the plan's filters from the statement (translate returns "1" for the filter); order empty cells -// first; render an exclude as NOT (cell condition) without COALESCE; round an integer operand; drop the Latin-1 fold; -// order by the transaction-time seconds without the floor. -namespace { - -// The corpus is split into this many test cases, each comparing every `kCorpusParts`-th query: a page costs a load per -// row, and the whole corpus in one case outlasts a test's time limit under the sanitizers. -constexpr std::size_t kCorpusParts = 4; - -// Compares the queries at @p part, @p part + kCorpusParts, ... of the corpus. -void checkEntryPagesAgainstEngine(std::size_t part) { - DbFixture fixture; - auto const period = books(); - writeJournal(period.id, journalRows()); - ScopedPrincipal const alice{"alice"}; - auto const rows = journalRowsFromLedger(); - REQUIRE(rows->size() == journalRows().size()); - morph::table::RowsSource const source{ - rows, [](lims::JournalEntryView const& entry) { return morph::table::RowId{*entry.id}; }}; - - auto corpus = morph::table::standardCorpus(source); - auto const standardQueries = corpus.size(); - for (auto&& query : dateQueries(*rows)) { - corpus.push_back(std::move(query)); - } - CHECK(standardQueries > 1000U); - for (auto&& query : groupQueries()) { - corpus.push_back(std::move(query)); - } - decltype(corpus) slice; - for (std::size_t i = part; i < corpus.size(); i += kCorpusParts) { - slice.push_back(std::move(corpus.at(i))); - } - REQUIRE_FALSE(slice.empty()); - - morph::table::ConformanceOptions options; - options.limits.totalCap = 10; - options.translatable = lims::LedgerModel::canTranslateEntryColumn; - auto const company = lims::test::seededCompany(); - auto const model = - [&](morph::table::QueryPlan const& plan) -> std::expected { - auto const page = lims::LedgerModel::pageEntries(company, plan); - morph::table::ModelPage out; - for (auto const& row : page.rows) { - out.rows.emplace_back(*row.id); - } - out.total = page.total; - out.totalKind = page.totalKind; - out.offset = page.offset; - return out; - }; - auto const failures = morph::table::conformanceFailures(source, model, slice, options); - for (std::size_t i = 0; i < failures.size() && i < 10; ++i) { - WARN(failures[i]); - } - CHECK(failures.empty()); -} - } // namespace -TEST_CASE( - "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " - "filter the journal offers (part 1 of 4)", - "[lims][ledger][pages]") { - checkEntryPagesAgainstEngine(0); -} - -TEST_CASE( - "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " - "filter the journal offers (part 2 of 4)", - "[lims][ledger][pages]") { - checkEntryPagesAgainstEngine(1); -} - -TEST_CASE( - "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " - "filter the journal offers (part 3 of 4)", - "[lims][ledger][pages]") { - checkEntryPagesAgainstEngine(2); -} - -TEST_CASE( - "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " - "filter the journal offers (part 4 of 4)", - "[lims][ledger][pages]") { - checkEntryPagesAgainstEngine(3); -} - -// The control for the cases above: the journal and the corpus compare what the helper is said to compare. Every column -// the database can translate is filtered, somewhere in the corpus, by a query the plan accepts and whose view is -// neither empty nor the whole journal, except the company, which every entry shares. The standard quick-search group -// spans `lines` and is refused as Unavailable, so the group queries of the cases above are the ones that are compared. -TEST_CASE("ledger: the entry page refuses the columns the database cannot compare, and nothing else", - "[lims][ledger][pages]") { - DbFixture fixture; - auto const period = books(); - writeJournal(period.id, journalRows()); - ScopedPrincipal const alice{"alice"}; - auto const rows = journalRowsFromLedger(); - morph::table::RowsSource const source{ - rows, [](lims::JournalEntryView const& entry) { return morph::table::RowId{*entry.id}; }}; - std::vector refused; - for (auto const& column : source.columns()) { - if (!lims::LedgerModel::canTranslateEntryColumn(column.id, morph::table::PlanUse::Sort)) { - refused.push_back(column.id); - } - } - CHECK(refused == std::vector{"rate", "lines"}); - - auto corpus = morph::table::standardCorpus(source); - for (auto&& query : groupQueries()) { - corpus.push_back(std::move(query)); - } - std::map partial; - std::size_t refusedGroups = 0; - std::size_t translatedGroups = 0; - auto const rowCount = static_cast(rows->size()); - for (auto const& query : corpus) { - auto const planned = - morph::table::planQuery(query, source.columns(), {}, {}, {}, lims::LedgerModel::canTranslateEntryColumn); - if (!query.filters.groups.empty()) { - if (planned) { - ++translatedGroups; - } else { - CHECK(planned.error().code == morph::table::TableErrorCode::Unavailable); - CHECK((planned.error().column == "lines" || planned.error().column == "rate")); - ++refusedGroups; - } - continue; - } - if (!planned || query.filters.columns.size() != 1U) { - continue; - } - auto counting = query; - counting.page = morph::table::PageRequest{.offset = 0, .limit = 0}; - auto const counted = morph::table::apply(source, counting); - REQUIRE(counted.has_value()); - if (counted->total && *counted->total > 0 && *counted->total < rowCount) { - partial[query.filters.columns.begin()->first] = true; - } - } - for (auto const& column : source.columns()) { - if (!lims::LedgerModel::canTranslateEntryColumn(column.id, morph::table::PlanUse::Filter) || - column.id == "company") { - continue; - } - INFO("column " << column.id); - CHECK(partial[column.id]); - } - for (auto const& entry : *rows) { - CHECK(entry.company == lims::test::seededCompany()); - } - CHECK(refusedGroups > 0U); - CHECK(translatedGroups >= 5U); - - lims::LedgerModel ledger; - for (std::string const column : {"lines", "rate"}) { - CAPTURE(column); - lims::ListEntriesPage sorted{.company = lims::test::seededCompany(), .query = {}}; - sorted.query.sort = {morph::table::SortKey{.column = column, .dir = morph::table::SortDirection::Ascending}}; - CHECK_THROWS_AS(ledger.execute(sorted), lims::ValidationError); - } - lims::ListEntriesPage unknown{.company = lims::test::seededCompany(), .query = {}}; - unknown.query.sort = {morph::table::SortKey{.column = "nope", .dir = morph::table::SortDirection::Ascending}}; - CHECK_THROWS_AS(ledger.execute(unknown), lims::ValidationError); -} - -// Operands shaped like injection and like pattern syntax are data: quotes, a statement terminator, a comment -// marker, `%`, `_`, backslashes and a driver escape. They are bound, so the page equals the engine's and the table is -// untouched; a NUL byte, which SQLite's text functions stop at, is refused in words. -// Mutation: write a text operand into the statement unescaped. -TEST_CASE("ledger: text operands that look like SQL or like patterns are only data", "[lims][ledger][pages]") { - DbFixture fixture; - auto const period = books(); - writeJournal(period.id, journalRows()); - ScopedPrincipal const alice{"alice"}; - auto const rows = journalRowsFromLedger(); - morph::table::RowsSource const source{ - rows, [](lims::JournalEntryView const& entry) { return morph::table::RowId{*entry.id}; }}; - using morph::table::ColumnFilter; - using morph::table::FilterEntry; - using morph::table::TableQuery; - std::vector corpus; - for (std::string const operand : - {"'", "''", "x'; DROP TABLE ledger_entries; --", "' OR '1'='1", "%", "_", "100%", "100%_done", "\\", - "back\\slash", "C:\\temp\\%", "\"quoted\"", "{fn now()}", "a?b", "?", "--", "/*", - "\xC3\x89" - "clair"}) { - for (std::string const column : {"memo", "sourceKey", "sourceReference"}) { - for (bool const caseSensitive : {false, true}) { - for (int op = 0; op < 5; ++op) { - FilterEntry entry; - entry.caseSensitive = caseSensitive; - switch (op) { - case 0: - entry.eq = operand; - break; - case 1: - entry.ne = operand; - break; - case 2: - entry.contains = operand; - break; - case 3: - entry.startsWith = operand; - break; - default: - entry.endsWith = operand; - break; - } - TableQuery query; - ColumnFilter filter; - filter.include.push_back(entry); - query.filters.columns.emplace(column, std::move(filter)); - corpus.push_back(std::move(query)); - } - } - } - } - morph::table::ConformanceOptions options; - options.translatable = lims::LedgerModel::canTranslateEntryColumn; - auto const company = lims::test::seededCompany(); - auto const model = - [&](morph::table::QueryPlan const& plan) -> std::expected { - auto const page = lims::LedgerModel::pageEntries(company, plan); - morph::table::ModelPage out; - for (auto const& row : page.rows) { - out.rows.emplace_back(*row.id); - } - out.total = page.total; - out.totalKind = page.totalKind; - out.offset = page.offset; - return out; - }; - auto const failures = morph::table::conformanceFailures(source, model, corpus, options); - for (std::size_t i = 0; i < failures.size() && i < 10; ++i) { - WARN(failures[i]); - } - CHECK(failures.empty()); - CHECK(lims::LedgerModel{}.execute(lims::ListEntries{.company = company}).entries.size() == rows->size()); - - lims::ListEntriesPage withNul{.company = company, .query = {}}; - withNul.query.filters.columns["memo"].include.push_back(FilterEntry{.contains = std::string{"a\0b", 3}}); - try { - static_cast(lims::LedgerModel{}.execute(withNul)); - FAIL("a NUL operand was answered"); - } catch (lims::ValidationError const& error) { - CHECK(std::string_view{error.what()}.contains("NUL")); - } -} - // Mutation: skip the visibility check (dave, who sees no company, gets the journal). -TEST_CASE("ledger: a page of entries is the caller's, with an exact total from the database", - "[lims][ledger][pages]") { +TEST_CASE("ledger: a page of entries is the caller's, with an exact total", "[lims][ledger][pages]") { DbFixture fixture; auto const period = books(); writeJournal(period.id, journalRows()); diff --git a/examples/lims/tests/test_ledger_scale.cpp b/examples/lims/tests/test_ledger_scale.cpp index 8cccdde96..5b9dbe7e1 100644 --- a/examples/lims/tests/test_ledger_scale.cpp +++ b/examples/lims/tests/test_ledger_scale.cpp @@ -170,6 +170,29 @@ struct Written { } // namespace +// How ListEntriesPage scales: ListEntries is the read and the views, the page adds `apply`. Hidden, run by name. +TEST_CASE("Scaling: a page of the journal at 10^4 and 10^5 entries", "[.][lims][ledger][scale]") { + for (std::int64_t const entries : {std::int64_t{10'000}, std::int64_t{100'000}}) { + DbFixture fixture; + lims::test::grant("alice", lims::LimsRole::Accountant); + ScopedPrincipal const alice{"alice"}; + auto const books = createBooks(); + static_cast(writeEntries(books, entries, false)); + lims::LedgerModel ledger; + auto const readStart = Clock::now(); + auto const listed = ledger.execute(lims::ListEntries{.company = lims::test::seededCompany()}); + report("ListEntries over " + std::to_string(entries) + " entries", millisSince(readStart)); + lims::ListEntriesPage request{.company = lims::test::seededCompany(), .query = {}}; + request.query.page.offset = entries / 2; + request.query.page.limit = kPageSize; + auto const pageStart = Clock::now(); + auto const page = ledger.execute(request); + report("ListEntriesPage over " + std::to_string(entries) + " entries", millisSince(pageStart)); + CHECK(listed.entries.size() == static_cast(entries)); + CHECK(page.rows.size() == static_cast(kPageSize)); + } +} + TEST_CASE("Stress: Hypothesis 10: a page of the journal over 10^6 entries", "[lims][ledger][scale][stress]") { DbFixture fixture; lims::test::grant("alice", lims::LimsRole::Accountant); @@ -200,8 +223,8 @@ TEST_CASE("Stress: Hypothesis 10: a page of the journal over 10^6 entries", "[li CHECK(*page.rows.front().id == ids[500'000]); CHECK(*page.rows.back().id == ids[500'000 + kPageSize - 1]); CHECK(page.offset == 500'000); - CHECK(page.total == kEntriesForPage); - CHECK(page.totalKind == morph::table::TotalKind::Exact); + // Above `QueryLimits::totalCap` (100,000 rows) `table::apply` gives no total. + CHECK_FALSE(page.total.has_value()); // A sorted and filtered page costs the same order: the last entries by descending id, among those whose reference // starts with the last one's prefix. diff --git a/examples/lims/tests/test_sample_pages.cpp b/examples/lims/tests/test_sample_pages.cpp index e80714091..821a733ca 100644 --- a/examples/lims/tests/test_sample_pages.cpp +++ b/examples/lims/tests/test_sample_pages.cpp @@ -1,16 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // -// The sample list pages in the database: the page a caller gets equals the page the table engine gives over the same -// visible rows, for every sort and filter the standard corpus derives and for the date queries it cannot. +// The sample list: the action reads the caller's samples and answers with the table engine, so a caller sees only +// the samples at the sites where they hold a role. #include #include -#include #include #include -#include #include -#include #include #include #include @@ -156,97 +153,10 @@ struct Samples { return views; } -/// @brief Date-time queries the standard corpus cannot make: its operands are the cells' own text, and a date-time -/// cell's text is not a date the parser reads. The operands are the whole seconds of the rows' own instants, so -/// every equality, bound and tie falls on a boundary, and a few instants that match no row. -/// @param samples The visible samples. -/// @return The queries. -[[nodiscard]] std::vector dateQueries(std::vector const& samples) { - using morph::table::ColumnFilter; - using morph::table::FilterEntry; - using morph::table::SortDirection; - using morph::table::SortKey; - using morph::table::TableQuery; - std::vector queries; - auto const filtered = [&](FilterEntry entry, bool asExclude) { - TableQuery query; - ColumnFilter filter; - (asExclude ? filter.exclude : filter.include).push_back(std::move(entry)); - query.filters.columns.emplace("registeredAt", std::move(filter)); - query.sort = {SortKey{.column = "registeredAt", .dir = SortDirection::Descending}}; - queries.push_back(std::move(query)); - }; - std::vector instants{"2026-11-10T09:00:00.500Z", "2026-11-11", "1963-01-01T00:00:00Z"}; - for (auto const& sample : samples) { - auto const second = lims::test::isoSecond(sample.registeredAt); - if (std::ranges::find(instants, second) == instants.end()) { - instants.push_back(second); - } - } - for (bool const asExclude : {false, true}) { - for (std::string const& instant : instants) { - filtered(FilterEntry{.eq = instant}, asExclude); - filtered(FilterEntry{.ne = instant}, asExclude); - filtered(FilterEntry{.lt = instant}, asExclude); - filtered(FilterEntry{.le = instant}, asExclude); - filtered(FilterEntry{.gt = instant}, asExclude); - filtered(FilterEntry{.ge = instant}, asExclude); - filtered(FilterEntry{.between = std::array{instant, "2026-11-12"}}, asExclude); - } - } - return queries; -} - } // namespace -// The page the database returns is the page the table engine returns over the same visible rows, as alice sees them -// (every site of two companies, and not the sample with no site) and as bob sees them (one site), with the total cap -// lowered so the above-cap rule runs on a small table. -// Mutations: drop the plan's filters from the statement; drop the site scope (bob gets every sample); drop the Latin-1 -// fold; order a state by its ordinal. -TEST_CASE( - "lab: a page of samples from the database equals the engine's page over the same rows, for every sort and filter " - "the list offers", - "[lims][lab][pages]") { - DbFixture fixture; - static_cast(setUp()); - for (std::string const principal : {"alice", "bob"}) { - CAPTURE(principal); - ScopedPrincipal const caller{principal}; - auto const sites = lims::OrgModel::visibleSites(principal); - auto const rows = visibleViews(sites); - REQUIRE_FALSE(rows->empty()); - morph::table::RowsSource const source{ - rows, [](lims::SampleView const& sample) { return morph::table::RowId{*sample.id}; }}; - auto corpus = morph::table::standardCorpus(source); - CHECK(corpus.size() > 300U); - for (auto&& query : dateQueries(*rows)) { - corpus.push_back(std::move(query)); - } - morph::table::ConformanceOptions options; - options.limits.totalCap = 10; - options.translatable = lims::SampleModel::canTranslateSampleColumn; - auto const model = [&](morph::table::QueryPlan const& plan) - -> std::expected { - auto const page = lims::SampleModel::pageSamples(sites, plan); - morph::table::ModelPage out; - for (auto const& row : page.rows) { - out.rows.emplace_back(*row.id); - } - out.total = page.total; - out.totalKind = page.totalKind; - out.offset = page.offset; - return out; - }; - auto const failures = morph::table::conformanceFailures(source, model, corpus, options); - for (std::size_t i = 0; i < failures.size() && i < 10; ++i) { - WARN(failures[i]); - } - CHECK(failures.empty()); - } -} - -// Mutation: let ListSamples ignore the plan's offset. +// Mutations: let ListSamples ignore the query's offset; let pageSamples ignore its sites (bob's total is every +// sample). TEST_CASE("lab: the sample list answers through the action with an exact total", "[lims][lab][pages]") { DbFixture fixture; static_cast(setUp()); @@ -264,15 +174,3 @@ TEST_CASE("lab: the sample list answers through the action with an exact total", request.query.sort = {morph::table::SortKey{.column = "nope", .dir = morph::table::SortDirection::Ascending}}; CHECK_THROWS_AS(model.execute(request), lims::ValidationError); } - -// Mutation: let pageSamples run a plan whose sort names a column the statement cannot order by. -TEST_CASE("lab: a plan the statement cannot translate is refused", "[lims][lab][pages]") { - DbFixture fixture; - static_cast(setUp()); - ScopedPrincipal const bob{"bob"}; - morph::table::QueryPlan plan; - plan.sort.push_back(morph::table::PlannedSortKey{.column = "nope"}); - plan.limit = 5; - plan.totalCap = 10; - CHECK_THROWS_AS(lims::SampleModel::pageSamples(lims::OrgModel::visibleSites("bob"), plan), lims::ValidationError); -} diff --git a/examples/lims/tests/test_shell_reads.cpp b/examples/lims/tests/test_shell_reads.cpp index e593231f2..4f17886b7 100644 --- a/examples/lims/tests/test_shell_reads.cpp +++ b/examples/lims/tests/test_shell_reads.cpp @@ -210,6 +210,30 @@ TEST_CASE("shell: the lab counts the samples to verify and finds samples by refe CHECK_THROWS_AS(lab.execute(lims::CountSamplesToVerify{}), lims::ValidationError); } +// Above the table engine's total cap (100,000 rows) the count and the search total are still the number of matches. +// Mutation: samplesWhere without its uncapped options, counting with `page.total.value_or(0)` (the count reads 0). +TEST_CASE("shell: the lab counts samples to verify exactly above the total cap", "[lims][lab][shell]") { + DbFixture fixture; + lims::test::grant("tech", lims::LimsRole::Analyst); + ScopedPrincipal const tech{"tech"}; + static_cast(lims::SampleModel{}.execute(lims::RegisterClient{.name = "Waterworks Ltd"})); + Lightweight::DataMapper mapper; + auto const clients = mapper.Query().All(); + REQUIRE(!clients.empty()); + constexpr std::int64_t kMatches = 100'001; + lims::test::runSql( + "INSERT INTO lims_samples (client_id, reference, state, version, registered_at, site_id) " + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < " + + std::to_string(kMatches) + ") SELECT " + std::to_string(clients.front().id.Value()) + ", 'CAP-' || i, " + + std::to_string(static_cast(lims::SampleState::ToBeVerified)) + ", 1, 0, " + + std::to_string(*lims::test::seededSite()) + " FROM n"); + lims::SampleDirectoryModel lab; + CHECK(lab.execute(lims::CountSamplesToVerify{.company = lims::test::seededCompany()}).count == countOf(kMatches)); + auto const found = lab.execute(lims::SearchSamples{.query = "CAP-", .company = lims::test::seededCompany()}); + CHECK(found.total == countOf(kMatches)); + CHECK(found.hits.size() == 8); +} + // Mutations: count the invoices of every company; count the caller's pending approvals // at every company (carl's count at the second company is wrong); answer the total as the number of hits (the total // reads as the 8 hits). diff --git a/examples/lims_gallery/src/screens/audit.cpp b/examples/lims_gallery/src/screens/audit.cpp index 9b73cd94a..a7e87e9d7 100644 --- a/examples/lims_gallery/src/screens/audit.cpp +++ b/examples/lims_gallery/src/screens/audit.cpp @@ -334,7 +334,7 @@ ui::Node trailTable(Audit const& audit) { return ui::table( audit.shown, {.key = ui::row("at"), - .columns = + .columns = layout::unfiltered( {{.name = "when", .label = "When", .width = ui::fixed(10), @@ -357,7 +357,7 @@ ui::Node trailTable(Audit const& audit) { .label = "Reason", .width = ui::stretch(), .cell = ui::text({.text = ui::cond(noReason, ui::AnyHandle{"—"}, reason), - .role = ui::cond(noReason, Text{"muted"}, Text{"normal"})})}}, + .role = ui::cond(noReason, Text{"muted"}, Text{"normal"})})}}), .pageSize = std::int64_t{25}, .page = audit.page, .empty = noEntries(audit), diff --git a/examples/lims_gallery/src/screens/console.cpp b/examples/lims_gallery/src/screens/console.cpp index 1f66e182b..6ef274f0c 100644 --- a/examples/lims_gallery/src/screens/console.cpp +++ b/examples/lims_gallery/src/screens/console.cpp @@ -591,7 +591,7 @@ ui::Node worklistTable(Console const& console, ui::AnyHandle const& rows, std::s return ui::table( rows, {.key = ui::row("id"), - .columns = columns, + .columns = layout::unfiltered(columns), .selectionMode = ui::Selection::Single, .selection = ui::map(atCurrent, "entry", [](ui::AnyHandle const& entry) { return entry.at("id"); }), .onSelectionChange = ui::set( diff --git a/examples/lims_gallery/src/screens/results.cpp b/examples/lims_gallery/src/screens/results.cpp index e828167ae..f619062c6 100644 --- a/examples/lims_gallery/src/screens/results.cpp +++ b/examples/lims_gallery/src/screens/results.cpp @@ -473,7 +473,7 @@ ui::Node resultTable(Worksheet const& sheet) { return ui::table( sheet.lines, {.key = ui::row("id"), - .columns = columns, + .columns = layout::unfiltered(columns), // Each sample's results under a heading across the worksheet: its id and its lot. .group = ui::TableGroup{ diff --git a/examples/lims_gallery/src/screens/review.cpp b/examples/lims_gallery/src/screens/review.cpp index 429e2eb4d..4eb394fbd 100644 --- a/examples/lims_gallery/src/screens/review.cpp +++ b/examples/lims_gallery/src/screens/review.cpp @@ -552,7 +552,7 @@ ui::Node resultTable(Review const& review) { .wrap = false, .shrink = true}}; return ui::table(review.shownResults, {.key = ui::row("key"), - .columns = columns, + .columns = layout::unfiltered(columns), .rowTone = ui::cond(ui::eq(ui::row("tone"), "err"), ui::AnyHandle{"err"}, ui::AnyHandle{nullptr})}) .a11y("Results under review") @@ -619,7 +619,7 @@ ui::Node lotTable(Review const& review) { return ui::column( {ui::table(ofSelected(review, review.lots), {.key = ui::row("lot"), - .columns = columns, + .columns = layout::unfiltered(columns), .empty = {ui::emptyState({.title = "No lots to compare", .text = "This product has no earlier lots tested by this method."})}}) .a11y("Previous lots") diff --git a/examples/lims_gallery/src/screens/samples.cpp b/examples/lims_gallery/src/screens/samples.cpp index 40522d671..33ec15408 100644 --- a/examples/lims_gallery/src/screens/samples.cpp +++ b/examples/lims_gallery/src/screens/samples.cpp @@ -504,7 +504,7 @@ ui::Node samplesTable(Samples const& list) { return ui::table( list.shown, {.key = ui::row("id"), - .columns = + .columns = layout::unfiltered( {{.name = "id", .label = "Sample", .width = ui::fixed(11), .role = "mono", .sortable = true}, {.name = "product", .label = "Product · lot", @@ -532,7 +532,7 @@ ui::Node samplesTable(Samples const& list) { .sortable = true, .sortBy = ui::row("dueAt"), .wrap = false}, - {.name = "spec", .label = "Specification", .width = ui::content(), .cell = specCell()}}, + {.name = "spec", .label = "Specification", .width = ui::content(), .cell = specCell()}}), // The table draws the selection the cards share: its own boxes, and a header box for the page. .selectionMode = ui::Selection::Multiple, .selection = list.selected, diff --git a/examples/lims_gallery/src/screens/screen_layout.hpp b/examples/lims_gallery/src/screens/screen_layout.hpp index 152d69644..77bfa4e1e 100644 --- a/examples/lims_gallery/src/screens/screen_layout.hpp +++ b/examples/lims_gallery/src/screens/screen_layout.hpp @@ -95,4 +95,14 @@ inline void plainPageWhenCompact(ui::Scope& screen, ui::AnyHandle const& width) quietTag(priority).visible(!(stat || urgent))}); } +/// @brief @p columns with no filter button on any header: the designs filter through the screen's own controls. +/// @param columns The table's columns. +/// @return The columns, none filterable. +[[nodiscard]] inline std::vector unfiltered(std::vector columns) { + for (ui::TableColumn& column : columns) { + column.filterable = false; + } + return columns; +} + } // namespace lims_gallery::layout diff --git a/examples/lims_gallery/tests/gallery_harness.hpp b/examples/lims_gallery/tests/gallery_harness.hpp index 06bd28255..57810fa53 100644 --- a/examples/lims_gallery/tests/gallery_harness.hpp +++ b/examples/lims_gallery/tests/gallery_harness.hpp @@ -37,7 +37,9 @@ class GalleryScreen : public morph::examples::testing::ScreenHarness { /// screen as `{"env": "widthClass"}`. GalleryScreen(std::string_view screenId, std::string_view width) : ScreenHarness{localApp(), std::string{screenId}, morph::examples::testing::RigMode::Local, {}, - {}, std::string{width}} {} + {}, std::string{width}} { + settle(); + } /// @brief Whether a widget of @p kind with @p testId is mounted and not hidden itself. /// @param kind The widget kind, as `RecordingBackend` names it. diff --git a/examples/lims_gallery/tests/test_audit.cpp b/examples/lims_gallery/tests/test_audit.cpp index 589531937..14104b589 100644 --- a/examples/lims_gallery/tests/test_audit.cpp +++ b/examples/lims_gallery/tests/test_audit.cpp @@ -36,7 +36,7 @@ TEST_CASE("audit, expanded: facets beside the trail, with the active filters as CHECK(screen.prop("Checkbox", "type-result", "checked") == "true"); CHECK(screen.prop("Checkbox", "type-specification", "checked") == "false"); CHECK(screen.shows("Table", "trail")); - CHECK(screen.prop("Table", "trail", "columns") == + CHECK(screen.prop("Table", "trail", "columns").value_or("none") == "[When:fixed(10);valign=start;wrap=false,User:fixed(6);valign=start,Record:fixed(12);valign=start," "Field:fixed(8);valign=start,Old value:fixed(7);valign=start,New value:fixed(8);valign=start," "Reason:stretch(1);valign=start]"); diff --git a/examples/lims_gallery/tests/test_review.cpp b/examples/lims_gallery/tests/test_review.cpp index 46d44d914..02b6054b9 100644 --- a/examples/lims_gallery/tests/test_review.cpp +++ b/examples/lims_gallery/tests/test_review.cpp @@ -29,6 +29,15 @@ bool pageInset(GalleryScreen& screen) { return screen.backend().prop(screen.backend().children(page).at(0), "visible") != "false"; } +// How many dialogs are open: a table mounts closed ones of its own, which a count of the Dialog widgets includes. +std::size_t openDialogs(GalleryScreen& screen) { + std::size_t open = 0; + for (int const dialog : screen.screenWidgets("Dialog")) { + open += screen.backend().prop(dialog, "open") == "true" ? 1U : 0U; + } + return open; +} + } // namespace TEST_CASE("review, expanded: the queue beside the worksheet, its flagged results", "[lims-gallery]") { @@ -108,13 +117,16 @@ TEST_CASE("review: approve and sign opens the e-signature over the review, and i screen.click("approve"); CHECK(screen.waitFor( [&screen] { return screen.backend().find("Dialog", "title", "Sign to approve results").has_value(); })); + CHECK(openDialogs(screen) == 1); CHECK(workspaceTabs(screen) == "[Review and approval]"); CHECK(screen.mounted().size() == 1); CHECK(screen.find("Column", "fields").has_value()); CHECK(screen.prop("Button", "overlay_action_sign", "enabled") == "true"); screen.edit("password", "meyer-2026"); screen.click("overlay_action_sign"); - CHECK(screen.waitFor([&screen] { return screen.screenWidgets("Dialog").size() == 1; })); + // The table mounts dialogs of its own, closed; the signature's is the only one open, and it closes when the + // signature answers. + CHECK(screen.waitFor([&screen] { return openDialogs(screen) == 0; })); CHECK(screen.waitFor([&screen] { return screen.shows("Banner", "signed"); })); CHECK(screen.prop("Banner", "signed", "text") == "WS-2026-0412 signed: approved."); screen.requireNoProblems(); diff --git a/examples/lims_gallery/tests/test_samples.cpp b/examples/lims_gallery/tests/test_samples.cpp index b405e045b..c69a5bb94 100644 --- a/examples/lims_gallery/tests/test_samples.cpp +++ b/examples/lims_gallery/tests/test_samples.cpp @@ -39,7 +39,7 @@ TEST_CASE("samples, expanded: the table, its out-of-spec tone, and three rows se GalleryScreen screen{kScreen, "expanded"}; screen.requireNoProblems(); CHECK(screen.shows("Table", "samples")); - CHECK(screen.prop("Table", "samples", "columns") == + CHECK(screen.prop("Table", "samples", "columns").value_or("none") == "[Sample:fixed(11);sortable=true,Product · lot:stretch(6),Tests:stretch(4),Priority:content," "Status:content,Due:fixed(12);sortable=true;wrap=false,Specification:content]"); // Sorted by due time, earliest first, 25 rows a page. @@ -85,9 +85,10 @@ TEST_CASE("samples, expanded: selecting rows drives the bulk bar, and changing p screen.backend().prop(badge, "text") == "STAT" && screen.backend().prop(badge, "tone") == "Err" ? 1U : 0U; } CHECK(stat == 2); - // The header box is Ctrl+A: every row on the page. + // The header box is Ctrl+A: it selects the table's whole view, every page, so all 38 samples the filters leave + // are selected while 25 show. CHECK(screen.backend().press(table, "Ctrl+A")); - CHECK(screen.waitFor([&screen] { return screen.text("selected") == "25 selected on this page ·"; })); + CHECK(screen.waitFor([&screen] { return screen.text("selected") == "38 selected on this page ·"; })); screen.click("select-all"); CHECK(screen.waitFor([&screen] { return screen.text("selected") == "All 312 samples selected ·"; })); screen.requireNoProblems(); diff --git a/examples/lims_gallery/tests/test_stability.cpp b/examples/lims_gallery/tests/test_stability.cpp index b06edaeff..d0a834979 100644 --- a/examples/lims_gallery/tests/test_stability.cpp +++ b/examples/lims_gallery/tests/test_stability.cpp @@ -163,6 +163,9 @@ TEST_CASE("stability: tests per timepoint, then review and sign", "[lims-gallery REQUIRE(screen.waitFor([&screen] { return screen.find("Text", "runs").has_value(); })); // Five tests at each of the 15 pulls; microbial limits is not run. CHECK(screen.text("runs") == "5 tests, 75 test runs over 15 pulls."); + // The check box is a table cell, which can be lowered after the summary line is on screen. + REQUIRE(screen.waitFor( + [&screen] { return screen.backend().find("Checkbox", "a11yName", "Run Microbial limits").has_value(); })); screen.backend().toggle(checkbox(screen, "Run Microbial limits")); CHECK(screen.waitFor([&screen] { return screen.text("runs") == "6 tests, 77 test runs over 15 pulls."; })); screen.click("continue"); diff --git a/include/morph/attributes.hpp b/include/morph/attributes.hpp index 3e6a7f267..5998dfe3b 100644 --- a/include/morph/attributes.hpp +++ b/include/morph/attributes.hpp @@ -35,3 +35,17 @@ #ifndef MORPH_LIFETIMEBOUND #define MORPH_LIFETIMEBOUND #endif + +/// @brief Gives a header-defined function default visibility, so the function-local statics inside it are one +/// object per process however many shared objects include the header. +/// +/// A header-only function is compiled into every shared object that uses it, and under `-fvisibility=hidden` each +/// copy keeps its own function-local static: a counter that must hand out distinct values process-wide hands out the +/// same ones from two objects, and a memo is built once per object. Default visibility lets the dynamic linker merge +/// the copies, which is what Clang's `-Wunique-object-duplication` asks for. Windows has no such merge for a +/// header-only function, and its compilers do not take the attribute, so it expands to nothing there. +#if defined(__GNUC__) && !defined(_WIN32) +#define MORPH_PROCESS_UNIQUE __attribute__((visibility("default"))) +#else +#define MORPH_PROCESS_UNIQUE +#endif diff --git a/include/morph/core/bridge.hpp b/include/morph/core/bridge.hpp index 228d086be..ac8eb5ddb 100644 --- a/include/morph/core/bridge.hpp +++ b/include/morph/core/bridge.hpp @@ -27,6 +27,7 @@ #include "../attributes.hpp" #include "../core/backend.hpp" +#include "../forms/derive.hpp" #include "../forms/forms.hpp" #include "../session/session.hpp" #include "callback_scope.hpp" @@ -617,10 +618,11 @@ void localTaskOp(::morph::model::detail::IModelHolder& holder, std::shared_ptr& executor, ::core::async::StopToken token, ::morph::backend::detail::ActionCall::LocalDone done) { using R = ::morph::model::ActionTraits::Result; - using Handler = decltype(std::declval().execute(std::declval())); + using Handler = decltype(::morph::model::detail::invokeExecute(std::declval(), std::declval())); Action& actionRef = *static_cast(actionOwner.get()); Handler task; try { + ::morph::forms::clearDerived(actionRef); ::morph::forms::recomputeAll(actionRef); if (!::morph::model::ActionValidator::ready(actionRef)) { throw ::morph::model::ValidationError{::morph::model::ModelTraits::typeId(), @@ -630,7 +632,7 @@ void localTaskOp(::morph::model::detail::IModelHolder& holder, std::shared_ptr::toJson(actionRef); }); - task = model.execute(actionRef); + task = ::morph::model::detail::invokeExecute(model, actionRef); } catch (...) { done(nullptr, std::current_exception()); return; @@ -2248,7 +2250,8 @@ class Bridge { template static consteval bool isTaskHandlerCall() { #ifndef MORPH_CLIENT_ONLY - return ::morph::model::isTaskHandler().execute(std::declval()))>; + return ::morph::model::isTaskHandler(), + std::declval()))>; #else // A client-only build never runs a handler locally (see makeActionCall). return false; @@ -2395,6 +2398,9 @@ class Bridge { // inspecting a computed field sees the authoritative value, not // whatever the caller constructed the action with. No-op for actions // with no computedFields. See docs/spec/forms/forms.md. + // Derived members are cleared first, as on every execution path, so the model and the computed fields + // read the same values in-process as over a server. + ::morph::forms::clearDerived(actionRef); ::morph::forms::recomputeAll(actionRef); if (!::morph::model::ActionValidator::ready(actionRef)) { throw ::morph::model::ValidationError{::morph::model::ModelTraits::typeId(), @@ -2437,7 +2443,7 @@ class Bridge { }); auto result = [&] { try { - return std::make_shared(model.execute(actionRef)); + return std::make_shared(::morph::model::detail::invokeExecute(model, actionRef)); } catch (const std::exception& exc [[maybe_unused]]) { if constexpr (::morph::model::detail::actionLoggable() == ::morph::model::Loggable::Yes) { @@ -3164,6 +3170,9 @@ inline void ActionExecuteRegistry::registerAction(std::string_view modelId, std: // Overwrite any computed fields from their declared inputs -- a // computed field is never trusted from the client, on any path. // No-op for actions with no computedFields. See docs/spec/forms/forms.md. + // A derived member is the model's to set: what the caller sent for it is cleared first, so neither the + // model nor a computed field over it reads a forged value. + ::morph::forms::clearDerived(action); ::morph::forms::recomputeAll(action); // Enforce the action's validator on the request/reply dispatch path, // just as the reactive `set<>` path does in diff --git a/include/morph/core/change_types.hpp b/include/morph/core/change_types.hpp index 61632b2bd..9d50e68d9 100644 --- a/include/morph/core/change_types.hpp +++ b/include/morph/core/change_types.hpp @@ -3,9 +3,11 @@ #pragma once #include #include +#include #include #include #include +#include #include /// @file @@ -51,4 +53,27 @@ struct Changes { [[nodiscard]] bool empty() const { return records.empty() && instances.empty(); } }; +/// @brief Reports a change to rows of a record that no execute made: what a server gives an attached observer. +/// +/// The first argument is the record's wire name; the second the changed rows' keys as raw JSON, absent for the +/// whole type. Callable from any thread; it holds the server weakly and does nothing once the server is gone. +using AnnounceSink = std::function> keys)>; + +/// @brief Something a server tells of every change an execute or a time fact derived, before the change's events +/// are queued: a server-side cache that must drop what the change made wrong. +// NOLINTBEGIN(cppcoreguidelines-special-member-functions) +class IChangeObserver { +public: + virtual ~IChangeObserver() = default; + + /// @brief Takes one fan-out's changes. Runs on the server strand, and must not load, wait or call out. + /// @param changes What the execute or the time fact changed. + virtual void changed(Changes const& changes) = 0; + + /// @brief Takes the sink through which the observer reports changes of its own. + /// @param sink The server's announce sink. + virtual void bind(AnnounceSink sink) = 0; +}; +// NOLINTEND(cppcoreguidelines-special-member-functions) + } // namespace morph::effects diff --git a/include/morph/core/changes.hpp b/include/morph/core/changes.hpp index ea7a734ec..c566856f2 100644 --- a/include/morph/core/changes.hpp +++ b/include/morph/core/changes.hpp @@ -167,7 +167,8 @@ inline void addInstanceChange(Changes& changes, InstanceChange const& ranOn) { } } -/// @brief Adds the change an `updates` effect makes: the keys of the `R` rows found in the result. +/// @brief Adds the change an `updates` effect makes: the keys of the `R` rows found in the result, and the keys +/// those rows had before, where the record names a member for them. /// /// A result that does not parse, or a record without a key, cannot name rows: the whole type is reported, /// which over-notifies but never misses. @@ -190,6 +191,9 @@ inline void addUpdatesChange(Resolved const& resolved, std::string_view actionId } for (auto const& path : held.paths) { collectKeysAtPath(*parsed, path, *info->keyField, keys); + if (info->previousKeyField) { + collectKeysAtPath(*parsed, path, *info->previousKeyField, keys); + } } } addRecordChange(changes, record, std::move(keys)); diff --git a/include/morph/core/detail/result_walker.hpp b/include/morph/core/detail/result_walker.hpp index 164d8d531..0c6f6f970 100644 --- a/include/morph/core/detail/result_walker.hpp +++ b/include/morph/core/detail/result_walker.hpp @@ -12,12 +12,14 @@ /// registry is first read. #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -36,6 +38,22 @@ struct ResultSlot { /// The JSON path to it: member names joined with `.`, empty for the result itself. /// A `std::vector`, `std::optional` or `std::map` value adds no segment. std::string path; + /// True when the result holds the type with no path a key can be read at: the + /// action holds the record, but no reader finds its rows in the value. + bool opaque = false; +}; + +/// @brief The members of one result holder that open or make partial what holds the result, by path. +/// +/// A holder is a visited aggregate whose type declares `openMembers()` or `partialMember()`. Only members its +/// reflection has are listed. +struct HolderMembers { + /// The holder's own path in the result. + std::string path; + /// The members that open an entry while any is set, by name. + std::vector open; + /// The member that makes an entry partial while set, by name; empty when the holder names none. + std::string partial; }; /// @brief What one action id's registration recorded about its result. @@ -49,6 +67,8 @@ struct ActionResult { std::type_index action; /// The places that action's result holds a reflected aggregate. std::vector resultSlots; + /// The holders in that action's result that declare open or partial members. + std::vector holders; }; /// @brief Every action's result, by action id. @@ -114,10 +134,42 @@ consteval bool mayHoldSlots() { } } +/// @brief A type that holds a record's rows at one of its members, under another type than the rows': it names +/// the record as `heldRecord` and the member as `heldMember()`. +template +concept HoldsRecord = requires { + typename T::heldRecord; + { T::heldMember() } -> std::convertible_to; +}; + +/// @brief A type that names the members of itself which open what holds it: `openMembers()`, a range of names. +template +concept DeclaresOpenMembers = + requires { T::openMembers(); } && std::ranges::range && + std::convertible_to, std::string_view>; + +/// @brief A type that names the member of itself which makes what holds it partial: `partialMember()`. +template +concept DeclaresPartialMember = requires { + { T::partialMember() } -> std::convertible_to; +}; + +/// @brief Whether the reflection of @p T has a member named @p name. +/// @tparam T An `Object`. +/// @param name The member's name. +/// @return `true` when one of glaze's keys for @p T is @p name. +template +[[nodiscard]] bool reflectsMember(std::string_view name) { + constexpr auto keys = glz::reflect::keys; + return std::ranges::find(keys, name) != keys.end(); +} + /// @brief The state of one walk. struct Walk { /// The slots found so far. std::vector found; + /// The holders that declare open or partial members, found so far. + std::vector holders; /// The aggregates on the current path, which end the walk where they recur. std::vector onPath; }; @@ -148,6 +200,7 @@ void visitMembers(Walk& walk, std::string const& path, std::index_sequence /// @param walk The walk's state. /// @param path Where the value sits in the result. template +// NOLINTNEXTLINE(readability-function-cognitive-complexity): `visit` dispatches on the shape of T (optional, variant, map, sequence, struct) and every branch extends the same walk path and error state void visit(Walk& walk, std::string const& path) { if constexpr (!std::is_void_v::type>) { result_walker::visit::type>>(walk, path); @@ -157,6 +210,27 @@ void visit(Walk& walk, std::string const& path) { return; } walk.found.push_back(ResultSlot{.type = self, .path = path}); + if constexpr (DeclaresOpenMembers || DeclaresPartialMember) { + HolderMembers holder{.path = path, .open = {}, .partial = {}}; + if constexpr (DeclaresOpenMembers) { + for (std::string_view const member : T::openMembers()) { + if (reflectsMember(member)) { + holder.open.emplace_back(member); + } + } + } + if constexpr (DeclaresPartialMember) { + if (reflectsMember(T::partialMember())) { + holder.partial = std::string{T::partialMember()}; + } + } + walk.holders.push_back(std::move(holder)); + } + if constexpr (HoldsRecord) { + std::string const member{T::heldMember()}; + walk.found.push_back(ResultSlot{.type = std::type_index{typeid(typename T::heldRecord)}, + .path = path.empty() ? member : path + "." + member}); + } walk.onPath.push_back(self); visitMembers(walk, path, std::make_index_sequence::size>{}); walk.onPath.pop_back(); @@ -170,9 +244,10 @@ void visit(Walk& walk, std::string const& path) { /// The result itself, a `std::vector`, `std::optional` or `std::map` value of a /// visited type, and the members of a reflected aggregate are visited, /// depth-first. Member names are glaze's reflected keys, which are the names -/// the codec writes. `void`, scalars, strings, types whose `glz::meta` replaces -/// the codec, and pure-reflection types in an anonymous namespace are skipped. -/// The walk stops at a type already on its path, so recursive types end. +/// the codec writes. A type with a `heldRecord` and a `heldMember()` also +/// reports its `heldRecord` at that member, beside its own slot. `void`, scalars, strings, types whose `glz::meta` +/// replaces the codec, and pure-reflection types in an anonymous namespace are skipped. The walk stops at a type +/// already on its path, so recursive types end. /// @tparam R The result type, `void` included. /// @return The slots in visiting order. template @@ -186,6 +261,23 @@ template return std::move(walk.found); } +/// @brief The holders a value of type @p R can hold that declare open or partial members, with each one's path. +/// +/// The same walk as `walkResult`: a visited aggregate whose type has `openMembers()` or `partialMember()` is a +/// holder, and a member it names that its reflection lacks is left out. +/// @tparam R The result type, `void` included. +/// @return The holders in visiting order. +template +[[nodiscard]] std::vector walkHolders() { + result_walker::Walk walk; + if constexpr (!std::is_void_v) { + if constexpr (result_walker::mayHoldSlots>()) { + result_walker::visit>(walk, std::string{}); + } + } + return std::move(walk.holders); +} + /// @brief The process-level map of action result slots, filled by static registrars. /// @return The mutable map. MORPH_API ActionResultSlotMap& mutableActionResultSlots(); diff --git a/include/morph/core/effects.hpp b/include/morph/core/effects.hpp index 1ad493be4..193cbd2b9 100644 --- a/include/morph/core/effects.hpp +++ b/include/morph/core/effects.hpp @@ -70,6 +70,14 @@ struct EffectsRegistrationError : std::logic_error { } // namespace morph::model +namespace morph::table { + +// The record type of a registered table, defined and documented in ``. +template +struct TableOf; + +} // namespace morph::table + namespace morph::effects { /// @brief Effect: the action edits existing rows of record @p R, and its result carries them. @@ -82,6 +90,17 @@ struct updates {}; template struct changes {}; +/// @brief Effect: the action edits rows of a table, and its result carries their keys in a +/// `morph::table::ChangedRows`. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` names it. +template +using updatesTable = updates<::morph::table::TableOf>; + +/// @brief Effect: the action may change any row of a table: a whole-table change. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` names it. +template +using changesTable = changes<::morph::table::TableOf>; + /// @brief Effect: the state of the instance the action ran on changed. struct changesInstance {}; @@ -116,13 +135,22 @@ struct ActionRecord { std::string record; /// The record's key field, empty for a keyless record. std::optional keyField; - /// The JSON paths at which the result holds the record; `""` is the result itself. + /// The JSON paths at which the result holds the record; `""` is the result itself. Empty when `opaque`. std::vector paths; + /// True when the result holds the record at no path a key can be read at, as a table's page holds its + /// table's record: the action holds it for watch admission, and no reader finds its rows in the value. + bool opaque = false; + /// The paths of the members that open an entry holding the result: those a holder of the record's rows names in + /// its `openMembers()`. While any is set, a row the result does not hold may come to belong to it. + std::vector open; + /// The paths of the members that make an entry holding the result partial: the one each holder of the record's + /// rows names as its `partialMember()`. While any is set, a merge by key would leave them describing other rows. + std::vector partial; /// @brief Memberwise equality. /// @param lhs One entry. /// @param rhs The other. - /// @return True when record, key field and paths match. + /// @return True when record, key field, paths, opacity and the open and partial members match. friend bool operator==(ActionRecord const& lhs, ActionRecord const& rhs) = default; }; @@ -410,11 +438,11 @@ struct Resolved { /// @brief Whether two registrations of one record type declared the same record. /// @param lhs One registration. /// @param rhs The other. -/// @return True when name, key, sources and privacy all match. +/// @return True when name, key, sources, privacy and tableness all match. [[nodiscard]] inline bool sameRegistration(record::RecordInfo const& lhs, record::RecordInfo const& rhs) { return lhs.name == rhs.name && lhs.type == rhs.type && lhs.keyField == rhs.keyField && - lhs.derivedFrom == rhs.derivedFrom && lhs.privateKeys == rhs.privateKeys && - lhs.keyIsString == rhs.keyIsString; + lhs.previousKeyField == rhs.previousKeyField && lhs.derivedFrom == rhs.derivedFrom && + lhs.privateKeys == rhs.privateKeys && lhs.keyIsString == rhs.keyIsString && lhs.table == rhs.table; } /// @brief Appends a problem for every `derivedFrom` cycle among the records. @@ -503,7 +531,9 @@ inline void findDerivationCycles(std::vector const& records, for (std::size_t index = 0; index < records.size(); ++index) { auto const& info = records[index]; indexOf.emplace(info.type, index); - if (info.keyField && !info.derivedFrom.empty()) { + // A table's record keeps its key: a source's change reaches it as a whole-record change, and its own + // actions name its rows. + if (info.keyField && !info.derivedFrom.empty() && !info.table) { problems.push_back("record `" + info.name + "` is derived from other records but has a key; a derived record is keyless"); } @@ -539,6 +569,15 @@ inline void findDerivationCycles(std::vector const& records, if (found == indexOf.end()) { continue; } + // An opaque holding names no path, so it neither hides nor is hidden by a path. + if (slot->opaque) { + auto const& info = records[found->second]; + if (std::ranges::find(matched, info.name, &ActionRecord::record) == matched.end()) { + matched.push_back( + ActionRecord{.record = info.name, .keyField = info.keyField, .paths = {}, .opaque = true}); + } + continue; + } if (std::ranges::any_of(kept, [&](std::string_view prefix) { return pathWithin(prefix, slot->path); })) { continue; } @@ -546,11 +585,35 @@ inline void findDerivationCycles(std::vector const& records, auto const& info = records[found->second]; auto entry = std::ranges::find(matched, info.name, &ActionRecord::record); if (entry == matched.end()) { - matched.push_back(ActionRecord{.record = info.name, .keyField = info.keyField, .paths = {}}); + matched.push_back( + ActionRecord{.record = info.name, .keyField = info.keyField, .paths = {}, .opaque = false}); entry = std::prev(matched.end()); } entry->paths.push_back(slot->path); } + // A holder above a record's rows says which of its members open or make partial what holds them. + for (auto& entry : matched) { + for (auto const& holder : result.holders) { + bool const above = std::ranges::any_of(entry.paths, [&](std::string const& path) { + return holder.path != path && pathWithin(holder.path, path); + }); + if (!above) { + continue; + } + auto const at = [&](std::string const& member) { + return holder.path.empty() ? member : holder.path + "." + member; + }; + for (auto const& member : holder.open) { + if (std::ranges::find(entry.open, at(member)) == entry.open.end()) { + entry.open.push_back(at(member)); + } + } + if (!holder.partial.empty() && + std::ranges::find(entry.partial, at(holder.partial)) == entry.partial.end()) { + entry.partial.push_back(at(holder.partial)); + } + } + } if (!matched.empty()) { for (auto const& entry : matched) { resolved.holding[entry.record].push_back(actionId); diff --git a/include/morph/core/records.hpp b/include/morph/core/records.hpp index eebf236af..d7b5dff0f 100644 --- a/include/morph/core/records.hpp +++ b/include/morph/core/records.hpp @@ -53,12 +53,18 @@ struct RecordInfo { std::type_index type; /// The glaze JSON name of the key member; empty for a keyless record or one without an `id` member. std::optional keyField; + /// The glaze JSON name of the member holding the key a record had before an action changed it, collected beside + /// `keyField` at the same paths; empty for a record whose key does not change. `"from"` on a table's record. + std::optional previousKeyField; /// The source types this record is derived from. std::vector derivedFrom; /// True when the record's keys must not reach other principals. bool privateKeys = false; /// True when the key's raw type is `std::string`; false when it is integral or there is no key. bool keyIsString = false; + /// True for a table's record, registered by `BRIDGE_REGISTER_TABLE`: keyed by `key`, and keyed even when it is + /// derived from other records, since a source's change reaches it as a whole-record change. + bool table = false; }; namespace detail { @@ -216,6 +222,39 @@ inline bool registerRecordOnce(std::string_view name) noexcept { return true; } +/// @brief Static-init helper for `BRIDGE_REGISTER_TABLE`: registers a table's record. +/// +/// The record is keyed by `key`, the member a `ChangedRow` names its row by, and marked `table`. +/// @tparam T The table's tag type, `morph::table::TableOf`. +/// @tparam Opts Any of `privateKeys` and `derivedFrom<>`. +/// @param name The record's wire name, `.`. +/// @return Always true, so the result can initialise a namespace-scope variable. +template +inline bool registerTableRecordOnce(std::string const& name) noexcept { + // NOLINTNEXTLINE(misc-static-assert,cert-dcl03-c) + assert(!::morph::model::registrationPhaseClosed() && + "registerTableRecordOnce: registration after the registration phase closed. The process-level " + "registries are unsynchronised and are read-only once dispatch begins -- registering now " + "races their internals against concurrent lookups. Load and register plugin modules before " + "the first dispatch."); + static_assert(((std::is_same_v || IsDerivedFrom::value) && ...), + "BRIDGE_REGISTER_TABLE: a table's record takes only privateKeys and derivedFrom<>"); + RecordInfo info{.name = name, .type = std::type_index{typeid(T)}, .keyField = "key", .derivedFrom = {}}; + info.table = true; + info.previousKeyField = "from"; + info.privateKeys = (std::is_same_v || ... || false); + // Unused when the table takes no options: the fold below is then empty. + [[maybe_unused]] auto const addSources = [](RecordInfo& target) { + if constexpr (IsDerivedFrom::value) { + [](RecordInfo& out, derivedFrom) { (out.derivedFrom.emplace_back(typeid(S)), ...); }( + target, O{}); + } + }; + (addSources.template operator()(info), ...); + mutableRecordRegistry().push_back(std::move(info)); + return true; +} + } // namespace detail } // namespace morph::record diff --git a/include/morph/core/registry.hpp b/include/morph/core/registry.hpp index 182297a59..a976fcc7c 100644 --- a/include/morph/core/registry.hpp +++ b/include/morph/core/registry.hpp @@ -23,6 +23,7 @@ #include #include +#include "../forms/derive.hpp" #include "../forms/field_errors.hpp" #include "../forms/forms.hpp" #include "detail/action_guard_core.hpp" @@ -498,6 +499,30 @@ inline std::string actionPayloadSchema() { } } +/// @brief Whether @p Action runs itself: it declares a static `invoke(Model&, Action&)`, as a table's actions +/// do, instead of the model declaring an `execute` for it. +template +concept DeclaresInvoke = requires(Model& model, Action& action) { Action::invoke(model, action); }; + +/// @brief Runs @p action on @p model: the one call every dispatch path makes to a handler. +/// +/// `Action::invoke(model, action)` when the action declares one, `model.execute(action)` otherwise. An action +/// that the framework defines for a model, such as a table's query, carries its handler with it, so the model +/// declares nothing for it. +/// @tparam Model The model type. +/// @tparam Action The action type. +/// @param model The model instance. +/// @param action The action. +/// @return What the handler returns: a value, or a `core::async::Task` of one. +template +decltype(auto) invokeExecute(Model& model, Action& action) { + if constexpr (DeclaresInvoke) { + return Action::invoke(model, action); + } else { + return model.execute(action); + } +} + /// @brief The request id of the session installed on the calling thread, or /// empty when there is none: the text that links one dispatch's /// profiler zones across the threads it crosses. @@ -741,8 +766,9 @@ template /// @return Reference to the process-lifetime description for `A`. template [[nodiscard]] inline const ActionDescription& actionDescription() { - static const ActionDescription kDesc = buildActionDescription(); - return kDesc; + // Named so no name of the including translation unit's global scope hides it (MSVC C4459). + static const ActionDescription cachedActionDescription = buildActionDescription(); + return cachedActionDescription; } class ActionDispatcher; @@ -838,7 +864,8 @@ class ActionDispatcher { Key key{std::string{modelId}, std::string{actionId}}; detail::claimId(_actionTypes, "action", key, key.first + "/" + key.second, std::type_index{typeid(Action)}); ActionEntry& entry = _actions[std::move(key)]; - if constexpr (isTaskHandler().execute(std::declval()))>) { + if constexpr (isTaskHandler(), + std::declval()))>) { entry.asyncRunner = &runTaskHandler; entry.runner = [](IModelHolder&, std::string_view) -> std::string { throw std::logic_error{ @@ -894,7 +921,9 @@ class ActionDispatcher { // bypassing every client-side gate. A tampered computed value on // the wire is discarded here, before the validator check and // Model::execute run. No-op for actions with no computedFields. See - // docs/spec/forms/forms.md. + // docs/spec/forms/forms.md. A derived member is the model's to set: what the client sent for it is cleared + // first, so neither the model nor a computed field over it reads a forged value. + ::morph::forms::clearDerived(action); ::morph::forms::recomputeAll(action); // Enforce the action's validator on the server dispatch path — the // one path an untrusted remote client can drive directly with a @@ -924,6 +953,7 @@ class ActionDispatcher { MORPH_ZONE("ActionDispatcher::evaluateAction"); auto action = ActionTraits::fromJson(payloadJson); ::morph::forms::reconcileDeclaredPrecision(action); + ::morph::forms::clearDerived(action); ::morph::forms::recomputeAll(action); Evaluation evaluation; evaluation.errors = ::morph::forms::fieldErrors(action); @@ -964,7 +994,7 @@ class ActionDispatcher { detail::runGuardJournaled(holder, model, action, [&] { return std::string{payloadJson}; }); auto result = [&] { try { - return model.execute(action); + return detail::invokeExecute(model, action); } catch (const std::exception& exc [[maybe_unused]]) { if constexpr (detail::actionLoggable() == Loggable::Yes) { if (holder.hasActionLog()) { @@ -1027,7 +1057,7 @@ class ActionDispatcher { static void runTaskHandler(IModelHolder& holder, std::string_view payloadJson, const std::shared_ptr<::morph::exec::detail::TaskResumer>& executor, ::core::async::StopToken token, DispatchDone done) { - using R = HandlerResultT().execute(std::declval()))>; + using R = HandlerResultT(), std::declval()))>; // Owned here and kept by the completion callback: the handler may take // the action by reference, and its frame outlives this call. std::shared_ptr action; @@ -1036,7 +1066,7 @@ class ActionDispatcher { action = std::make_shared(prepareAction(payloadJson)); auto& model = holder.template into(); detail::runGuardJournaled(holder, model, *action, [&] { return std::string{payloadJson}; }); - task = model.execute(*action); + task = detail::invokeExecute(model, *action); } catch (...) { done(std::string{}, std::current_exception()); return; @@ -1315,6 +1345,22 @@ class ActionDispatcher { } } + /// @brief The schema `(modelId, actionId)` serves, as `schemasJson` lists it. + /// @param modelId Model type-id. + /// @param actionId Action type-id. + /// @return The schema's JSON text; empty when the pair is unregistered or its description cannot be produced. + [[nodiscard]] std::string actionSchema(std::string_view modelId, std::string_view actionId) const { + auto iter = _actions.find(detail::PairKeyView{modelId, actionId}); + if (iter == _actions.end()) { + return {}; + } + try { + return iter->second.describe().schema; + } catch (const std::exception&) { + return {}; + } + } + /// @brief The model type-ids @p actionId is registered under. /// /// An action id names one action, but the pair registered is @@ -1641,9 +1687,40 @@ inline bool registerActionResultOnce(std::string_view actionId) noexcept { } return true; } - entries.emplace( - std::string{actionId}, - ActionResult{.action = action, .resultSlots = walkResult::Result>()}); + entries.emplace(std::string{actionId}, + ActionResult{.action = action, + .resultSlots = walkResult::Result>(), + .holders = walkHolders::Result>()}); + return true; +} + +/// @brief Static-init helper for `BRIDGE_REGISTER_TABLE`: records that @p Action's result holds @p Record at no +/// path, beside the slots its walk found. +/// +/// Runs after the action's `registerActionResultOnce`, in the same translation unit. Idempotent: a repeat adds +/// nothing. Under an id another action type took, it adds nothing, since that id is already a conflict. +/// @tparam Action The action type; `ActionTraits` must be visible. +/// @tparam Record The record type the result holds. +/// @param actionId The action's registered type-id. +/// @return Always true, so the result can initialise a namespace-scope variable. +template +inline bool registerOpaqueResultOnce(std::string_view actionId) noexcept { + // NOLINTNEXTLINE(misc-static-assert,cert-dcl03-c) + assert(!::morph::model::registrationPhaseClosed() && + "registerOpaqueResultOnce: registration after the registration phase closed. The process-level " + "registries are unsynchronised and are read-only once dispatch begins -- registering now " + "races their internals against concurrent lookups. Load and register plugin modules before " + "the first dispatch."); + auto& entries = mutableActionResultSlots(); + auto const existing = entries.find(actionId); + if (existing == entries.end() || existing->second.action != std::type_index{typeid(Action)}) { + return true; + } + std::type_index const record{typeid(Record)}; + auto& held = existing->second.resultSlots; + if (std::ranges::none_of(held, [&](ResultSlot const& slot) { return slot.opaque && slot.type == record; })) { + held.push_back(ResultSlot{.type = record, .path = {}, .opaque = true}); + } return true; } @@ -2208,6 +2285,78 @@ void actionSourceRegistrationRequired() {} BRIDGE_DETAIL_ACTION_REGISTRARS(M, A) // clang-format on +/// @cond detail +/// The table's record and its action's opaque holding, suppressed under `MORPH_CLIENT_ONLY` like every +/// registrar that records facts only a process hosting models serves. The holding is registered after the +/// action's result slots, which the action registrars before it in the same translation unit record. +#ifdef MORPH_CLIENT_ONLY +#define MORPH_DETAIL_REGISTER_TABLE_LOCAL(M, KEY, ID, ...) +#else +// clang-format off -- public macro surface; see CONTRIBUTING.md, "Formatting/linting". +#define MORPH_DETAIL_REGISTER_TABLE_LOCAL(M, KEY, ID, ...) \ + namespace { \ + [[maybe_unused]] const bool BRIDGE_DETAIL_CAT(bridge_table_record_reg_, __COUNTER__) = \ + ::morph::table::detail::registerTableRecord( \ + std::string{::morph::model::ModelTraits::typeId()} + "." ID); \ + [[maybe_unused]] const bool BRIDGE_DETAIL_CAT(bridge_table_held_reg_, __COUNTER__) = \ + ::morph::model::detail::registerOpaqueResultOnce<::morph::table::QueryTable, \ + ::morph::table::TableOf>( \ + ::morph::model::ActionTraits<::morph::table::QueryTable>::typeId()); \ + } +// clang-format on +#endif +/// @endcond + +/// @brief Registers table @p ID of model @p M, served by @p FN. +/// +/// @p FN is a member function `table::ServedTable (M::*)(table::TableContext const&)`, or +/// `morph::table::typed(&M::fn)` for a function returning `std::shared_ptr const>`, whose +/// description is built from `Row` and whose key is the key of the record registered for `Row`. The macro emits: +/// +/// - `morph::table::TableTraits<&M::fn>`, keyed on the member function in both forms, so +/// `table::TableOf<&M::fn>`, `table::ChangedRows<&M::fn>`, `effects::updatesTable<&M::fn>` and +/// `effects::changesTable<&M::fn>` name the table by its function; +/// - the actions `"Table." ID` (`table::QueryTable`, a `TableQuery` in, a `GenericPage` out), +/// `"Table." ID ".describe"` (`table::DescribeTable`, the `TableDescription`) and `"Table." ID ".resolve"` +/// (`table::ResolveTable`, a `ResolveRequest` in, the `SelectedRows` out), all `Loggable::No`: they read; +/// - the table's record, `table::TableOf<&M::fn>`, named `.` ID and keyed by `key`; +/// - that `"Table." ID` holds that record opaquely, at no path: a principal who may run it may watch the +/// record, and no reader looks for rows in a page. +/// +/// **A table id is unique in the process**, not only in its model: the action ids carry the id and no model, +/// and two action types under one id fail every effects lookup of the process ("action `Table.` is +/// registered by two action types; give each its own id"). +/// +/// `BRIDGE_REGISTER_MODEL(M, ...)` must come before it, and the translation unit must include +/// `` and ``, as for `BRIDGE_REGISTER_ACTION`. Place it where +/// every translation unit that names the table's `TableOf` or `ChangedRows` sees it, as a model's header. +/// @param M Concrete model type. +/// @param ID The table's id, a string literal, unique in the process. +/// @param FN `&M::fn` or `morph::table::typed(&M::fn)`. +/// @param ... Options of the table's record: `morph::table::rowScoped` (its keys are private: callers see +/// different rows) and `morph::table::derivedFrom` (a change of any of them is a change of +/// the table). +// clang-format off -- public macro surface; see CONTRIBUTING.md, "Formatting/linting". +#define BRIDGE_REGISTER_TABLE(M, ID, FN, ...) \ + template <> \ + struct morph::table::TableTraits<::morph::table::detail::tableKey(FN)> { \ + using model = M; \ + using row = ::morph::table::detail::TableRow; \ + static constexpr bool registered = true; \ + static constexpr std::string_view id = ID; \ + static constexpr auto serve = FN; \ + }; \ + BRIDGE_DETAIL_ACTION_TRAITS_BODY(M, ::morph::table::QueryTable<::morph::table::detail::tableKey(FN)>, \ + ::morph::table::GenericPage, "Table." ID, ::morph::model::Loggable::No) \ + BRIDGE_DETAIL_ACTION_TRAITS_BODY(M, ::morph::table::DescribeTable<::morph::table::detail::tableKey(FN)>, \ + ::morph::table::TableDescription, "Table." ID ".describe", \ + ::morph::model::Loggable::No) \ + BRIDGE_DETAIL_ACTION_TRAITS_BODY(M, ::morph::table::ResolveTable<::morph::table::detail::tableKey(FN)>, \ + ::morph::table::SelectedRows, "Table." ID ".resolve", \ + ::morph::model::Loggable::No) \ + MORPH_DETAIL_REGISTER_TABLE_LOCAL(M, ::morph::table::detail::tableKey(FN), ID __VA_OPT__(, ) __VA_ARGS__) +// clang-format on + /// @brief Registers a readiness predicate for action @p A. /// /// Specialises `morph::model::ActionValidator` so that @p FN gates @p A on every diff --git a/include/morph/core/remote.hpp b/include/morph/core/remote.hpp index f576b7bfe..71ab263c0 100644 --- a/include/morph/core/remote.hpp +++ b/include/morph/core/remote.hpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -21,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +32,7 @@ #include "../core/backend.hpp" #include "../journal/action_log.hpp" #include "../session/session.hpp" +#include "../table/runtime.hpp" #include "../util/datetime.hpp" #include "changes.hpp" #include "completion.hpp" @@ -371,6 +374,19 @@ struct ServerConfig { /// the instant is judged by reading `clock`, never by the length of the sleep. Not positive is refused by the /// constructor. std::chrono::milliseconds clockRecheck{1000}; + + /// @brief Where a table's reply is built: the sort, the filter and the page of a `Table.` action, after + /// the table's function has run on the model's strand. Null: the server's worker pool. + /// + /// A pool, so that a sort of many rows holds neither the model's strand nor the server's. + std::shared_ptr<::morph::exec::IExecutor> tableWork; + + /// @brief The server's one view cache: its bound, across every table, and the hook called where a view is + /// computed. + /// + /// A table's computed views (its sort and filter over one snapshot) are kept and read by every page, keyed + /// fetch and watcher of the same sort and filter, until the rows or an order level change. + ::morph::table::ViewCacheOptions views; }; /// @brief Server-side message handler that owns model instances and dispatches actions. @@ -525,7 +541,19 @@ class RemoteServer : public std::enable_shared_from_this { _config{validated(std::move(config))}, _executeTimeouts{_config.limits.executeTimeout.count() > 0 ? std::make_unique<::morph::async::detail::TimeoutScheduler>() - : nullptr} { + : nullptr}, + _settle{std::make_shared<::morph::exec::OwnerStrand>(workerPool)}, + _views{::morph::table::makeViewCache(_config.views)}, + _tableRuntime{.work = _config.tableWork != nullptr ? _config.tableWork.get() : &workerPool, + .views = _views.get(), + .settle = _settle.get(), + .settleKeep = _settle, + .schemaOf = [&dispatcher](std::string_view action) { + // A description names an edit action by its id alone: the first model registering the id + // serves its schema. + std::vector const models = dispatcher.modelsOf(action); + return models.empty() ? std::string{} : dispatcher.actionSchema(models.front(), action); + }} { // The first read of the record and effects registries: an invalid // declaration fails the server's construction rather than its first // successful execute, whose changes are derived from them. @@ -548,6 +576,8 @@ class RemoteServer : public std::enable_shared_from_this { ~RemoteServer() { _strand.seal(); _strand.close(); + // A resolve still queued on an outside `tableWork` delivers to a closed strand, which drops it. + _settle->close(); } /// @brief Asynchronously processes a JSON `Envelope` and calls @p reply with the response. @@ -866,6 +896,80 @@ class RemoteServer : public std::enable_shared_from_this { void fanOut(::morph::effects::Changes changes, ConnectionId caller, std::string_view callerPrincipal) { assert(_strand.runningHere() && "RemoteServer::fanOut runs on the server strand"); noteOwner("RemoteServer::fanOut"); + // Before any event is queued: a client that refetches because of the event reads what the observers left. + for (auto const& observer : _observers) { + try { + observer->changed(changes); + } catch (std::exception const& exc) { + ::morph::log::logError("[fanOut] an observer failed: {}", exc.what()); + } catch (...) { + ::morph::log::logError("[fanOut] an observer failed: unknown exception"); + } + } + fanOutEvents(std::move(changes), caller, callerPrincipal); + } + + /// @brief Reports a change to rows of @p record that no execute made. Callable from any thread. + /// + /// The change is built as an execute's is: the record's derived records are added whole, and more than + /// `effects::kMaxChangeKeys` keys become a whole-type change. It is posted to the server strand and fanned out + /// with no caller, as a time fact's is, except that the change observers are not told: an arrival never + /// invalidates the cache that announced it. + /// @param record The record's wire name. + /// @param keys The changed rows' keys as raw JSON; absent for the whole type. + /// @return Nothing, or why the record was refused (`"unregistered record: "`); then nothing is sent. + std::expected announce(std::string_view record, + std::optional> keys) { + auto const& resolved = ::morph::effects::detail::resolved(); + if (resolved.recordNamed(record) == nullptr) { + return std::unexpected("unregistered record: " + std::string{record}); + } + std::string const name{record}; + ::morph::effects::Changes changes; + ::morph::effects::detail::addRecordChange(changes, name, std::move(keys)); + ::morph::effects::detail::addDerivedChanges(resolved, name, changes); + for (auto& change : changes.records) { + if (change.keys && change.keys->size() > ::morph::effects::kMaxChangeKeys) { + change.keys.reset(); + } + } + _strand.postTask([self = shared_from_this(), changes = std::move(changes)]() mutable { + self->fanOutEvents(std::move(changes), 0, std::string_view{}); + }); + return {}; + } + + /// @brief Tells @p observer of every change an execute or a time fact derives, and gives it the server's + /// announce sink. + /// + /// The application calls it after constructing the server. The observer is called on the server strand, + /// before the change's events are queued; the sink holds the server weakly and calls `announce`. + /// @param observer The observer, such as a `table::LevelCache`; null is ignored. + void attach(std::shared_ptr<::morph::effects::IChangeObserver> observer) { + if (observer == nullptr) { + return; + } + observer->bind( + [weak = weak_from_this()](std::string_view record, std::optional> keys) { + if (auto const self = weak.lock()) { + std::ignore = (self->announce(record, std::move(keys))); + } + }); + _strand.postTask([self = shared_from_this(), observer = std::move(observer)]() mutable { + self->_observers.push_back(std::move(observer)); + }); + } + + /// @brief The server's view cache's counters. Callable from any thread. + /// @return What the cache has done, and the bytes it holds. + [[nodiscard]] ::morph::table::ViewCacheStats viewStats() const { return ::morph::table::viewCacheStats(*_views); } + +private: + /// @brief `fanOut` without the observers: the events of @p changes. On the server strand. + /// @param changes What changed. + /// @param caller Connection the execute arrived on; `0` for none. + /// @param callerPrincipal The execute's verified principal; empty when none. + void fanOutEvents(::morph::effects::Changes changes, ConnectionId caller, std::string_view callerPrincipal) { askTimeFactsNamedIn(changes); std::map bodies; for (auto const& change : changes.records) { @@ -893,6 +997,7 @@ class RemoteServer : public std::enable_shared_from_this { } } +public: /// @brief The server strand, as an executor. /// /// What `runningOn(server.strand())` asks about: true inside every task the @@ -2880,6 +2985,7 @@ class RemoteServer : public std::enable_shared_from_this { try { ::morph::session::detail::ScopedContext const scoped{run.env.session}; ::morph::session::detail::ScopedOrigin const originScope{run.origin ? &*run.origin : nullptr}; + ::morph::table::TableRuntimeScope const tableScope{run.self->_tableRuntime}; result = run.self->_dispatcher.dispatch(run.env.modelType, run.env.actionType, *run.holder, run.env.body); } catch (...) { error = std::current_exception(); @@ -2897,6 +3003,7 @@ class RemoteServer : public std::enable_shared_from_this { try { ::morph::session::detail::ScopedContext const scoped{run->env.session}; ::morph::session::detail::ScopedOrigin const originScope{run->origin ? &*run->origin : nullptr}; + ::morph::table::TableRuntimeScope const tableScope{run->self->_tableRuntime}; auto const& strands = run->self->_strands; executor = std::make_shared<::morph::exec::detail::TaskResumer>(strands, run->mid, run->env.session, run->origin); @@ -3014,6 +3121,13 @@ class RemoteServer : public std::enable_shared_from_this { // Fixed at construction, so a model strand's finish can cancel through it // without a lock. std::unique_ptr<::morph::async::detail::TimeoutScheduler> const _executeTimeouts; + // The server's one view cache, made from `ServerConfig::views`. Its type stays incomplete here. + // The owner of a `resolve`'s completion: shared, so the work queued on `tableWork` keeps it alive. + std::shared_ptr<::morph::exec::OwnerStrand> const _settle; + std::shared_ptr<::morph::table::ViewCache> const _views; + // What a table's action reads during a dispatch: `tableWork`, or the worker pool, the view cache, and the owner of + // a `resolve`'s completion. Fixed at construction. + ::morph::table::TableRuntime const _tableRuntime; // ── Server-strand state: touched only in the server strand's tasks ────── // Every live instance, private and shared alike, plus the shared-instance @@ -3107,6 +3221,8 @@ class RemoteServer : public std::enable_shared_from_this { std::uint64_t _nextWindow{0}; // The reporters of time-derived facts; filled by the first envelope handled. std::vector _timeFacts; + // The attached change observers, told of every execute's and time fact's changes. + std::vector> _observers; bool _timeFactsStarted{false}; // Drawn off the strand by openConnection(), which answers at once. diff --git a/include/morph/forms/derive.hpp b/include/morph/forms/derive.hpp new file mode 100644 index 000000000..ea9a5cc61 --- /dev/null +++ b/include/morph/forms/derive.hpp @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file forms/derive.hpp +/// @brief Derived values: members the model sets from the domain's data (`derived()`, `x-derived`), the derive action +/// a form asks for them through (`DeriveOf`, `Derived`), the server's clearing of what a client sent for them +/// (`clearDerived`), and the round types a `FormSession` asks for derived and computed values with. +/// +/// Specified in `docs/spec/table/editing.md`, "Derived values", and `docs/spec/forms/engine.md`, "Derived values". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../core/completion.hpp" +#include "../reactive/scheduler.hpp" +#include "forms.hpp" + +namespace morph::forms { + +/// @brief The input of a derive action: the form's body as far as it encodes. +/// +/// A derive action is declared as a type deriving from it, `struct DeriveSieve : forms::DeriveOf {};`, +/// and registered as any action of the form's model, `Loggable::No` and with no effects, so a derive call is a read. +/// Its JSON is `{"body": …}`; the in-class glaze meta is inherited by the deriving type. +/// @tparam Action The form's action. +template +struct DeriveOf { + /// @brief The form's body; a member that was blank or did not encode is at its default. + Action body; + + /// @brief glaze's meta: the one member `body`. + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks the meta type up by this name. + struct glaze { + /// @brief The described type. + using T = DeriveOf; + /// @brief `{"body": body}`. + static constexpr auto value = glz::object("body", &T::body); + }; +}; + +/// @brief The values of derived members, by path into the body that was sent: what a derive action returns. Its JSON +/// is `{"values": [{"path": "specimens[3].density", "value": …}, …]}`. +struct Derived { + /// @brief One derived member's value. + struct Value { + /// @brief The member's path into the body sent: `name`, or `rows[i].member` for a row's member. + std::string path; + /// @brief The member's wire value. + glz::raw_json value; + }; + /// @brief The values, each path once. + std::vector values; +}; + +/// @brief Builds the `FieldMeta` of a derived member: `describe(label, help).withDerived()`. +/// @tparam MemberPtr Pointer to the member, e.g. `&Specimen::limit`. +/// @param label Display label; empty infers one from the member name. +/// @param help Help text; empty omits `description`. +/// @return The descriptor, `derived` set. +template +[[nodiscard]] FieldMeta derived(std::string_view label = {}, std::string_view help = {}) noexcept { + return describe(label, help).withDerived(); +} + +namespace detail { + +/// @brief Value-initialises the members of @p action its type's `fieldMetadata` marks derived, not descending into +/// nested aggregates. +/// @tparam A The action or row type, one with field metadata. +/// @param action The value cleared in place. +template +void clearOwnDerived(A& action) { + using Plain = std::remove_cvref_t; + constexpr auto memberCount = reflectedCount(); + [&](std::index_sequence) { + [[maybe_unused]] auto clear = [&]() { + // A `glz::meta` entry that computes its value yields a value: there is no stored member to clear. + [[maybe_unused]] decltype(auto) member = morph::detail::reflectedMember(action); + using Member = std::remove_cvref_t; + // Assignability of the reference itself: a const member, or a const accessor, is never cleared. + if constexpr (std::is_lvalue_reference_v && std::is_default_constructible_v && + std::is_assignable_v) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): Idx < size. + if (detail::declaredDerived(glz::reflect::keys[Idx])) { + member = Member{}; + } + } + }; + (clear.template operator()(), ...); + }(std::make_index_sequence{}); +} + +} // namespace detail + +/// @brief Value-initialises every derived member of @p action (`FieldMeta::derived` in its type's `fieldMetadata`), +/// and of every nested aggregate of it (each element of a `std::vector` member, a nested struct member, either +/// inside an engaged `std::optional`, recursively: `detail::forEachNested`): what every execution path runs +/// before the model, so a derived value a caller sent is never the one kept. +/// @tparam A The action or row type. +/// @param action The value cleared in place. +template +void clearDerived(A& action) { + using Plain = std::remove_cvref_t; + if constexpr (detail::WrittenAsMember) { + clearDerived(action.*(glz::meta::value)); + } else if constexpr (glz::reflectable || glz::glaze_object_t) { + // Only a type with field metadata can mark a member derived, and the member walk reads the names, which needs + // the type to have linkage. The check stays out here, not in the walk's lambda: MSVC instantiates a discarded + // branch there whose condition does not depend on the lambda's own parameters. + if constexpr (detail::HasFieldMetadata) { + detail::clearOwnDerived(action); + } + detail::forEachNested(action, [](auto& nested) { clearDerived(nested); }); + } else { + static_cast(action); + } +} + +/// @brief Where a form's derived values stand. +enum class DeriveState : std::uint8_t { + Current, ///< No round is in flight, and the last one succeeded (or none was made). + Running, ///< A round is in flight. + Failed, ///< The last round's evaluation or derive call failed; the values are the last ones loaded. +}; + +/// @brief How a `FormSession` asks for its derived and computed values. +struct DeriveOptions { + /// @brief Evaluates the action over a body (`ActionDispatcher::evaluate`): the recomputed body in, as JSON. Empty + /// makes no evaluation. + std::function(std::string bodyJson)> evaluate; + /// @brief Calls the form's derive action with `{"body": }`: a `Derived` reply. Empty makes no derive call. + std::function(std::string deriveBodyJson)> derive; + /// @brief The timers the debounce runs on; null starts a round at each commit. + reactive::Scheduler* scheduler = nullptr; + /// @brief How long after a commit, with no further commit, a round starts. + std::chrono::milliseconds debounce{150}; + /// @brief Told the paths a derive reply named that are no derived member, which the round dropped; empty tells + /// no one. + std::function const&)> refused; +}; + +/// @brief One round as it was sent: its sequence, its body, and the rows each collection held then. +struct DeriveRound { + /// @brief The round's sequence; a later round has a greater one. + std::uint64_t sequence = 0; + /// @brief The body sent (`FormSession::partialBody`). + std::string body; + /// @brief The row keys of each collection, by the collection's path, in the order the body wrote them. + std::map, std::less<>> rowKeys; +}; + +/// @brief What a load wrote, and what it refused. +struct DeriveLoad { + /// @brief How many members it wrote. + std::size_t loaded = 0; + /// @brief The paths it refused: a path that names no member of the kind the reply writes. + std::vector refused; +}; + +} // namespace morph::forms diff --git a/include/morph/forms/engine/collection.hpp b/include/morph/forms/engine/collection.hpp index 568f7b29e..17f5a03c5 100644 --- a/include/morph/forms/engine/collection.hpp +++ b/include/morph/forms/engine/collection.hpp @@ -63,6 +63,8 @@ struct CollectionColumn { std::optional decimalPlaces; /// @brief The unit appended to an exact value (`ExtUnits.unitUnicode`, else `unitAscii`). std::string unit; + /// @brief `x-level`: the data level the column's cells need; empty is the base level. + std::string level; }; /// @brief One `v-rowAction` or `v-actions` entry. @@ -195,6 +197,14 @@ class CollectionModel { } column.kind = parsed; } + // A measure's cells name their units, and a collection's table has no registry to read them through: its + // sort and filters would be refused and its cells shown without their units. + if (column.kind == table::ColumnKind::Measure) { + return std::unexpected(SchemaError{ + .path = "v-columns." + column.field, + .message = "a collection cannot show a measure column, having no unit registry; serve the rows as a " + "model's table"}); + } Json const* const hidden = detail::engine::member(entry, "v-hidden"); column.hidden = hidden != nullptr && hidden->is_boolean() && hidden->get(); if (auto const places = @@ -202,6 +212,9 @@ class CollectionModel { column.decimalPlaces = static_cast(std::min(*places, math::kMaxDecimalPlaces)); } + if (auto const* const level = detail::engine::stringAt(entry, "x-level")) { + column.level = *level; + } if (Json const* const units = detail::engine::member(entry, "ExtUnits")) { auto const* const unicode = detail::engine::stringAt(*units, "unitUnicode"); auto const* const ascii = detail::engine::stringAt(*units, "unitAscii"); @@ -345,14 +358,16 @@ namespace detail::engine { return toJson(*value); } -/// @brief The table columns of a collection: every `v-columns` entry, hidden ones included, by field and kind. +/// @brief The table columns of a collection: every `v-columns` entry, hidden ones included, by field, kind and +/// level. /// @param model The collection model. /// @return The columns. [[nodiscard]] inline std::vector tableColumns(CollectionModel const& model) { std::vector columns; columns.reserve(model.columns().size()); for (CollectionColumn const& column : model.columns()) { - columns.push_back(table::ColumnInfo{.id = column.field, .kind = column.kind, .comparator = {}, .format = {}}); + columns.push_back(table::ColumnInfo{ + .id = column.field, .kind = column.kind, .comparator = {}, .format = {}, .level = column.level}); } return columns; } diff --git a/include/morph/forms/engine/collection_view.hpp b/include/morph/forms/engine/collection_view.hpp index deab1ab23..c5e5b18a0 100644 --- a/include/morph/forms/engine/collection_view.hpp +++ b/include/morph/forms/engine/collection_view.hpp @@ -36,6 +36,11 @@ struct CollectionChrome { /// @brief Replaces each row's cells and buttons: the rows are then a list of these nodes rather than a table. /// Called once per row mounted, with the session and the row's signal (read it inside bindings). std::function const&)> row; + /// @brief Replaces the rows table whole: an interpreter lowers it as it lowers its other tables, over the + /// session's `source()`. Called once, with the session and what draws a row's buttons (Open and the row + /// actions) for its key text; that is empty when the view has neither. Unused while `row` is set. + std::function const& buttons)> + rows; /// @brief Replaces the confirm dialog: mounted while an action waits for confirmation, unmounted once it is /// answered. Called with the session, whose `pendingConfirm`, `confirm` and `cancelConfirm` it uses. std::function confirm; @@ -174,8 +179,9 @@ namespace detail::engine { return table; } -/// @brief The rows: a table of the visible columns' cells and the row buttons, or a list of the row chrome's nodes. -/// In a master-detail view a row is selected while the editor is open on it, and selecting one opens it. +/// @brief The rows: a table of the visible columns' cells and the row buttons, a list of the row chrome's nodes, or +/// the rows chrome's table. In a master-detail view a row is selected while the editor is open on it, and +/// selecting one opens it. /// @param session The session. /// @param options The view options, shared with the row views. /// @return The rows. @@ -190,6 +196,15 @@ namespace detail::engine { [view, options](reactive::Signal const& slot) { return options->chrome.row(*view, slot); }); return list; } + bool const buttons = + session.model().rowAction().has_value() || !actionsOf(session.model(), CollectionActionScope::Row).empty(); + if (options->chrome.rows) { + std::function drawn; + if (buttons) { + drawn = [view, options](std::string const& rowKey) { return rowButtons(*view, rowKey, *options); }; + } + return options->chrome.rows(session, drawn); + } std::vector columns; std::vector fields; for (CollectionColumn const& column : session.model().columns()) { @@ -198,8 +213,6 @@ namespace detail::engine { fields.push_back(column.field); } } - bool const buttons = - session.model().rowAction().has_value() || !actionsOf(session.model(), CollectionActionScope::Row).empty(); if (buttons) { columns.push_back(ui::TableColumn{.label = std::string{}}); } diff --git a/include/morph/forms/engine/field_control.hpp b/include/morph/forms/engine/field_control.hpp new file mode 100644 index 000000000..d7a6ae19a --- /dev/null +++ b/include/morph/forms/engine/field_control.hpp @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file forms/engine/field_control.hpp +/// @brief The built-in control of a scalar field: the forms control a form's cell and a grid's cell editor both draw. +/// +/// Specified in `docs/spec/forms/engine.md`, "Rendering". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../ui/view.hpp" +#include "form_session.hpp" + +namespace morph::forms::detail::engine { + +/// @brief Whether a text property says something: bound, or a constant that is not empty. +/// @param text The property. +/// @return Whether it is set. +[[nodiscard]] inline bool isSet(ui::Prop const& text) { + return text.isBound() || !text.constant().empty(); +} + +/// @brief The last reply or failure. +/// @param session The session. +/// @return `error: `, `ok: `, or empty before the first answer. +[[nodiscard]] MORPH_API std::string resultText(FormSession const& session); + +/// @brief A draft wall clock (`YYYY-MM-DDTHH:MM[:SS]`, or a `YYYY-MM-DD` date) as the instant it denotes. +/// @param text The draft. +/// @param date Whether the field holds a date. +/// @param offsetMinutes The display zone. +/// @return The instant, or `std::nullopt` while the draft is not a complete one. +[[nodiscard]] MORPH_API std::optional draftInstant(std::string_view text, bool date, + int offsetMinutes); + +/// @brief The draft a date-time control writes for an instant (blank for none). +/// @param value The instant. +/// @param date Whether the field holds a date. +/// @param offsetMinutes The display zone. +/// @return `YYYY-MM-DDTHH:MM:SS` in the zone, or `YYYY-MM-DD`. +[[nodiscard]] MORPH_API std::string instantDraft(std::optional const& value, bool date, + int offsetMinutes); + +/// @brief The view-tree field state of a field: read-only, required, its error as the one message shown, and its +/// help as the control's description, which assistive technology associates with the control. +/// @param field The field. +/// @return The state, bound to the field. +[[nodiscard]] MORPH_API ui::FieldState fieldState(FieldState const* field); + +/// @brief The `Common` of a field's control: its test id (`field_`) and accessible name (its label). +/// @param field The field. +/// @return The common part. +[[nodiscard]] MORPH_API ui::Common controlCommon(FieldState const* field); + +/// @brief A Select over the field's options (an Enum's, or a Choice's as last fetched), keyed by each option's +/// JSON literal, so an id past 2^53 is never a number on the way. +/// @param field The field. +/// @param style Dropdown or radio. +/// @return The control. +[[nodiscard]] MORPH_API ui::Node optionSelect(FieldState* field, ui::SelectStyle style); + +/// @brief The built-in control of a scalar field (the table in `docs/spec/forms/engine.md`, "Rendering"): every kind +/// but an Object and an ObjectArray, each of which draws its members' cells. +/// @param session The session: a date or date-time control reads its display zone and its pattern. +/// @param state The field. +/// @return The control. +// One case per kind. +// NOLINTNEXTLINE(readability-function-cognitive-complexity) +[[nodiscard]] MORPH_API ui::Node scalarControl(FormSession& session, FieldState& state); + +} // namespace morph::forms::detail::engine diff --git a/include/morph/forms/engine/field_model.hpp b/include/morph/forms/engine/field_model.hpp index 263b661f5..ee9c78e02 100644 --- a/include/morph/forms/engine/field_model.hpp +++ b/include/morph/forms/engine/field_model.hpp @@ -182,8 +182,13 @@ struct FieldSpec { bool readOnly = false; /// @brief `x-hidden`. bool hidden = false; + /// @brief `x-computed`: a member the action recomputes, which only a round writes; `computedInputs` alone cannot + /// tell an `x-computed` with no inputs from none. + bool computed = false; /// @brief `x-computed.inputs`: the members a computed field derives from. std::vector computedInputs; + /// @brief `x-derived`: a member the model sets from the domain's data, which only a round writes. + bool derived = false; /// @brief `minimum`, as canonical decimal text. std::optional minimum; /// @brief `maximum`, as canonical decimal text. @@ -229,6 +234,10 @@ struct FieldSpec { std::int64_t sliderStep = 1; /// @brief An Array's item JSON type (`"string"` when undeclared). std::string itemType; + /// @brief An Array's or ObjectArray's `minItems`: the fewest rows it holds, which a grid's row deletion keeps. + std::optional minItems; + /// @brief An Array's or ObjectArray's `maxItems`: the most rows it holds, which a grid's row insertion keeps. + std::optional maxItems; /// @brief An Object's members, or an ObjectArray's element members, in `x-order`. std::vector children; /// @brief An Object or ObjectArray whose members are not described: its `$ref` is already on @@ -594,8 +603,10 @@ class SchemaReader { spec.required = required; spec.readOnly = flagOf(raw, prop, "x-readonly"); spec.hidden = flagOf(raw, prop, "x-hidden"); + spec.derived = flagOf(raw, prop, "x-derived"); spec.widget = textOf(raw, prop, "x-widget"); if (Json const* const computed = either(raw, prop, "x-computed")) { + spec.computed = true; if (Json const* const inputs = member(*computed, "inputs"); inputs != nullptr && inputs->is_array()) { for (Json const& input : inputs->get_array()) { if (auto const* const text = input.get_if()) { @@ -657,6 +668,12 @@ class SchemaReader { } if (hasType("array")) { + if (auto const fewest = unsignedOf(member(prop, "minItems"))) { + spec.minItems = static_cast(*fewest); + } + if (auto const most = unsignedOf(member(prop, "maxItems"))) { + spec.maxItems = static_cast(*most); + } Json const* const rawItems = member(prop, "items"); Json const items = rawItems == nullptr ? emptyObject() : resolveProp(*rawItems); std::vector const itemTypes = jsonTypes(items); diff --git a/include/morph/forms/engine/form_session.hpp b/include/morph/forms/engine/form_session.hpp index c79fd0de2..f09474f66 100644 --- a/include/morph/forms/engine/form_session.hpp +++ b/include/morph/forms/engine/form_session.hpp @@ -16,7 +16,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -26,17 +28,8 @@ #include #include -#include "../../attributes.hpp" -#include "../../core/completion.hpp" #include "../../reactive/control.hpp" -#include "../../reactive/runtime.hpp" -#include "../../reactive/signal.hpp" -#include "../../render/i18n.hpp" -#include "../../render/locale_format.hpp" #include "../i18n.hpp" -#include "detail/text.hpp" -#include "field_model.hpp" -#include "rules.hpp" #include "values.hpp" namespace morph::forms { @@ -76,7 +69,7 @@ namespace detail::engine { /// @brief What every field of one session shares: the runtime, the model, the options, the /// Choice fetcher, and the hook a programmatic change ends with. -class SessionCore { +class MORPH_API SessionCore { public: /// @param runtime The runtime. Borrowed. /// @param model The form model. @@ -112,43 +105,24 @@ class SessionCore { /// @brief The options a value conversion reads. Tracked: a change of the number format (`setFormat`) or of the /// translations (`setTranslations`) reruns what read them. /// @return The value context. - [[nodiscard]] ValueContext const& values() const { - static_cast(_format.get()); - trackTexts(); - return _values; - } + [[nodiscard]] ValueContext const& values() const; /// @brief The pattern a date or date-time input shows and reads. Tracked. /// @param date `true` for the date pattern, `false` for the date-time pattern. /// @return The pattern; empty keeps ISO. - [[nodiscard]] std::string const& pattern(bool date) const { - static_cast(_format.get()); - return date ? _options.datePattern : _options.dateTimePattern; - } + [[nodiscard]] std::string const& pattern(bool date) const; /// @brief Replaces the number locale and the date patterns every field reads. Drafts keep their text; the /// fields check it again against the new format. /// @param locale The number format. Its views must outlive the session or the next call. /// @param datePattern The date pattern. /// @param dateTimePattern The date-time pattern. - void setFormat(render::NumericLocale locale, std::string datePattern, std::string dateTimePattern) { - _options.locale = locale; - _options.datePattern = std::move(datePattern); - _options.dateTimePattern = std::move(dateTimePattern); - _values.locale = locale; - _format.set(_format.peek() + 1); - } + void setFormat(render::NumericLocale locale, std::string datePattern, std::string dateTimePattern); /// @brief Replaces the translations and the locale every field text is resolved in, and reruns what read one. /// @param translations The catalog; empty shows every schema literal. /// @param bcp47 The locale. - void setTranslations(render::TranslationProvider translations, std::string bcp47) { - _options.translations = std::move(translations); - _options.bcp47 = std::move(bcp47); - _values.translations = _options.translations; - _values.bcp47 = _options.bcp47; - _texts.set(_texts.peek() + 1); - } + void setTranslations(render::TranslationProvider translations, std::string bcp47); /// @brief Records the translations and the locale as a dependency of the running computation, so a text it /// resolves follows `setTranslations`. @@ -163,11 +137,7 @@ class SessionCore { void onProgrammatic(std::function hook) { _programmatic = std::move(hook); } /// @brief Ends a programmatic change: automatic submission does not submit the body it produced. - void markProgrammatic() const { - if (_programmatic) { - _programmatic(); - } - } + void markProgrammatic() const; /// @brief Installs the top-level fields rules look up. /// @param fields The session's fields. Borrowed: they must outlive this core's use. @@ -182,7 +152,22 @@ class SessionCore { /// @return A lookup reading each named field's encoding. [[nodiscard]] RuleLookup lookup() const; + /// @brief Fetches a Choice's options through the fetcher, once per `(optionsAction, request)` for the session's + /// life: a second ask for a pair joins the fetch in flight or takes its reply. A failed fetch is not kept, + /// so the next ask fetches again. + /// @param action The options action. + /// @param request The request body. + /// @return The reply, delivered on the runtime's owner. + [[nodiscard]] async::Completion sharedChoices(std::string const& action, std::string request); + private: + // One shared options fetch: its reply once it arrived, and who waits for it until then. + struct SharedFetch { + std::optional reply; + std::vector::Promise> waiting; + }; + using Fetches = std::map, std::less<>>; + reactive::Runtime* _rt; FormModel _model; ChoiceFetcher _choices; @@ -193,6 +178,7 @@ class SessionCore { reactive::Signal _texts; std::function _programmatic; std::vector> const* _fields = nullptr; + std::shared_ptr _fetches = std::make_shared(); }; } // namespace detail::engine @@ -238,8 +224,16 @@ class RowState { std::vector> _fields; }; +/// @brief A collection row `FieldState::removeRows` took out, with the position it stood at. +struct RemovedRow { + /// @brief The row's position in the collection when it was removed. + std::size_t position = 0; + /// @brief The row, kept whole: its key and every member's draft and unit. + std::shared_ptr row; +}; + /// @brief The reactive state of one field: its draft and everything derived from it. -class FieldState { +class MORPH_API FieldState { public: /// @param core The session core. Borrowed: it must outlive the field. /// @param spec The field's spec. Borrowed from the core's model (or a parent's children). @@ -248,54 +242,7 @@ class FieldState { /// @param parent The containing Object or ObjectArray field, or null at the top level. // NOLINTNEXTLINE(misc-no-recursion): an Object's or ObjectArray row's members are fields, to the model's depth. FieldState(detail::engine::SessionCore& core MORPH_LIFETIMEBOUND, FieldSpec const& spec MORPH_LIFETIMEBOUND, - std::string path, std::vector> const* siblings, FieldState const* parent) - : _core{&core}, - _spec{&spec}, - _path{std::move(path)}, - _siblings{siblings}, - _parent{parent}, - _text{core.runtime(), std::string{}}, - _unit{core.runtime(), spec.entryUnit}, - _places{core.runtime(), std::optional{}}, - _engaged{core.runtime(), false}, - _rows{core.runtime(), std::vector>{}}, - _encoded{core.runtime(), [this] { return computeEncoding(); }}, - _error{core.runtime(), - [this] -> std::optional { - Encoding const& encoding = _encoded.get(); - if (encoding.has_value() && !encoding->has_value()) { - return encoding->error(); - } - return std::nullopt; - }}, - _visible{core.runtime(), - [this] { - if (_spec->hidden) { - return false; - } - return _parent != nullptr || - visibleVerdict(_core->model().rules(), _spec->name, _core->lookup()) != Tri::False; - }}, - _readonly{core.runtime(), - [this] { - if (_spec->readOnly || (_parent != nullptr && _parent->readonly().get())) { - return true; - } - return _parent == nullptr && - readonlyVerdict(_core->model().rules(), _spec->name, _core->lookup()) == Tri::True; - }}, - _required{core.runtime(), [this] { - return _spec->required || - (_parent == nullptr && - requiredVerdict(_core->model().rules(), _spec->name, _core->lookup()) == Tri::True); - }} { - if (_spec->kind == FieldKind::Object) { - for (FieldSpec const& child : _spec->children) { - _members.push_back( - std::make_unique(core, child, _path + "." + child.name, &_members, this)); - } - } - } + std::string path, std::vector> const* siblings, FieldState const* parent); ~FieldState() = default; FieldState(FieldState const&) = delete; @@ -314,17 +261,11 @@ class FieldState { /// @brief The label: the explicit key's translation, else the derived key's (top level /// only), else the schema's title. Tracked: it follows the session's `setTranslations`. /// @return The label. - [[nodiscard]] std::string label() const { - _core->trackTexts(); - return resolveSlot(i18n::FieldSlot::Label, _spec->title); - } + [[nodiscard]] std::string label() const; /// @brief The help text, resolved like the label. Tracked. /// @return The help text; empty when neither the schema nor the translations state one. - [[nodiscard]] std::string help() const { - _core->trackTexts(); - return resolveSlot(i18n::FieldSlot::Help, _spec->help); - } + [[nodiscard]] std::string help() const; /// @brief Whether the field has a help text now, read without tracking: what a view decides, when it is built, /// whether to give the help a line of its own. The line's text is `help()`, which follows the translations. @@ -333,15 +274,10 @@ class FieldState { return !_core->runtime().untracked([this] { return help(); }).empty(); } - /// @brief The placeholder: `x-placeholder` resolved like the label, else `defaultPlaceholder`. Tracked. + /// @brief The placeholder: the one `overridePlaceholder` set, else `x-placeholder` resolved like the label, else + /// `defaultPlaceholder`. Tracked. /// @return The placeholder. - [[nodiscard]] std::string placeholder() const { - if (_spec->placeholder.empty()) { - return defaultPlaceholder(*_spec); - } - _core->trackTexts(); - return resolveSlot(i18n::FieldSlot::Placeholder, _spec->placeholder); - } + [[nodiscard]] std::string placeholder() const; /// @brief The draft: what the control holds. Setting it is a user edit. /// @return The draft signal. @@ -355,6 +291,10 @@ class FieldState { /// @return The unit signal. [[nodiscard]] reactive::Signal& unit() noexcept { return _unit; } + /// @brief A Decimal's or Quantity's entry unit, read-only. + /// @return The unit signal. + [[nodiscard]] reactive::Signal const& unit() const noexcept { return _unit; } + /// @brief The field's places as a record gives them after the form was built, with the meaning of /// `x-decimalPlaces`: the canonical unit's entry places and the wire `dp`. Another unit of a Quantity keeps /// its own. Unset keeps the schema's. A change checks the draft again and leaves its text as typed. @@ -366,6 +306,10 @@ class FieldState { /// @return The engagement signal. [[nodiscard]] reactive::Signal& engaged() noexcept { return _engaged; } + /// @brief Whether the control was engaged, read-only. + /// @return The engaged signal. + [[nodiscard]] reactive::Signal const& engaged() const noexcept { return _engaged; } + /// @brief The draft's encoding. Tracked. /// @return The encoding computed. [[nodiscard]] reactive::Computed const& encoded() const noexcept { return _encoded; } @@ -378,8 +322,9 @@ class FieldState { /// @return The visibility computed. [[nodiscard]] reactive::Computed const& visible() const noexcept { return _visible; } - /// @brief Whether the field is frozen: `x-readonly`, a frozen parent, or a `readonlyWhen` naming it that is - /// True. + /// @brief Whether the field is frozen: `x-readonly`, `x-computed`, `x-derived`, a frozen parent, or a + /// `readonlyWhen` + /// naming it that is True. /// @return The read-only computed. [[nodiscard]] reactive::Computed const& readonly() const noexcept { return _readonly; } @@ -391,54 +336,35 @@ class FieldState { /// collection with no rows that was never engaged. Tracked. /// @return `true` when blank. // NOLINTNEXTLINE(misc-no-recursion): an Object asks its members. - [[nodiscard]] bool blank() const { - if (_spec->kind == FieldKind::Object) { - if (_spec->truncated) { - return detail::engine::trim(_text.get()).empty(); - } - // NOLINTNEXTLINE(misc-no-recursion): each member answers for itself. - return std::ranges::all_of(_members, [](auto const& entry) { return entry->blank(); }); - } - if (_spec->kind == FieldKind::ObjectArray) { - if (_spec->truncated) { - return detail::engine::trim(_text.get()).empty() && !_engaged.get(); - } - return _rows.get().empty() && !_engaged.get(); - } - return detail::engine::trim(_text.get()).empty(); - } + [[nodiscard]] bool blank() const; /// @brief What a rule sees of this field. Tracked. /// @return Blank, Invalid, or Valid with the exact value. - [[nodiscard]] RuleOperand ruleOperand() const { - Encoding const& encoding = _encoded.get(); - if (!encoding.has_value()) { - return RuleOperand{}; - } - if (!encoding->has_value()) { - return RuleOperand{.state = RuleOperand::State::Invalid, .value = {}}; - } - return RuleOperand{.state = RuleOperand::State::Valid, .value = (*encoding)->value}; - } + [[nodiscard]] RuleOperand ruleOperand() const; /// @brief The selectable options: an Enum's from the schema, a Choice's as last fetched for - /// its current parents. Tracked. + /// its current parents, less those `narrowOptions` leaves out. Tracked. /// @return The options; empty for every other kind, and for a Choice with nothing fetched. - [[nodiscard]] std::vector const& options() const { - if (_fetched) { - return _fetched->get(); - } - return _spec->enumOptions; - } + [[nodiscard]] std::vector const& options() const { return _offered.get(); } + + /// @brief Narrows the options `options()` offers to those whose value is listed: a grid column's `options` overlay + /// for the field's row. + /// @param keep The option values kept, as their JSON literals; nothing offers every option. + void narrowOptions(std::optional> keep); + + /// @brief Replaces the placeholder: a grid column's `placeholder` overlay for the field's row. + /// @param text The placeholder; empty restores the schema's. + void overridePlaceholder(std::string text) { _placeholderOverride = std::move(text); } + + /// @brief What an editor of the field runs as it opens: a Choice member of a collection row fetches its options + /// from now on (a column of rows fetches only for the rows a user opens), and a failed fetch is retried + /// (`retryOptions`). + void openOptions(); /// @brief Fetches a Choice's options again when the last fetch failed; does nothing otherwise. What opening its /// select runs, so options that could not be fetched when the form was built are fetched once the user /// asks for them. - void retryOptions() { - if (_optionsQuery != nullptr && !_optionsQuery->pending() && _optionsQuery->error() != nullptr) { - _optionsQuery->refetch(); - } - } + void retryOptions(); /// @brief Whether a Choice's options request is in flight. Tracked. /// @return `true` while fetching. @@ -447,23 +373,7 @@ class FieldState { /// @brief Switches a Quantity's entry unit, converting the draft exactly (half away from /// zero to the new unit's decimals). A user action. /// @param index The new unit, an index into `spec().units`. - void switchUnit(std::size_t index) { - std::size_t const current = _unit.peek(); - if (index >= _spec->units.size() || index == current || current >= _spec->units.size()) { - return; - } - UnitOption target = _spec->units.at(index); - if (index == 0 && _places.peek().has_value()) { - target.decimals = std::min(*_places.peek(), math::kMaxDecimalPlaces); - } - auto converted = convertDraft(_text.peek(), _spec->units.at(current), target, _core->values().locale); - _core->runtime().batch([&] { - _unit.set(index); - if (!detail::engine::trim(_text.peek()).empty()) { - _text.set(converted.value_or(std::string{})); - } - }); - } + void switchUnit(std::size_t index); /// @brief An Object's members, in `x-order`. /// @return The members; empty for every other kind. @@ -472,11 +382,7 @@ class FieldState { /// @brief An Object's member by wire name. /// @param name The wire name. /// @return The member, or null. - [[nodiscard]] FieldState* member(std::string_view name) const noexcept { - auto const found = - std::ranges::find_if(_members, [&](auto const& entry) { return entry->spec().name == name; }); - return found == _members.end() ? nullptr : found->get(); - } + [[nodiscard]] FieldState* member(std::string_view name) const noexcept; /// @brief A collection's rows, in order. Tracked. /// @return The rows; empty for every other kind. @@ -484,19 +390,12 @@ class FieldState { /// @brief Appends a blank row to a collection and engages it. A user action. /// @return The new row's key; 0 when the field is not a collection, or a truncated one. - std::uint64_t addRow() { - if (_spec->kind != FieldKind::ObjectArray || _spec->truncated) { - return 0; - } - auto row = std::make_shared(*_core, *_spec, _path, _nextRowKey++, this); - row->start(); - std::uint64_t const key = row->key(); - _core->runtime().batch([&] { - _rows.mutate([&](auto& rows) { rows.push_back(std::move(row)); }); - _engaged.set(true); - }); - return key; - } + std::uint64_t addRow(); + + /// @brief Inserts a blank row into a collection before the row at @p position and engages it. A user action. + /// @param position The new row's position; one past the end appends. + /// @return The new row's key; 0 when the field is not a collection, or a truncated one. + std::uint64_t insertRow(std::size_t position); /// @brief Removes a collection row by key. A user action. A holder of the row's `shared_ptr` (a mounted view) /// keeps its state alive until it lets go. @@ -505,14 +404,21 @@ class FieldState { _rows.mutate([&](auto& rows) { std::erase_if(rows, [&](auto const& row) { return row->key() == key; }); }); } + /// @brief Removes collection rows by key, in one change. A user action. + /// @param keys The rows' keys; a key the collection does not hold is skipped. + /// @return The rows removed, each with the position it stood at, ascending: what `restoreRows` puts back. + std::vector removeRows(std::span keys); + + /// @brief Puts rows `removeRows` took out back, each at the position it stood at, in one change. A user action. + /// @param rows The rows, ascending by position, as `removeRows` gave them; a position past the end appends. + void restoreRows(std::vector rows); + /// @brief What the field holds, as one string: two snapshots are equal exactly when the field holds the same - /// entry (draft, unit and engagement, and every member's and row's). Untracked. + /// entry (draft, unit and engagement, and every member's and row's). A computed or derived member, which + /// only a round of derived values writes, is no entry and is left out, so a round never makes a field look + /// edited or unsaved. Untracked. /// @return The snapshot. - [[nodiscard]] std::string snapshot() const { - std::string out; - appendSnapshot(out); - return out; - } + [[nodiscard]] std::string snapshot() const; /// @brief Whether loading @p value would leave what the field encodes unchanged: a scalar whose draft decodes /// from the wire value to the same body entry as the current draft, such as `1` and the record's `1.000`. @@ -520,290 +426,65 @@ class FieldState { /// rather than compared). Untracked. /// @param value The wire value, or null for blank. /// @return `true` when the current draft already encodes as @p value does. - [[nodiscard]] bool encodesLike(detail::engine::Json const* value) const { - if (_spec->truncated || _spec->kind == FieldKind::Object || _spec->kind == FieldKind::ObjectArray) { - return false; - } - bool const present = value != nullptr && !value->is_null(); - std::string draft = present ? decodeScalar(*_spec, *value, _core->values(), _places.peek()) : std::string{}; - std::size_t const unit = _spec->entryUnit; - if (unit != 0 && unit < _spec->units.size() && !draft.empty()) { - draft = convertDraft(draft, _spec->units.front(), _spec->units.at(unit), _core->values().locale) - .value_or(std::string{}); - } - Encoding const incoming = encodeScalar(*_spec, draft, unit, _core->values(), _places.peek()); - Encoding const& current = _encoded.peek(); - if (incoming.has_value() != current.has_value()) { - return false; - } - if (!incoming.has_value()) { - return true; - } - return incoming->has_value() && current->has_value() && (*incoming)->json == (*current)->json; - } + [[nodiscard]] bool encodesLike(detail::engine::Json const* value) const; /// @brief Replaces the draft with a wire value as the user's own edit, in one batch: a `load` the session does /// not mark programmatic, so the field counts as changed and is validated as an edit is. /// @param value The wire value; null is blank. /// @return Nothing, or why the value does not fit the field: an Object takes a JSON object, a collection a JSON /// array. Then nothing changes. - std::expected edit(detail::engine::Json const& value) { - if (!value.is_null() && !_spec->truncated) { - if (_spec->kind == FieldKind::Object && !value.is_object()) { - return std::unexpected(std::string{"an object field takes a JSON object"}); - } - if (_spec->kind == FieldKind::ObjectArray && !value.is_array()) { - return std::unexpected(std::string{"a list field takes a JSON array"}); - } - } - _core->runtime().batch([&] { load(&value); }); - return {}; - } + std::expected edit(detail::engine::Json const& value); /// @brief Replaces the draft with the decoded wire value; null or absent is blank. Does not /// mark the change programmatic — the caller does, in the same batch. /// @param value The wire value, or null. // An Object loads its members, a collection its rows; one case per kind. // NOLINTNEXTLINE(misc-no-recursion,readability-function-cognitive-complexity) - void load(detail::engine::Json const* value) { - using detail::engine::Json; - bool const present = value != nullptr && !value->is_null(); - if (_spec->truncated) { - _text.set(present ? detail::engine::toJson(*value) : std::string{}); - _engaged.set(present && value->is_array()); - return; - } - if (_spec->kind == FieldKind::Object) { - for (auto const& entry : _members) { - entry->load(present ? detail::engine::member(*value, entry->spec().name) : nullptr); - } - return; - } - if (_spec->kind == FieldKind::ObjectArray) { - std::vector> loaded; - if (present && value->is_array()) { - for (Json const& element : value->get_array()) { - auto row = std::make_shared(*_core, *_spec, _path, _nextRowKey++, this); - for (auto const& cell : row->fields()) { - cell->load(detail::engine::member(element, cell->spec().name)); - } - row->start(); - loaded.push_back(std::move(row)); - } - } - _rows.set(std::move(loaded)); - _engaged.set(present && value->is_array()); - return; - } - std::string draft = present ? decodeScalar(*_spec, *value, _core->values(), _places.peek()) : std::string{}; - std::size_t const unit = _spec->entryUnit; - if (unit != 0 && unit < _spec->units.size() && !draft.empty()) { - // The wire value is in the canonical unit; the draft is shown in the entry unit. - draft = convertDraft(draft, _spec->units.front(), _spec->units.at(unit), _core->values().locale) - .value_or(std::string{}); - } - _text.set(std::move(draft)); - _unit.set(unit); - _engaged.set(_spec->blankAs == BlankAs::Empty && present && value->is_string()); - } + void load(detail::engine::Json const* value); /// @brief Blanks the draft, the unit, the engagement, the members and the rows. // NOLINTNEXTLINE(misc-no-recursion): an Object clears its members. - void clear() { - _text.set(std::string{}); - _unit.set(_spec->entryUnit); - _engaged.set(false); - for (auto const& entry : _members) { - entry->clear(); - } - _rows.set({}); - } + void clear(); /// @brief Starts what needs every sibling to exist: an `x-blankAs` field's engagement, a /// Choice's options query, and every member's own. Called once, after the owner built /// all its fields. // NOLINTNEXTLINE(misc-no-recursion): an Object starts its members. - void start() { - for (auto const& entry : _members) { - entry->start(); - } - if (_spec->blankAs == BlankAs::Empty) { - _engage = std::make_unique(_core->runtime(), [this] { - if (!detail::engine::trim(_text.get()).empty() && !_engaged.peek()) { - _engaged.set(true); - } - }); - } - if (_spec->kind == FieldKind::Choice && _spec->choice.has_value() && _core->choices()) { - reactive::Runtime& runtime = _core->runtime(); - _optionsQuery = std::make_unique>( - runtime, - [this](std::string const& request) { return _core->choices()(_spec->choice->optionsAction, request); }, - [this] { return optionsRequest(); }); - _fetched = std::make_unique>>(runtime, [this] { - std::optional const& reply = _optionsQuery->value(); - return reply.has_value() ? parseOptions(*reply, *_spec->choice) : std::vector{}; - }); - _clearStale = std::make_unique(runtime, [this] { clearStaleSelection(); }); - } - } + void start(); private: - // Each draft is written with its length first, so no draft can be read as the end of another. + // Each draft is written with its length first, so no draft can be read as the end of another. A computed or + // derived member writes a fixed mark in its place. // NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's cells are fields. - void appendSnapshot(std::string& out) const { - std::string const& text = _text.peek(); - out += std::to_string(text.size()); - out += ':'; - out += text; - out += std::to_string(_unit.peek()); - out += _engaged.peek() ? '+' : '-'; - for (auto const& entry : _members) { - entry->appendSnapshot(out); - } - for (auto const& row : _rows.peek()) { - out += '#'; - for (auto const& cell : row->fields()) { - cell->appendSnapshot(out); - } - } - out += ';'; - } + void appendSnapshot(std::string& out) const; - [[nodiscard]] std::string resolveSlot(i18n::FieldSlot slot, std::string const& literal) const { - auto const& translations = _core->options().translations; - std::string_view const locale = _core->options().bcp47; - auto const explicitKey = i18n::explicitFieldKey(_spec->i18nKey, slot); - if (_parent == nullptr) { - return render::resolveText(translations, locale, explicitKey, - i18n::fieldKey(_core->model().actionType(), _spec->name, slot), literal); - } - if (translations && explicitKey) { - if (auto hit = translations(*explicitKey, locale)) { - return *std::move(hit); - } - } - return literal; - } + [[nodiscard]] std::string resolveSlot(i18n::FieldSlot slot, std::string const& literal) const; - [[nodiscard]] FieldState* sibling(std::string_view name) const { - if (_siblings == nullptr) { - return nullptr; - } - auto const found = - std::ranges::find_if(*_siblings, [&](auto const& entry) { return entry->spec().name == name; }); - return found == _siblings->end() ? nullptr : found->get(); + // A member of a collection row. + [[nodiscard]] bool inRow() const noexcept { + return _parent != nullptr && _parent->spec().kind == FieldKind::ObjectArray; } - /// The options request for the current parents, or nullopt while one does not encode. - [[nodiscard]] std::optional optionsRequest() const { - std::string body = "{"; - bool first = true; - // NOLINTNEXTLINE(bugprone-unchecked-optional-access): only a Choice asks, and a Choice has its spec. - for (std::string const& parent : _spec->choice.value().dependsOn) { - FieldState const* const source = sibling(parent); - if (source == nullptr) { - return std::nullopt; - } - Encoding const& encoding = source->encoded().get(); - if (!encoding.has_value() || !encoding->has_value()) { - return std::nullopt; - } - body += (first ? "" : ",") + detail::engine::quote(parent) + ":" + (*encoding)->json; - first = false; - } - return body + "}"; - } + // A field `x-optionsDependsOn` names: a sibling first (a row's member, an object's member), then a top-level + // field. + [[nodiscard]] FieldState* sibling(std::string_view name) const; + + /// The options request for the current parents, or nullopt while one does not encode, or while a row's member was + /// never opened. + [[nodiscard]] std::optional optionsRequest() const; /// Clears a selection the options no longer back — once the query has answered for the /// current parents, so a value set before its options arrive survives the fetch. A failed /// fetch judges nothing, so it keeps the selection. - void clearStaleSelection() { - if (_optionsQuery->pending() || _optionsQuery->error() != nullptr) { - return; - } - // An idle query (a parent is blank or does not encode) fetched nothing to judge the selection against. - std::optional const request = optionsRequest(); - if (!request.has_value()) { - return; - } - std::vector const& current = _fetched->get(); - std::string_view const selected = detail::engine::trim(_text.get()); - if (selected.empty() || - std::ranges::any_of(current, [&](ChoiceOption const& option) { return option.valueJson == selected; })) { - return; - } - _core->runtime().batch([&] { - _text.set(std::string{}); - _core->markProgrammatic(); - }); - } + void clearStaleSelection(); // NOLINTNEXTLINE(misc-no-recursion): an Object or a row encodes its members. [[nodiscard]] std::expected encodeMembers( - std::span const> members) const { - std::string json = "{"; - bool first = true; - for (auto const& entry : members) { - Encoding const& encoding = entry->encoded().get(); - if (!encoding.has_value()) { - if (entry->spec().required) { - return std::unexpected(fieldError("incomplete", _core->values())); - } - continue; - } - if (!encoding->has_value()) { - return std::unexpected(encoding->error()); - } - json += (first ? "" : ",") + detail::engine::quote(entry->spec().name) + ":" + (*encoding)->json; - first = false; - } - return json + "}"; - } + std::span const> members) const; // An Object or a row encodes its members; one case per kind. // NOLINTNEXTLINE(misc-no-recursion,readability-function-cognitive-complexity) - [[nodiscard]] Encoding computeEncoding() const { - if (_spec->truncated) { - std::string_view const draft = detail::engine::trim(_text.get()); - bool const array = _spec->kind == FieldKind::ObjectArray; - if (draft.empty() && !_engaged.get()) { - return (array && _spec->required) - ? Encoding{WireValue{.json = "[]", .value = ui::Value{ui::ValueList{}}}} - : Encoding{}; - } - if (array && (draft == "[]" || draft.empty())) { - return WireValue{.json = "[]", .value = ui::Value{ui::ValueList{}}}; - } - return std::unexpected(fieldError("unrepresentable", _core->values())); - } - if (_spec->kind == FieldKind::Object) { - if (blank()) { - return std::nullopt; - } - auto json = encodeMembers(_members); - if (!json) { - return std::unexpected(json.error()); - } - return WireValue{.json = *std::move(json), .value = ui::Value{}}; - } - if (_spec->kind == FieldKind::ObjectArray) { - auto const& rows = _rows.get(); - if (rows.empty() && !_engaged.get() && !_spec->required) { - return std::nullopt; - } - std::string json = "["; - for (std::size_t i = 0; i < rows.size(); ++i) { - auto row = encodeMembers(rows.at(i)->fields()); - if (!row) { - return std::unexpected(row.error()); - } - json += (i == 0 ? "" : ",") + *row; - } - return WireValue{.json = json + "]", .value = ui::Value{}}; - } - return encodeScalar(*_spec, _text.get(), _unit.get(), _core->values(), _places.get()); - } + [[nodiscard]] Encoding computeEncoding() const; // Declaration order is destruction order reversed: the signals precede the computeds that // read them, and the effects are last, so nothing is torn down while something reads it. @@ -817,6 +498,10 @@ class FieldState { reactive::Signal _unit; reactive::Signal> _places; reactive::Signal _engaged; + reactive::Signal _opened; + reactive::Signal>> _narrow; + /// The placeholder a grid column's overlay gives the field's row; empty for the schema's. + std::string _placeholderOverride; reactive::Signal>> _rows; std::vector> _members; reactive::Computed _encoded; @@ -828,6 +513,10 @@ class FieldState { std::unique_ptr> _optionsQuery; std::unique_ptr>> _fetched; std::unique_ptr _clearStale; + // Last: it reads `_fetched`, which is a pointer and not a reactive source, so nothing may read `options()` before + // `start()` made it: the Computed would keep the options it read then. A row is started before it is published and + // `load` decodes without options, so no path does. + reactive::Computed> _offered; }; inline RowState::RowState(detail::engine::SessionCore& core, FieldSpec const& arraySpec, std::string const& arrayPath, @@ -879,7 +568,7 @@ inline RuleLookup SessionCore::lookup() const { /// /// Non-copyable and non-movable: fields, bindings and in-flight replies point into it. Destroy a /// mounted view of it before the session. -class FormSession { +class MORPH_API FormSession { public: /// @param runtime The runtime. Borrowed: it must outlive the session. /// @param model The form model. @@ -888,46 +577,7 @@ class FormSession { /// @param options Locale, translations, display zone, extra readiness gate. /// @throws std::invalid_argument when @p submit is empty. FormSession(reactive::Runtime& runtime MORPH_LIFETIMEBOUND, FormModel model, Submitter submit, - ChoiceFetcher choices, FormSessionOptions options = {}) - : _core{std::make_unique(runtime, std::move(model), std::move(choices), - std::move(options))}, - _submit{std::move(submit)}, - _assembled{runtime, [this] { return assemble(); }}, - _ready{runtime, - [this] { - std::optional const& assembled = _assembled.get(); - if (!assembled.has_value()) { - return false; - } - auto const& accepts = _core->options().accepts; - return !accepts || accepts(*assembled); - }}, - _body{runtime, [this] { return _ready.get() ? _assembled.get() : std::optional{}; }}, - _mutation{runtime, - [this](std::string body) { return _submit(_core->model().actionType(), std::move(body)); }}, - _attempts{runtime, std::uint64_t{0}} { - if (!_submit) { - throw std::invalid_argument{"FormSession: a Submitter is required"}; - } - for (FieldSpec const& spec : _core->model().fields()) { - _fields.push_back(std::make_unique(*_core, spec, spec.name, &_fields, nullptr)); - } - _core->adopt(&_fields); - _core->onProgrammatic([this] { _lastSubmitted = _body.peek(); }); - for (std::size_t i = 0; i < _core->model().groups().size(); ++i) { - _collapsed.push_back(std::make_unique>(runtime, false)); - _tabs.push_back(std::make_unique>(runtime, std::size_t{0})); - } - for (auto const& field : _fields) { - field->start(); - } - markLoaded(); - _autoSubmit = std::make_unique(runtime, [this] { autoSubmit(); }); - _acceptSent = std::make_unique(runtime, [this, &runtime] { - static_cast(_mutation.successCount()); - runtime.untracked([&] { acceptSent(); }); - }); - } + ChoiceFetcher choices, FormSessionOptions options = {}); ~FormSession() = default; FormSession(FormSession const&) = delete; @@ -977,10 +627,7 @@ class FormSession { /// @brief The session options, read as a dependency on the translations and the locale: a computation that /// resolves a text through them reruns on `setTranslations`. /// @return The options. - [[nodiscard]] FormSessionOptions const& trackedOptions() const { - _core->trackTexts(); - return _core->options(); - } + [[nodiscard]] FormSessionOptions const& trackedOptions() const; /// @brief The top-level fields, in `x-order`. /// @return The fields. @@ -989,66 +636,15 @@ class FormSession { /// @brief A row position written in a path's brackets. /// @param digits The text between the brackets. /// @return The position, or `std::nullopt` unless the text is all decimal digits. - [[nodiscard]] static std::optional rowIndexOf(std::string_view digits) { - std::size_t parsed = 0; - char const* const end = std::to_address(digits.end()); - auto const result = std::from_chars(std::to_address(digits.begin()), end, parsed); - if (digits.empty() || result.ec != std::errc{} || result.ptr != end) { - return std::nullopt; - } - return parsed; - } + [[nodiscard]] static std::optional rowIndexOf(std::string_view digits); - /// @brief A field by path: `name`, `parent.member`, or `rows[i].member` (a row by position). + /// @brief A field by path: `name`, `parent.member`, `rows[i].member` (a row by position) or `rows#key.member` (a + /// row by its key, as `FieldState::path` writes it). /// @param path The path. /// @return The field. /// @throws std::out_of_range when no field has that path. - [[nodiscard]] FieldState& field(std::string_view path) const { - FieldState* current = nullptr; - std::span const> scope = _fields; - std::string_view rest = path; - auto const missing = [&] { - return std::out_of_range{"FormSession::field: no field '" + std::string{path} + "'"}; - }; - while (!rest.empty()) { - auto const dot = rest.find('.'); - std::string_view segment = rest.substr(0, dot); - rest = dot == std::string_view::npos ? std::string_view{} : rest.substr(dot + 1); - std::optional index; - if (auto const bracket = segment.find('['); bracket != std::string_view::npos) { - if (!segment.ends_with(']')) { - throw missing(); - } - index = rowIndexOf(segment.substr(bracket + 1, segment.size() - bracket - 2)); - if (!index.has_value()) { - throw missing(); - } - segment = segment.substr(0, bracket); - } - auto const found = - std::ranges::find_if(scope, [&](auto const& entry) { return entry->spec().name == segment; }); - if (found == scope.end()) { - throw missing(); - } - current = found->get(); - if (index.has_value()) { - auto const& rows = current->rows(); - if (*index >= rows.size() || rest.empty()) { - throw missing(); - } - scope = rows.at(*index)->fields(); - } else { - scope = current->members(); - if (!rest.empty() && scope.empty()) { - throw missing(); - } - } - } - if (current == nullptr) { - throw missing(); - } - return *current; - } + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + [[nodiscard]] FieldState& field(std::string_view path) const; /// @brief Whether the form can submit. Tracked. /// @return `true` when every required field encodes, no field has an error, no gating rule @@ -1062,35 +658,13 @@ class FormSession { /// @brief Submits the current body; does nothing while not ready, or while a submission is in /// flight (the submission is `Exclusive`). The explicit-mode trigger; in automatic mode /// it forces a resubmission of an unchanged body. - void submit() { - std::optional const body = _body.peek(); - if (!body.has_value()) { - return; - } - rememberSent(); - _lastSubmitted = body; - if (_mutation.run(*body)) { - _attempts.set(_attempts.peek() + 1); - } - } + void submit(); /// @brief Loads a stored payload for editing. Every field is replaced (an absent member starts /// blank), every unit returns to the canonical one, and nothing is submitted. Text that /// is not a JSON object changes nothing. /// @param bodyJson The payload. - void prefill(std::string_view bodyJson) { - auto const dom = detail::engine::parseJson(bodyJson); - if (!dom || !dom->is_object()) { - return; - } - runtime().batch([&] { - for (auto const& field : _fields) { - field->load(detail::engine::member(*dom, field->spec().name)); - } - _core->markProgrammatic(); - }); - markLoaded(); - } + void prefill(std::string_view bodyJson); /// @brief Loads a stored payload like `prefill`, except that a top-level field the user changed since the form /// was last loaded keeps what they entered: a later value of the record being edited, such as its first @@ -1101,71 +675,138 @@ class FormSession { /// (`1.000` for a typed `1`) leaves the text alone. A saved object or collection of an automatic form /// stays an edit. Nothing is submitted. Text that is not a JSON object changes nothing. /// @param bodyJson The payload. - void refill(std::string_view bodyJson) { - auto const dom = detail::engine::parseJson(bodyJson); - if (!dom || !dom->is_object()) { - return; - } - std::vector loaded; - runtime().batch([&] { - for (std::size_t index = 0; index < _fields.size(); ++index) { - FieldState& field = *_fields.at(index); - if (field.snapshot() != _loaded.at(index)) { - continue; - } - detail::engine::Json const* const incoming = detail::engine::member(*dom, field.spec().name); - // An automatic form's saved field is a finished edit only while the record differs from what the - // person typed: the record's form of the same value (`1.000` for `1`) is left out, so a refill - // never rewrites text the person may still be typing. - if (submitMode() == SubmitMode::Automatic && field.encodesLike(incoming)) { - continue; - } - field.load(incoming); - loaded.push_back(index); - } - _core->markProgrammatic(); - }); - for (std::size_t const index : loaded) { - _loaded.at(index) = _fields.at(index)->snapshot(); - } - } + void refill(std::string_view bodyJson); /// @brief Sets one field from a JSON value, programmatically (nothing is submitted). /// @param path The field's path (see `field`). /// @param jsonValue The value as JSON; text that is not JSON changes nothing. /// @throws std::out_of_range when no field has that path. // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): a path and a JSON value; swapped, the path is not found. - void assign(std::string_view path, std::string_view jsonValue) { - FieldState& target = field(path); - auto const dom = detail::engine::parseJson(jsonValue); - if (!dom) { - return; - } - runtime().batch([&] { - target.load(&*dom); - _core->markProgrammatic(); - }); - // A programmatic value is not an edit: the top-level field holding the target counts as loaded. - for (std::size_t index = 0; index < _fields.size(); ++index) { - std::string const& name = _fields.at(index)->spec().name; - if (path.starts_with(name) && - (path.size() == name.size() || path.at(name.size()) == '.' || path.at(name.size()) == '[')) { - _loaded.at(index) = _fields.at(index)->snapshot(); - } - } - } + void assign(std::string_view path, std::string_view jsonValue); /// @brief Blanks every field, programmatically (nothing is submitted). - void reset() { - runtime().batch([&] { - for (auto const& field : _fields) { - field->clear(); - } - _core->markProgrammatic(); - }); - markLoaded(); + void reset(); + + /// @brief A token that expires when the session is destroyed: what an object that may outlive it (a grid's source, + /// whose node a mount holds) checks before it calls back into the session. + /// @return The token. + [[nodiscard]] std::weak_ptr alive() const noexcept { return _alive; } + + /// @brief Registers what `submit` runs first, before it assembles the body: what ends an edit not committed yet, + /// such as a grid's open cell editor. Hooks run in the order they were added. + /// @param hook The hook. + /// @return The hook's id, for `removeBeforeSubmit`. + [[nodiscard]] std::size_t addBeforeSubmit(std::function hook); + + /// @brief Removes a hook `addBeforeSubmit` registered. + /// @param hookId The hook's id; one not registered is ignored. + void removeBeforeSubmit(std::size_t hookId) { + std::erase_if(_beforeSubmit, [hookId](auto const& entry) { return entry.first == hookId; }); } + /// @brief Whether a scalar field holds another entry than when the form was last loaded: its draft or its unit + /// differs, or it is a member of a row added since. Tracked. A computed or derived member is never + /// modified: only a round writes it. Any other member stays modified whatever freezes it after the user + /// typed in it. + /// @param path The field's path (see `field`), such as `specimens#3.mass`. + /// @return `true` when modified; `false` for a path that names no field, and for an Object or a collection. + [[nodiscard]] bool modified(std::string_view path) const; + + /// @brief A count that moves with each load: each write through `FieldState::load`, which sets the fields it + /// writes afresh, their units included. Construction, `prefill`, `reset`, a `refill` that loads a field, a + /// submission that ends a field's edit and a round of derived values that writes a member are loads; a + /// switch of units as loaded alone is not, and nor is a revert. Tracked. + /// @return The count. + [[nodiscard]] std::uint64_t loadGeneration() const { return _loads.get(); } + + /// @brief Whether a row of a collection holds another entry than when the form was last loaded: one of its members + /// is modified, or the row was added since. Tracked. + /// @param arrayPath The collection's path. + /// @param key The row's key. + /// @return `true` when modified; `false` for a row the collection does not hold. + [[nodiscard]] bool rowModified(std::string_view arrayPath, std::uint64_t key) const; + + /// @brief Why the last submission's reply refused a field: the reply's `errors` member, an object of field paths + /// (`field`) to a message or a list of messages, names it. Held while the field keeps the draft it had + /// then. Tracked. + /// @param path The field's path. + /// @return The message; empty while none holds. + [[nodiscard]] std::optional refusal(std::string_view path) const; + + /// @brief Restores what a field held when the form was last loaded, programmatically (nothing is submitted): a + /// scalar's draft and unit, or each member of a row (`rows#key`). A row added since the load is removed. + /// @param path The field's or the row's path. + void revert(std::string_view path); + + /// @brief Asks for derived and computed values in rounds from now on: each commit (`noteCommit`) starts a round + /// once + /// `options.debounce` passed with no further commit, which evaluates the body and calls the derive action. + /// @param options The evaluation, the derive call, the timers and the debounce. + void deriveWith(DeriveOptions options); + + /// @brief An edit was committed (a grid's cell): with a round in flight its replies are marked stale, so one more + /// round follows them; otherwise a round starts once the debounce passed with no further commit, at once + /// when there are no timers. Does nothing until `deriveWith` gave an evaluation or a derive call. + void noteCommit(); + + /// @brief Makes one more round at once, unless one is in flight: what "Recalculate" runs after a failed round. + void recalculate(); + + /// @brief Where the derived values stand. Tracked. + /// @return `Running` while a round is in flight, `Failed` after a round whose evaluation or derive call failed, + /// else `Current`. + [[nodiscard]] DeriveState deriveState() const { return _deriveState.get(); } + + /// @brief Whether the derived values are the last ones loaded before a failure: true from a round that failed + /// until + /// a round succeeds, so it holds through a retry in flight (what "Recalculate" offers stays until it + /// worked). Tracked. + /// @return `true` while the last round to settle failed. + [[nodiscard]] bool deriveFailing() const { return _deriveFailing.get(); } + + /// @brief The body as far as it encodes: every top-level field that encodes; an Object or a collection member by + /// member, leaving out a member that is blank or does not encode; every row of a collection written, in + /// order, `{}` for a row with nothing. Untracked. + /// @return The JSON body. + [[nodiscard]] std::string partialBody() const; + + /// @brief Starts a round's record: the next sequence, `partialBody()`, and the row keys of every collection by its + /// `FieldState::path()`, in the order the body writes the rows. Untracked. + /// @return The round. + [[nodiscard]] DeriveRound captureRound(); + + /// @brief Loads a derive reply's values: each path names a derived member (`x-derived`) of the body @p round sent, + /// `rows[i]` resolved through the row keys at sending to the row's current position, so a value lands on + /// the row it was computed for; a value for a row removed since is dropped. Programmatic, and no edit: + /// nothing is submitted, and a member that held its loaded value holds the new one as loaded. A derived + /// member is in no field's snapshot, so a top-level field that held its loaded value, or what the + /// submission in flight sent, keeps holding it. A round older than the last loaded derive reply loads + /// nothing. + /// @param round The round the reply answers. + /// @param reply The reply. + /// @return How many members were written, and the paths refused: those naming no derived member. + DeriveLoad loadDerived(DeriveRound const& round, Derived const& reply); + + /// @brief Loads an evaluation's recomputed body: every computed member (`x-computed`) of the body @p round sent, + /// rows resolved as `loadDerived(round, Derived)` resolves them; a computed member the body leaves out of + /// an object it holds is blank. The reply's `errors` and `ready` are not read. Programmatic, and no edit, + /// as `loadDerived(round, Derived)` writes. A round older than the last loaded evaluation loads nothing. + /// @param round The round the reply answers. + /// @param evaluatedBody The recomputed body. + /// @return How many members were written; nothing is refused, since only computed members are read. + DeriveLoad loadDerived(DeriveRound const& round, std::string_view evaluatedBody); + + /// @brief Switches units as part of how the fields were loaded: what the first unit a grid's per-row `unit` + /// overlay + /// gives each loaded row is. Each switch converts the draft as `FieldState::switchUnit` does. A cell that + /// held its loaded value is then recorded as loaded with what it holds after the switch, so it draws no + /// modified mark and a revert returns to it; a modified cell, and a member of a row added since the load, + /// stay as they are, the switch an ordinary programmatic change. A top-level field that held its loaded + /// value, or what the submission in flight sent, keeps holding it. Nothing is submitted. All the switches + /// are one batch and one pass over the top-level fields, so a load's rows cost no more than one switch. + /// @param switches Each field, a scalar of this session, and the index into its `spec().units` to switch it to. + void switchUnitsAsLoaded(std::span const> switches); + /// @brief Whether a submission is in flight. Tracked. /// @return `true` while one is. [[nodiscard]] bool pending() const { return _mutation.pending(); } @@ -1204,124 +845,173 @@ class FormSession { /// @param group Index into `model().groups()`. /// @return The title; empty for the implicit trailing group. Tracked: it follows `setTranslations`. /// @throws std::out_of_range for an index past the groups. - [[nodiscard]] std::string groupTitle(std::size_t group) const { - FieldGroupSpec const& spec = detail::engine::elementAt(_core->model().groups(), group); - if (spec.implicit) { - return {}; - } - _core->trackTexts(); - return render::resolveText(_core->options().translations, _core->options().bcp47, std::nullopt, - i18n::groupKey(_core->model().actionType(), group), spec.title); - } + [[nodiscard]] std::string groupTitle(std::size_t group) const; private: // Only while nothing is in flight: the submission is Exclusive, so a run made during one is refused and what it // would have sent was never saved. - void rememberSent() { - runtime().untracked([&] { - if (_mutation.pending()) { - return; - } - // A success the accept effect has not yet seen belongs to the snapshots about to be replaced. - acceptSent(); - _sent.clear(); - for (auto const& field : _fields) { - _sent.push_back(field->snapshot()); - } - }); - } + void rememberSent(); // An explicit form ends the edit of what it saved. An automatic one does so only for a scalar: its refill compares // the record's value with the draft, which a collection's rows and an object's members do not allow, and // rebuilding them would replace the row the person is typing in. - [[nodiscard]] bool endsEditOnSave(FieldState const& field) const { - if (_core->model().submitMode() == SubmitMode::Explicit) { - return true; - } - FieldSpec const& spec = field.spec(); - return !spec.truncated && spec.kind != FieldKind::Object && spec.kind != FieldKind::ObjectArray; - } + [[nodiscard]] bool endsEditOnSave(FieldState const& field) const; // Ends the edit of what the last success sent. Runs untracked: the accept effect and the next send both call it. - void acceptSent() { - std::uint64_t const successes = _mutation.successCount(); - if (successes == _acceptedSuccesses) { - return; - } - _acceptedSuccesses = successes; - for (std::size_t index = 0; index < _sent.size(); ++index) { - if (_fields.at(index)->snapshot() == _sent.at(index) && endsEditOnSave(*_fields.at(index))) { - _loaded.at(index) = _sent.at(index); - } - } - _sent.clear(); - } + void acceptSent(); - void markLoaded() { - _loaded.clear(); - for (auto const& field : _fields) { - _loaded.push_back(field->snapshot()); - } - } + void markLoaded(); - [[nodiscard]] std::optional assemble() const { - std::string json = "{"; - bool first = true; - for (auto const& field : _fields) { - Encoding const& encoding = field->encoded().get(); - bool const required = field->required().get(); - std::string literal; - if (!encoding.has_value()) { - if (field->spec().blankAs == BlankAs::Empty && field->engaged().get() && !required) { - literal = R"("")"; - } else if (required) { - return std::nullopt; - } else { - continue; - } - } else if (!encoding->has_value()) { - return std::nullopt; - } else { - literal = (*encoding)->json; - } - json += (first ? "" : ",") + detail::engine::quote(field->spec().name) + ":" + literal; - first = false; - } - if (gatingVerdict(_core->model().rules(), _core->lookup()) == Tri::False) { - return std::nullopt; - } - return json + "}"; + // A field the last submission refused: the message, and the draft the field held then. + struct Refused { + std::string message; + std::string draft; + }; + + // The field errors a reply names in its `errors` member, by the field's path: the first message of each entry. An + // entry that names no field of the form is left out. A failure's exception names none: a refusal's arguments are + // its sentence's. + [[nodiscard]] std::map> fieldErrorsOf( + std::optional const& reply) const; + + // Takes the field errors of each submission as it settles: a reply's `errors`, or none for a failure. + void takeFieldErrors(std::uint64_t successes, std::exception_ptr const& error); + + // What one scalar held when the form was last loaded; a row's own entry marks the row as loaded. + struct LoadedCell { + std::string text; + std::size_t unit = 0; + }; + + // Records what a field holds now as loaded: each scalar's draft and unit, each row of a collection, each member. + // NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields. + void recordLoaded(FieldState const& state); + + // A round of derived values loads its targets (`FieldState::load` sets each afresh, its unit included): the load + // count moves when it wrote any. + void noteLoads(std::size_t written); + + // Records a top-level field as loaded again, forgetting what it held before. + void reloaded(FieldState const& state); + + // NOLINTNEXTLINE(misc-no-recursion): an Object's members are fields. + [[nodiscard]] bool modified(FieldState const& state) const; + + // A collection's row by key, tracked; null when there is none. + [[nodiscard]] RowState const* rowOf(std::string_view arrayPath, std::uint64_t key) const; + + [[nodiscard]] bool addedSinceLoad(RowState const& row) const; + + // Puts back what a scalar held when the form was last loaded, or blanks a member of a row added since. + // NOLINTNEXTLINE(misc-no-recursion): an Object's members are fields. + void restoreLoaded(FieldState& state); + + [[nodiscard]] std::optional assemble() const; + + void autoSubmit(); + + [[nodiscard]] static bool isComposite(FieldSpec const& spec) noexcept { + return spec.truncated || spec.kind == FieldKind::Object || spec.kind == FieldKind::ObjectArray; } - void autoSubmit() { - if (_core->model().submitMode() != SubmitMode::Automatic) { - return; - } - // While a Choice's options are in flight its selection is unjudged: a parent just changed, and the selection - // may be one the new options no longer back. Waiting lets the stale selection be cleared first; the settled - // query wakes this Effect again. - if (std::ranges::any_of(_fields, [](auto const& field) { return field->optionsPending(); })) { - return; - } - // The submission is Exclusive: while one is in flight a new run would be refused and its body lost. Waiting - // here sends the latest body once the one in flight settles, which wakes this Effect again. - if (_mutation.pending()) { - return; - } - std::optional const& body = _body.get(); - if (!body.has_value() || body == _lastSubmitted) { - return; - } - _lastSubmitted = body; - rememberSent(); - std::string const toSend = *body; + // What one field adds to the partial body: a scalar's encoding, an object's or a collection's members that encode; + // nothing for a blank field or one that does not encode. + // NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields. + [[nodiscard]] static std::optional partialOf(FieldState const& field); + + // Every collection's row keys, by its path, in order, its rows' own collections included. + // NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields. + static void collectRowKeys(FieldState const& field, + std::map, std::less<>>& out); + + // Where a reply's path lands: a field, a row removed since the round was sent, or nothing the body held. + struct Resolved { + enum class Kind : std::uint8_t { Found, Dropped, Missing } kind = Kind::Missing; + FieldState* field = nullptr; + }; + + // Resolves `name`, `parent.member` and `rows[i].member` against the body @p round sent: `rows[i]` is the row whose + // key was i-th when it was sent, wherever it is now. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per segment's form. + [[nodiscard]] Resolved resolve(DeriveRound const& round, std::string_view path) const; + + // The computed members under one field and their values in the recomputed body: a scalar's when computed, an + // object's members, a collection's rows by the keys they had when the round was sent. A computed member the body + // leaves out of an object it holds is written blank (a null value). + // NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields. + static void collectComputed(DeriveRound const& round, FieldState& field, detail::engine::Json const& object, + std::vector>& out); + + // Whether a scalar holds what the form recorded for it at the last load. A member of a row added since holds no + // loaded value. + [[nodiscard]] bool holdsLoaded(FieldState const& field) const; + + // A programmatic write into @p targets that is no edit: a target that held its loaded value is recorded as loaded + // with its new one, a modified target stays modified, and each top-level field that held its loaded value, or what + // the submission in flight sent, keeps holding it. Nothing is submitted. + // A round writes only computed and derived members, which no snapshot holds, so it passes `keepTop` false: the + // top-level fields' loaded and sent snapshots are unchanged by it already. + template + void writeKeepingLoaded(std::span targets, Write const& write, bool keepTop = true) { + std::vector heldLoaded; + std::vector topLoaded(_fields.size(), false); + std::vector topSent(_fields.size(), false); runtime().untracked([&] { - if (_mutation.run(toSend)) { - _attempts.set(_attempts.peek() + 1); + for (FieldState const* const target : targets) { + heldLoaded.push_back(holdsLoaded(*target)); + } + for (std::size_t index = 0; keepTop && index < _fields.size(); ++index) { + std::string const snap = _fields.at(index)->snapshot(); + topLoaded.at(index) = snap == _loaded.at(index); + topSent.at(index) = index < _sent.size() && snap == _sent.at(index); } }); + runtime().batch([&] { + write(); + _core->markProgrammatic(); + }); + runtime().untracked([&] { + for (std::size_t at = 0; at < targets.size(); ++at) { + if (heldLoaded.at(at)) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < targets.size() + FieldState const& target = *targets[at]; + _loadedCells.insert_or_assign(target.path(), + LoadedCell{.text = target.draft(), .unit = target.unit().peek()}); + } + } + for (std::size_t index = 0; index < _fields.size(); ++index) { + if (!topLoaded.at(index) && !topSent.at(index)) { + continue; + } + std::string const snap = _fields.at(index)->snapshot(); + if (topLoaded.at(index)) { + _loaded.at(index) = snap; + } + if (topSent.at(index)) { + _sent.at(index) = snap; + } + } + }); + _loadGeneration.set(_loadGeneration.peek() + 1); } + // One round in flight: what it sent, which replies settled, whether one failed, and whether a commit came since. + struct InFlight { + DeriveRound round; + bool evaluated = false; + bool derived = false; + bool failed = false; + bool stale = false; + }; + + // Sends a round: the evaluation and the derive call, each with the partial body. + // NOLINTNEXTLINE(misc-no-recursion): a stale round's settling starts the next round, which settles through its replies in turn. + void startRound(); + + // One reply of the round in flight settled; once both did, the state follows, and a stale round makes one more. + // NOLINTNEXTLINE(misc-no-recursion): a stale round's settling starts the next round, which settles through its replies in turn. + void settled(std::uint64_t sequence, bool evaluation, bool failed); + std::unique_ptr _core; Submitter _submit; std::vector> _fields; @@ -1338,8 +1028,33 @@ class FormSession { /// @brief Each top-level field's snapshot when the explicit submission in flight was sent. std::vector _sent; std::uint64_t _acceptedSuccesses = 0; + /// @brief What each scalar held when the form was last loaded, by its path, and each row of a collection then. + std::map> _loadedCells; + /// @brief Moves on every change of `_loadedCells`, so what compares against it is evaluated again. + reactive::Signal _loadGeneration; + /// @brief Moves with each load (`loadGeneration`); a switch of units as loaded leaves it. + reactive::Signal _loads; + /// @brief What `submit` runs first, by id, in the order added. + std::vector>> _beforeSubmit; + std::size_t _nextHook = 0; + std::shared_ptr _alive = std::make_shared(0); + /// @brief The fields the last failed submission refused, by path, and the failure they were read from. + reactive::Signal>> _refusals; + std::exception_ptr _refusalSeen; + std::uint64_t _errorsSeenSuccesses = 0; + /// @brief How the session asks for derived values, and the round in flight. + DeriveOptions _derive; + std::optional _round; + std::uint64_t _sequence = 0; + std::uint64_t _derivedLoaded = 0; + std::uint64_t _evaluationLoaded = 0; + reactive::Signal _deriveState; + reactive::Signal _deriveFailing; + reactive::TimerHandle _debounce; + async::CallbackScope _deriveScope; std::unique_ptr _autoSubmit; std::unique_ptr _acceptSent; + std::unique_ptr _refused; }; } // namespace morph::forms diff --git a/include/morph/forms/engine/form_view.hpp b/include/morph/forms/engine/form_view.hpp index 7945e8d44..d56560bfa 100644 --- a/include/morph/forms/engine/form_view.hpp +++ b/include/morph/forms/engine/form_view.hpp @@ -23,10 +23,12 @@ #include #include "../../reactive/control.hpp" +#include "../../ui/grid.hpp" #include "../../ui/view.hpp" #include "../../util/datetime.hpp" #include "../layout.hpp" #include "detail/text.hpp" +#include "field_control.hpp" #include "field_layout.hpp" #include "field_model.hpp" #include "form_session.hpp" @@ -80,280 +82,18 @@ using ViewOptions = std::shared_ptr; : "submits as you type"; } -/// @brief Whether a text property says something: bound, or a constant that is not empty. -/// @param text The property. -/// @return Whether it is set. -[[nodiscard]] inline bool isSet(ui::Prop const& text) { - return text.isBound() || !text.constant().empty(); -} - -/// @brief The last reply or failure. -/// @param session The session. -/// @return `error: `, `ok: `, or empty before the first answer. -[[nodiscard]] inline std::string resultText(FormSession const& session) { - if (std::exception_ptr const error = session.lastError()) { - return "error: " + reactive::errorMessage(error); - } - std::optional const& reply = session.lastReply(); - return reply.has_value() ? "ok: " + *reply : std::string{}; -} - -/// @brief A draft wall clock (`YYYY-MM-DDTHH:MM[:SS]`, or a `YYYY-MM-DD` date) as the instant it denotes. -/// @param text The draft. -/// @param date Whether the field holds a date. -/// @param offsetMinutes The display zone. -/// @return The instant, or `std::nullopt` while the draft is not a complete one. -[[nodiscard]] inline std::optional draftInstant(std::string_view text, bool date, int offsetMinutes) { - std::optional local; - if (date) { - if (isIsoDate(text)) { - local = parseWallClock(std::string{text} + "T00:00"); - } - } else { - local = parseWallClock(text); - } - if (!local) { - return std::nullopt; - } - auto const utc = *local - std::chrono::minutes{date ? 0 : offsetMinutes}; - return time::Timestamp{time::DateTime{std::chrono::time_point_cast(utc)}}; -} - -/// @brief The draft a date-time control writes for an instant (blank for none). -/// @param value The instant. -/// @param date Whether the field holds a date. -/// @param offsetMinutes The display zone. -/// @return `YYYY-MM-DDTHH:MM:SS` in the zone, or `YYYY-MM-DD`. -[[nodiscard]] inline std::string instantDraft(std::optional const& value, bool date, - int offsetMinutes) { - if (!value || !value->hasValue()) { - return {}; - } - auto const instant = - std::chrono::floor((**value).value) + std::chrono::minutes{date ? 0 : offsetMinutes}; - std::string const text = formatWallClock(instant); - return date ? text.substr(0, 10) : text; -} - -/// @brief The view-tree field state of a field: read-only, required, its error as the one message shown, and its -/// help as the control's description, which assistive technology associates with the control. -/// @param field The field. -/// @return The state, bound to the field. -[[nodiscard]] inline ui::FieldState fieldState(FieldState const* field) { - return ui::FieldState{ - .readonly = [field] { return field->readonly().get(); }, - .required = [field] { return field->required().get(); }, - .errors = - [field] { - auto const& error = field->error().get(); - return error.has_value() ? std::vector{error->message} : std::vector{}; - }, - .stale = false, - .description = [field] { return field->help(); }, - }; -} - -/// @brief The `Common` of a field's control: its test id (`field_`) and accessible name (its label). -/// @param field The field. -/// @return The common part. -[[nodiscard]] inline ui::Common controlCommon(FieldState const* field) { - ui::Common common{}; - common.testId = "field_" + field->path(); - common.a11y.name = [field] { return field->label(); }; - return common; -} - [[nodiscard]] ui::Node fieldCell(FormSession& session, FieldState& state, ViewOptions const& options); -/// @brief A Select over the field's options (an Enum's, or a Choice's as last fetched), keyed by each option's -/// JSON literal, so an id past 2^53 is never a number on the way. -/// @param field The field. -/// @param style Dropdown or radio. -/// @return The control. -[[nodiscard]] inline ui::Node optionSelect(FieldState* field, ui::SelectStyle style) { - return ui::select(ui::Select{ - .options = - [field] { - std::vector options; - for (ChoiceOption const& option : field->options()) { - options.push_back(ui::SelectOption{.key = ui::Key{option.valueJson}, .label = option.label}); - } - return options; - }, - .selected = [field] -> std::optional { - std::string_view const selected = trim(field->text().get()); - return selected.empty() ? std::nullopt : std::optional{ui::Key{std::string{selected}}}; - }, - .onSelect = - [field](ui::Key const& key) { - if (auto const* const value = std::get_if(&key)) { - field->text().set(*value); - } - }, - .onOpen = [field] { field->retryOptions(); }, - .style = style, - // The cell draws the caption, so the select is told its label and not to show it. - .label = [field] { return field->label(); }, - .showLabel = false, - .field = fieldState(field), - .common = controlCommon(field), - }); -} - /// @brief The built-in control of one field (the table in `docs/spec/forms/engine.md`, "Rendering"). /// @param session The session. /// @param state The field. /// @param options The view options (members and rows draw their own cells with them). /// @return The control. -// One case per kind; an Object or an ObjectArray draws its members' cells. +// An Object or an ObjectArray draws its members' cells; every other kind is a scalar control. // NOLINTNEXTLINE(misc-no-recursion,readability-function-cognitive-complexity) [[nodiscard]] inline ui::Node fieldControl(FormSession& session, FieldState& state, ViewOptions const& options) { FieldState* const field = &state; FieldSpec const& spec = state.spec(); - auto const textInput = [field](ui::TextInputMode mode, std::string unit = {}, ui::Prop decimals = -1) { - return ui::textInput(ui::TextInput{ - .value = [field] { return field->text().get(); }, - .onChange = [field](std::string text) { field->text().set(std::move(text)); }, - .onSubmit = {}, - .onCommit = {}, - .placeholder = [field] { return field->placeholder(); }, - .mode = mode, - .unit = std::move(unit), - .decimals = std::move(decimals), - .label = [field] { return field->label(); }, - .showLabel = false, - .field = fieldState(field), - .common = controlCommon(field), - }); - }; - // A number's input shows its unit and knows its entry places: an integer's 0, the chosen unit's, a plain - // number's display places, a decimal's declared ones; -1 where none is declared. A record's places - // (`FieldState::places`) replace the canonical unit's, or a plain number's, and no other unit's. - auto const numberInput = [&] { - if (spec.kind == FieldKind::Integer) { - return textInput(ui::TextInputMode::SingleLine, spec.unit, 0); - } - if (!spec.units.empty()) { - return textInput(ui::TextInputMode::SingleLine, spec.unit, [field] { - auto const& units = field->spec().units; - std::size_t const unit = std::min(field->unit().get(), units.size() - 1); - std::optional const places = field->places().get(); - return static_cast(unit == 0 && places.has_value() ? *places : units.at(unit).decimals); - }); - } - int decimals = -1; - if (spec.displayDecimals) { - decimals = static_cast(*spec.displayDecimals); - } else if (spec.decimalPlaces) { - decimals = static_cast(*spec.decimalPlaces); - } - return textInput(ui::TextInputMode::SingleLine, spec.unit, [field, decimals] { - std::optional const places = field->places().get(); - return places.has_value() ? static_cast(*places) : decimals; - }); - }; - auto const dateInput = [&](bool date) { - int const offset = date ? 0 : session.options().displayOffsetMinutes; - // The input shows and reads the session's pattern, which it follows; the draft text below stays ISO. - FormSession const* const owner = &session; - return ui::dateTimeInput(ui::DateTimeInput{ - .value = [field, date, offset] { return draftInstant(trim(field->text().get()), date, offset); }, - .onChange = - [field, date, offset](std::optional const& value) { - field->text().set(instantDraft(value, date, offset)); - }, - .mode = date ? ui::DateMode::Date : ui::DateMode::DateTime, - .offsetMinutes = offset, - .label = [field] { return field->label(); }, - .showLabel = false, - .field = fieldState(field), - .common = controlCommon(field), - .pattern = [owner, date] { return owner->pattern(date); }, - }); - }; - if (spec.kind == FieldKind::Multiline) { - return textInput(ui::TextInputMode::Multiline); - } - if (spec.kind == FieldKind::Integer || spec.kind == FieldKind::Number || spec.kind == FieldKind::Decimal) { - return numberInput(); - } - if (spec.kind == FieldKind::Quantity) { - if (spec.units.size() <= 1) { - return numberInput(); - } - std::vector units; - units.reserve(spec.units.size()); - for (std::size_t i = 0; i < spec.units.size(); ++i) { - units.push_back( - ui::SelectOption{.key = ui::Key{static_cast(i)}, .label = spec.units.at(i).display}); - } - ui::Common unitCommon{}; - unitCommon.testId = "unit_" + field->path(); - unitCommon.a11y.name = [field] { return field->label(); }; - return ui::row(ui::Row{ - .children = {textInput(ui::TextInputMode::SingleLine), - ui::select(ui::Select{ - .options = std::move(units), - .selected = [field] -> std::optional { - return ui::Key{static_cast(field->unit().get())}; - }, - .onSelect = - [field](ui::Key const& key) { - if (auto const* const index = std::get_if(&key); - index != nullptr && *index >= 0) { - field->switchUnit(static_cast(*index)); - } - }, - .style = ui::SelectStyle::Dropdown, - .field = {}, - .common = std::move(unitCommon), - })}, - .gap = 4, - }); - } - if (spec.kind == FieldKind::Boolean) { - return ui::checkbox(ui::Checkbox{ - .label = [field] { return field->label(); }, - .checked = [field] { return trim(field->text().get()) == "true"; }, - .onToggle = [field](bool checked) { field->text().set(checked ? "true" : "false"); }, - .field = fieldState(field), - .common = controlCommon(field), - }); - } - if (spec.kind == FieldKind::Enum) { - return optionSelect(field, spec.widget == "radio" ? ui::SelectStyle::Radio : ui::SelectStyle::Dropdown); - } - if (spec.kind == FieldKind::Choice) { - return ui::row(ui::Row{ - .children = - {optionSelect(field, spec.widget == "radio" ? ui::SelectStyle::Radio : ui::SelectStyle::Dropdown), - ui::busy(ui::Busy{.active = [field] { return field->optionsPending(); }, .label = std::string{}})}, - .gap = 4, - }); - } - if (spec.kind == FieldKind::DateTime || spec.kind == FieldKind::EpochDateTime) { - return dateInput(false); - } - if (spec.kind == FieldKind::Date || spec.kind == FieldKind::EpochDate) { - return dateInput(true); - } - if (spec.kind == FieldKind::Slider) { - return ui::slider(ui::Slider{ - .value = - [field] { - std::string_view const text = trim(field->text().get()); - std::int64_t value = field->spec().sliderMin; - std::from_chars(std::to_address(text.begin()), std::to_address(text.end()), value); - return value; - }, - .minimum = spec.sliderMin, - .maximum = spec.sliderMax, - .step = spec.sliderStep, - .onChange = [field](std::int64_t value) { field->text().set(std::to_string(value)); }, - .field = fieldState(field), - .common = controlCommon(field), - }); - } if ((spec.kind == FieldKind::Object || spec.kind == FieldKind::ObjectArray) && spec.truncated) { return ui::text(ui::Text{.text = "nested too deeply to edit here", .role = ui::TextRole::Muted}); } @@ -369,6 +109,15 @@ using ViewOptions = std::shared_ptr; panel.common.testId = "field_" + state.path(); return ui::panel(std::move(panel)); } + if (spec.kind == FieldKind::ObjectArray && spec.widget == "grid") { + std::vector columns; + columns.reserve(spec.children.size()); + for (FieldSpec const& member : spec.children) { + columns.push_back( + ui::GridColumn{.id = member.name, .label = member.title, .field = member.name, .value = {}}); + } + return ui::formGrid(session, state, std::move(columns), {}, ui::formatOf(session)); + } if (spec.kind == FieldKind::ObjectArray) { FormSession* const owner = &session; ViewOptions const& shared = options; @@ -405,7 +154,7 @@ using ViewOptions = std::shared_ptr; column.common.testId = "field_" + state.path(); return ui::column(std::move(column)); } - return textInput(ui::TextInputMode::SingleLine); + return scalarControl(session, state); } /// @brief Space as wide as an inline caption, which lines a Boolean's box or a help text up with the controls. diff --git a/include/morph/forms/field_errors.hpp b/include/morph/forms/field_errors.hpp index 18f4ed9ad..acf8b7734 100644 --- a/include/morph/forms/field_errors.hpp +++ b/include/morph/forms/field_errors.hpp @@ -30,7 +30,9 @@ template if constexpr (EmptyCapableField) { bool const isComputed = detail::isComputedDestinationMember(action, static_cast(std::addressof(member))); - return !detail::declaredOptional(name) && !isComputed && !member.hasValue(); + // A derived member is the model's to set: the dispatch path clears what a client sent for it. + return !detail::declaredOptional(name) && !isComputed && !detail::declaredDerived(name) && + !member.hasValue(); } else { static_cast(action); static_cast(name); @@ -55,7 +57,9 @@ template [[nodiscard]] bool outOfBounds(std::string_view name, Member const& member) { if constexpr (detail::HasFieldMetadata) { FieldMeta const* const meta = detail::findFieldMeta(name); - if (meta == nullptr || !detail::declaresAnyBound(*meta)) { + // A derived member is cleared before the model sets it, so a bound on it judges the model's value, not the + // caller's. + if (meta == nullptr || meta->derived || !detail::declaresAnyBound(*meta)) { return false; } if constexpr (units::isQuantity) { diff --git a/include/morph/forms/forms.hpp b/include/morph/forms/forms.hpp index 6677b3f17..8609ad291 100644 --- a/include/morph/forms/forms.hpp +++ b/include/morph/forms/forms.hpp @@ -88,6 +88,10 @@ /// sibling inputs (named in `x-computed.inputs`) and must not be rendered as /// an editable control (`x-readonly: true`). See `morph::forms::computed`, /// `morph::forms::computeList`, and `morph::forms::recomputeAll`. +/// - **`x-derived` / `x-readonly`** — for a member its type's `fieldMetadata` +/// marks `derived()` (`forms/derive.hpp`): a value the model sets from the +/// domain's data, read-only in a form, left out of `required`, untouched by +/// `recomputeAll` and cleared by the server dispatch path before the model runs. /// /// `morph::time::Timestamp` members need no extension keys: their schema /// carries the standard `"format": "date-time"` annotation. @@ -101,8 +105,10 @@ /// whatever depth it has: there is no depth limit, and a self- or /// mutually-referential type is described rather than rejected — glaze emits /// a finite `$ref`-cyclic schema for it, and the runtime `$defs` visited set -/// walks that once. Computed fields/`formLayout`/`fieldSpans`/`formRules` -/// remain top-level-only regardless of depth. See docs/spec/forms/forms.md, +/// walks that once. A nested type's own `computedFields` are written as the +/// top level's are, and recomputed in every nested value by `recomputeAll`; +/// `formLayout`/`fieldSpans`/`formRules` remain top-level-only regardless of +/// depth. See docs/spec/forms/forms.md, /// "Nested aggregates (recursive, cycle-safe)", and /// `detail::annotateNestedAggregateRef`. /// @@ -176,6 +182,7 @@ #include #include #include +#include #include #include #include @@ -193,6 +200,10 @@ #include "layout.hpp" #include "version.hpp" +namespace morph::table { +struct MeasureValue; +} // namespace morph::table + namespace morph::forms { /// @brief Per-field presentation overrides and scalar bounds: label, help, @@ -338,6 +349,12 @@ struct FieldMeta { /// @brief Field of each options row shown to the user (`x-optionLabel`); set with `optionsAction`. // NOLINTNEXTLINE(readability-redundant-member-init) -- as `unit` above std::string_view labelField{}; + /// @brief A derived member when `true`: a value the model sets when it executes the action, from the domain's + /// data, which no pure function of the record can compute. Emits `x-derived` (read-only in a form) and + /// leaves the member out of `required`; `recomputeAll` and the bound checks do not touch it, and every + /// execution path clears it before the model runs (`clearDerived`), so the value a caller sends is never + /// kept. + bool derived{false}; /// @brief The version this field first ships in, a dotted numeric version such as `"6.11.0"` (`FieldVersion`); /// emitted as `x-since`. Empty means the first version. @@ -436,6 +453,14 @@ struct FieldMeta { copy.since = version; return copy; } + + /// @brief Returns a copy with `derived` set to `true`. + /// @return The updated descriptor. + [[nodiscard]] constexpr FieldMeta withDerived() const noexcept { + FieldMeta copy = *this; + copy.derived = true; + return copy; + } }; /// @brief Concept: a field type with an internal empty state (`Quantity`, @@ -519,6 +544,21 @@ template return nullptr; } +/// @brief Whether `A::fieldMetadata` marks @p fieldName `derived` (`FieldMeta::withDerived`). +/// @tparam A The type declaring the member. +/// @param fieldName The member's wire name. +/// @return `true` for a derived member. +template +[[nodiscard]] constexpr bool declaredDerived(std::string_view fieldName) noexcept { + if constexpr (HasFieldMetadata) { + FieldMeta const* const meta = findFieldMeta(fieldName); + return meta != nullptr && meta->derived; + } else { + static_cast(fieldName); + return false; + } +} + /// @brief Splits @p fieldName on camelCase/underscore boundaries and /// title-cases each word (`dryMassPct` -> `"Dry Mass Pct"`, /// `sample_id` -> `"Sample Id"`, `notes` -> `"Notes"`). @@ -563,8 +603,19 @@ concept DeclaresSchemaMarker = requires { { std::remove_cvref_t::schemaMarker() } noexcept -> std::convertible_to; }; +/// @brief Concept: a field type that marks its schema property with a +/// keyword and a text value of its own, through a `static schemaValue()` +/// returning the pair — `morph::table::RowSelection` names its table's +/// record under `x-selectionOf` this way. The value is computed when the +/// schema is written, since it may come from a registry. +template +concept DeclaresSchemaValue = requires { + { std::remove_cvref_t::schemaValue() } -> std::convertible_to>; +}; + /// @brief Sets the keyword a member type declares with `schemaMarker()` on -/// its property; does nothing for any other type. +/// its property, and the keyword and value it declares with +/// `schemaValue()`; does nothing for any other type. /// @tparam Member The member's type. /// @param property The property's schema node. template @@ -573,6 +624,11 @@ void annotateSchemaMarker(glz::generic_u64& property) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- glaze DOM requires operator[] property[std::string{Member::schemaMarker()}] = true; } + if constexpr (DeclaresSchemaValue) { + auto [keyword, value] = std::remove_cvref_t::schemaValue(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- glaze DOM requires operator[] + property[std::string{keyword}] = std::move(value); + } } /// @brief Concept: a field type that declares slider bounds via `noexcept` @@ -622,6 +678,26 @@ template return {}; } +/// @brief Whether glaze writes @p T as one of its own members: its `glz::meta` +/// value is a member pointer, as a table's query action's is. +template +concept WrittenAsMember = requires { glz::meta::value; } && + std::is_member_object_pointer_v::value)>>; + +/// @brief How many members glaze reflects on @p T, counted without reading their names: naming a member needs the type +/// to have linkage, so a walk that reads no name (a type local to a translation unit's unnamed namespace) still +/// compiles. +/// @tparam T A type glaze reflects by itself or one with a `glz::meta` object. +/// @return The count, equal to `glz::reflect::size`. +template +[[nodiscard]] consteval std::size_t reflectedCount() noexcept { + if constexpr (glz::reflectable) { + return glz::tuple_size_v()))>>; + } else { + return glz::reflect::size; + } +} + /// @brief Invokes `visitor.operator()(name, member)` for every key glaze /// reflects on @p action, with the value glaze reads and writes under /// that key (`morph::detail::reflectedMember`). Under a `glz::meta` @@ -640,15 +716,22 @@ template // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) constexpr void forEachNamedMember(A&& action, Visitor&& visitor) { using Plain = std::remove_cvref_t; - constexpr auto memberCount = glz::reflect::size; - [&](std::index_sequence) { - // `I` is a pack of `std::index_sequence`, i.e. every value in - // [0, glz::reflect::size), and `keys` is an array of exactly that - // size — the index cannot be out of range by construction. The directive - // stays on one physical line; see the note at detail/fixed_string.hpp:48. - // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) - (visitor.template operator()(glz::reflect::keys[I], morph::detail::reflectedMember(action)), ...); - }(std::make_index_sequence{}); + // A type glaze writes as one of its members (its `glz::meta` value is a + // member pointer) has that member's keys. + if constexpr (WrittenAsMember) { + forEachNamedMember(action.*(glz::meta::value), visitor); + } else { + constexpr auto memberCount = glz::reflect::size; + [&](std::index_sequence) { + // `I` is a pack of `std::index_sequence`, i.e. every value in + // [0, glz::reflect::size), and `keys` is an array of exactly that + // size — the index cannot be out of range by construction. The directive + // stays on one physical line; see the note at detail/fixed_string.hpp:48. + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + (visitor.template operator()(glz::reflect::keys[I], morph::detail::reflectedMember(action)), + ...); + }(std::make_index_sequence{}); + } } /// @brief Extracts the containing class type from a pointer-to-member type. @@ -2259,6 +2342,22 @@ void collectComputedInputs(const A& probe, const ComputedField{resolveMemberName(probe, Inputs)...}); } +/// @brief Writes a computed member's `x-readonly` and `x-computed` (`{"inputs": [...]}`) on its property. +/// @param property The member's property node. +/// @param inputs The wire names of the members it is computed from, in declaration order. +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) — glaze DOM requires operator[] +inline void annotateComputedProperty(glz::generic_u64& property, std::vector const& inputs) { + property["x-readonly"] = true; + glz::generic_u64 computedMeta{}; + glz::generic_u64::array_t inputsList{}; + for (auto const& inputName : inputs) { + inputsList.emplace_back(std::string{inputName}); + } + computedMeta["inputs"] = inputsList; + property["x-computed"] = std::move(computedMeta); +} +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + /// @brief Trait: is `T` a `std::vector<...>`? Exposes the element type as /// `ValueType` (`void` when `T` is not a vector). template @@ -2353,6 +2452,17 @@ inline void annotateDeclaredBounds(glz::generic_u64& property, const FieldMeta& } } +/// @brief Whether a member is a `table::MeasureValue`, an amount with its unit's id, or an optional one. +/// +/// Compared by type alone, so it needs no table header: a translation unit that never includes +/// `` has no such member and the comparison with the incomplete type is `false`. +/// @tparam T The member's static type. +template +inline constexpr bool isMeasureValue = std::same_as, ::morph::table::MeasureValue>; +// An optional member is a measure when its value is. +template +inline constexpr bool isMeasureValue> = isMeasureValue; + /// @brief Whether a member is a bare `math::Rational`, or an optional one. /// @tparam T The member's static type. template @@ -2494,8 +2604,8 @@ void annotateMetaOptions(glz::generic_u64& property, std::string_view name, Fiel } // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- glaze DOM requires operator[] -/// @brief Applies the annotations a member's `FieldMeta` declares: help, placeholder, flags, bounds, display unit, -/// options, `since` and `blankAs`. +/// @brief Applies the annotations a member's `FieldMeta` declares: help, placeholder, flags (`derived` implies +/// read-only), bounds, display unit, options, `since` and `blankAs`. /// @tparam Owner The type declaring @p name. /// @tparam Member The static type of the member. /// @param property DOM node for this one property. @@ -2512,6 +2622,10 @@ void annotateFieldMeta(glz::generic_u64& property, std::string_view name, FieldM if (meta.readOnly) { property["x-readonly"] = true; } + if (meta.derived) { + property["x-derived"] = true; + property["x-readonly"] = true; + } if (meta.hidden) { property["x-hidden"] = true; } @@ -2561,9 +2675,9 @@ void annotateQuantity(glz::generic_u64& property) { /// single implementation of those rules; neither caller duplicates it. /// /// Deliberately excludes computed-field annotations (`x-computed`/ -/// `x-readonly`) and `x-order`: computed fields are not supported inside a -/// nested aggregate (see `annotateNestedAggregate`), and `x-order`'s source index -/// differs by caller, so each caller sets it itself. +/// `x-readonly`) and `x-order`: each caller reads the computed fields of its own +/// type (`annotateComputedProperty`), and `x-order`'s source index differs by +/// caller, so each caller sets them itself. /// @tparam Owner The type declaring @p name (drives `FieldMeta`/widget-override lookup). /// @tparam Member The static type of the member itself (drives type-driven annotations). /// @param property DOM node for this one property; annotations are merged in, not replacing. @@ -2593,6 +2707,12 @@ void annotateBasicMemberProperty(glz::generic_u64& property, std::string_view na if (fieldMeta != nullptr) { annotateFieldMeta(property, name, *fieldMeta); } + + if constexpr (isMeasureValue) { + // The units are the application's at run time, listed by the table's description, not by the schema. + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): glz::generic's operator[] keys by name; it indexes no sequence + property["x-measure"] = true; + } if constexpr (units::isQuantity) { annotateQuantity(property); } @@ -2836,9 +2956,12 @@ void recurseIntoNestedAggregateIfAny(SchemaDomRef dom, glz::generic_u64& propert /// {...}}` shape this function needs, so one implementation handles both -- /// see the call site in `mergeSchemaExtras` for how @p node is resolved. /// -/// Computed fields, `formLayout`/`fieldSpans`, and `formRules` stay -/// top-level-only regardless of depth; a nested `Sub` declaring any of those -/// has no effect here. +/// A `Sub` declaring `computedFields` has those members written `x-computed` +/// and `x-readonly` and left out of `required`, as the top level's are, since +/// `recomputeAll` recomputes every nested aggregate (`detail::forEachNested`); a +/// derived member (`FieldMeta::derived`) is left out of `required` too. +/// `formLayout`/`fieldSpans` and `formRules` stay top-level-only regardless of +/// depth; a nested `Sub` declaring any of those has no effect here. /// /// For a `Sub` that is reachable from itself, this is entered once: the /// caller's @p visited set records the `$defs` key on first arrival, and a @@ -2856,13 +2979,23 @@ template void annotateNestedAggregate(SchemaDomRef dom, glz::generic_u64& node, NestedDefsVisited& visited) { Sub probe{}; glz::generic_u64::array_t requiredNames{}; + // A row type's own computed fields: recomputed with each element (`recomputeAll`), so written as the top level's. + std::unordered_map> computedInputs{}; + if constexpr (HasComputedFields) { + std::apply([&](const auto&... field) { (collectComputedInputs(probe, field, computedInputs), ...); }, + Sub::computedFields.fields); + } forEachNamedMember(probe, [&](std::string_view name, const auto& member) { using Member = std::remove_cvref_t; - if (!(isStdOptional || declaredOptional(name))) { + bool const isComputed = computedInputs.contains(name); + if (!(isStdOptional || declaredOptional(name) || isComputed || declaredDerived(name))) { requiredNames.emplace_back(std::string{name}); } auto& property = node["properties"][std::string{name}]; property["x-order"] = std::uint64_t{I}; + if (isComputed) { + annotateComputedProperty(property, computedInputs.at(name)); + } annotateBasicMemberProperty(property, name); recurseIntoNestedAggregateIfAny(dom, property, visited); }); @@ -3229,6 +3362,90 @@ void annotateSubmitMode(glz::generic_u64& dom) { } } } + +/// @brief Writes the keyword and value an action type declares with `schemaValue()` at its schema's root: a table's +/// `CellEdit` or `RowEdit` action is itself the marked type, so its keyword has no property to sit on, unlike a +/// member's (`annotateSchemaMarker`). Does nothing for any other type. +/// @tparam A Action type whose schema is being annotated. +/// @param dom Schema DOM to stamp in place. +template +void annotateSchemaRoot(glz::generic_u64& dom) { + if constexpr (DeclaresSchemaValue) { + auto [keyword, value] = A::schemaValue(); + dom[std::string{keyword}] = std::move(value); + } else { + static_cast(dom); + } +} +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + +/// @brief A row type that declares the data levels of its columns, as +/// `static constexpr std::array columnLevels() noexcept`, each entry naming a +/// member by `column` and its level by `level`. +template +concept HasColumnLevels = requires { + { A::columnLevels() }; +}; + +/// @brief Stamps `x-level` on each property `A::columnLevels()` names, so a table's column derived from the +/// schema knows the data level its cells need (`docs/spec/table/table.md`, "Data levels"). +/// +/// An entry naming a member `A` does not have is skipped here: the table refuses it where it reflects the +/// columns, and a schema is never the place generation throws over a name. +/// @tparam A Type whose schema is being annotated. +/// @param dom Schema DOM to stamp in place. +/// @param memberNames Wire keys of every reflected member of `A`. +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- glaze DOM requires operator[] +template +void annotateColumnLevels(glz::generic_u64& dom, std::span memberNames) { + if constexpr (HasColumnLevels) { + for (auto const& entry : A::columnLevels()) { + if (std::ranges::find(memberNames, std::string_view{entry.column}) == memberNames.end()) { + continue; + } + dom["properties"][std::string{entry.column}]["x-level"] = std::string{entry.level}; + } + } else { + static_cast(dom); + static_cast(memberNames); + } +} +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + +/// @brief A row type that declares column groups, as +/// `static constexpr std::array columnGroups() noexcept`, each entry naming a +/// group by `id` and its members by `columns`. +template +concept HasColumnGroups = requires { + { A::columnGroups() }; +}; + +/// @brief Stamps `x-column-group` on each property `A::columnGroups()` names, so a table's column derived from the +/// schema knows the declared group it is in (`docs/spec/table/table.md`, "Column groups"). Not `x-group`, +/// which a form layout writes for the title of a field's group. +/// +/// A column naming a member `A` does not have is skipped here: the table refuses a group whose columns it lacks +/// where it reads the columns. +/// @tparam A Type whose schema is being annotated. +/// @param dom Schema DOM to stamp in place. +/// @param memberNames Wire keys of every reflected member of `A`. +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- glaze DOM requires operator[] +template +void annotateColumnGroups(glz::generic_u64& dom, std::span memberNames) { + if constexpr (HasColumnGroups) { + for (auto const& group : A::columnGroups()) { + for (auto const column : group.columns) { + if (std::ranges::find(memberNames, column) == memberNames.end()) { + continue; + } + dom["properties"][std::string{column}]["x-column-group"] = std::string{group.id}; + } + } + } else { + static_cast(dom); + static_cast(memberNames); + } +} // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) /// @brief The DOM post-merge behind `schemaJson`: adds the derived `required` @@ -3244,6 +3461,7 @@ void annotateSubmitMode(glz::generic_u64& dom) { /// throws. // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) — glaze DOM requires operator[] template +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. [[nodiscard]] std::string mergeSchemaExtras(std::string rawSchema) { // u64 number mode: the schema carries int64/uint64 bounds in $defs, which // the default double-only DOM would silently round. @@ -3293,7 +3511,9 @@ template const bool isComputed = computedInputs.contains(name); // A computed field is derived, not user-entered: exclude it from // `required` the same way an opted-out or std::optional field is. - const bool isOptional = isStdOptional || declaredOptional(name) || isComputed; + // A derived member is the model's to set, so it is not required either. + const bool isOptional = + isStdOptional || declaredOptional(name) || isComputed || declaredDerived(name); if (!isOptional) { requiredNames.emplace_back(std::string{name}); requiredMemberNames.push_back(name); @@ -3301,14 +3521,7 @@ template auto& property = dom["properties"][std::string{name}]; property["x-order"] = std::uint64_t{I}; if (isComputed) { - property["x-readonly"] = true; - glz::generic_u64 computedMeta{}; - glz::generic_u64::array_t inputsList{}; - for (auto const& inputName : computedInputs.at(name)) { - inputsList.emplace_back(std::string{inputName}); - } - computedMeta["inputs"] = inputsList; - property["x-computed"] = computedMeta; + annotateComputedProperty(property, computedInputs.at(name)); } // Label/title/FieldMeta/Quantity/Choice/widget/ranged-bounds: shared @@ -3334,6 +3547,8 @@ template // Always assign — an explicit empty array beats leaving whatever the // schema writer may have emitted (or omitted) for `required`. dom["required"] = requiredNames; + annotateColumnLevels(dom, memberNames); + annotateColumnGroups(dom, memberNames); // Layout & grouping (docs/spec/forms/forms.md, "Layout & grouping"): // purely additive over the required/x-order pass above; a no-op unless @@ -3419,6 +3634,7 @@ template } annotateSubmitMode(dom); + annotateSchemaRoot(dom); // Exact companions for any bound a double cannot hold. Last, so it also // covers nodes added by the passes above. @@ -3469,10 +3685,13 @@ template return detail::ComputeList{std::tuple{fields...}}; } -/// @brief Recomputes every entry of `A::computedFields` in place on @p action. +/// @brief Recomputes every entry of `A::computedFields` in place on @p action, +/// after every nested aggregate of it (each element of a `std::vector` +/// member, a nested struct member, either inside an engaged `std::optional`, +/// recursively: `detail::forEachNested`), so an entry over the rows reads +/// them recomputed. A derived member (`FieldMeta::derived`) is never touched. /// -/// A no-op for actions with no `computedFields` declaration -- backward -/// compatible with every existing action type. For an action that does +/// A no-op for actions with no `computedFields` declaration at any depth. For an action that does /// declare `computedFields`, every entry is evaluated in declaration order via /// `detail::recomputeOne` (see that function for the per-entry semantics: /// empty-input propagation and declared-precision retagging). Called from the @@ -3482,13 +3701,88 @@ template /// identical function over identically-reconciled inputs. /// @tparam A Action type (a reflectable aggregate). /// @param action Draft action whose computed members are overwritten in place. +template +constexpr void recomputeAll(A& action); + +namespace detail { + +/// @brief A member type the server's walks descend into: a reflectable aggregate with no empty state of its own (not a +/// `Quantity`, `Choice` or `Timestamp`), whose members can be computed or derived. +template +concept NestedAggregate = ReflectableAggregate && !EmptyCapableField; + +/// @brief Calls @p visit on every nested aggregate directly inside @p object: a member of a `NestedAggregate` type, +/// each +/// element of a `std::vector` of them, and either of those inside an engaged `std::optional`: the shapes the +/// schema describes a nested aggregate's members in (`recurseIntoNestedAggregateIfAny`). The walk reads no +/// member name, so it compiles for a type local to an unnamed namespace. +/// @tparam A The object's type. +/// @tparam Visit A callable taking any nested aggregate by reference. +/// @param object The object whose nested aggregates are visited. +/// @param visit Called once per nested aggregate, in member order. +template +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +constexpr void forEachNested(A& object, Visit const& visit) { + using Plain = std::remove_cvref_t; + if constexpr (WrittenAsMember) { + forEachNested(object.*(glz::meta::value), visit); + } else if constexpr (glz::reflectable || glz::glaze_object_t) { + constexpr auto memberCount = reflectedCount(); + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + [&](std::index_sequence) { + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + [[maybe_unused]] auto one = [&]() { + // A `glz::meta` entry that computes its value yields a value: nothing is stored behind it. + [[maybe_unused]] decltype(auto) member = morph::detail::reflectedMember(object); + using Member = std::remove_cvref_t; + if constexpr (!std::is_lvalue_reference_v || + std::is_const_v>) { + return; + } else if constexpr (IsStdVector::value) { + if constexpr (NestedAggregate::ValueType>) { + for (auto& element : member) { + visit(element); + } + } + } else if constexpr (isStdOptional) { + // The schema decides an engaged value as it decides the member itself: a nested aggregate, or a + // `std::vector` of them. + using Value = Member::value_type; + if constexpr (NestedAggregate) { + if (member.has_value()) { + visit(*member); + } + } else if constexpr (IsStdVector::value) { + if constexpr (NestedAggregate::ValueType>) { + if (member.has_value()) { + for (auto& element : *member) { + visit(element); + } + } + } + } + } else if constexpr (NestedAggregate) { + visit(member); + } + }; + (one.template operator()(), ...); + }(std::make_index_sequence{}); + } else { + static_cast(object); + static_cast(visit); + } +} + +} // namespace detail + template constexpr void recomputeAll(A& action) { + // The nested aggregates first (each element of a `std::vector`, a nested struct), so a top-level entry over them + // (a sum of the rows' totals) reads them recomputed. + detail::forEachNested(action, [](auto& nested) { ::morph::forms::recomputeAll(nested); }); if constexpr (detail::HasComputedFields) { std::apply([&](const auto&... field) { (detail::recomputeOne(action, field), ...); }, A::computedFields.fields); - } else { - static_cast(action); } } @@ -3659,9 +3953,10 @@ inline void enforceQuantityBounds(const A& action) { /// /// Empty-capable covers `Quantity`, `Choice`, `Timestamp`, and any user type /// satisfying `EmptyCapableField`. Required means: not a `std::optional<...>` -/// member, not listed in `A::optionalFields`, and not the destination of a +/// member, not listed in `A::optionalFields`, not the destination of a /// `A::computedFields` entry (a computed field is never something the user -/// must fill -- see `morph::forms::recomputeAll`). Intended as the body of the +/// must fill -- see `morph::forms::recomputeAll`), and not a derived member +/// (`FieldMeta::derived`, which the model sets). Intended as the body of the /// action's `validate()`. /// /// The walk is flat: only @p action's own top-level members are inspected, @@ -3681,7 +3976,9 @@ template if constexpr (EmptyCapableField) { const bool isComputed = detail::isComputedDestinationMember(action, static_cast(std::addressof(member))); - if (!detail::declaredOptional(name) && !isComputed && !member.hasValue()) { + // A derived member is the model's to set, and the dispatch path clears it before the validator runs. + if (!detail::declaredOptional(name) && !isComputed && !detail::declaredDerived(name) && + !member.hasValue()) { allEngaged = false; } } else { @@ -3709,6 +4006,10 @@ template /// be filled at all is `required`/`allRequiredEngaged`'s question. A field /// with no empty state is always checked. /// +/// **A derived member is not checked** (`FieldMeta::derived`): every execution +/// path clears it before the validator runs, and the model sets it afterwards, +/// so a bound on it describes the model's value, which this check never sees. +/// /// Bounds are read from these member kinds and no others: `Quantity` (its /// engaged `math::Rational`, in the canonical unit), a bare `math::Rational`, /// and an integral member satisfying `detail::BoundCheckableInteger`. A @@ -3728,7 +4029,7 @@ template detail::forEachNamedMember(action, [&](std::string_view name, const auto& member) { using Member = std::remove_cvref_t; const FieldMeta* meta = detail::findFieldMeta(name); - if (meta == nullptr || !detail::declaresAnyBound(*meta)) { + if (meta == nullptr || meta->derived || !detail::declaresAnyBound(*meta)) { return; } if constexpr (units::isQuantity) { diff --git a/include/morph/forms/views.hpp b/include/morph/forms/views.hpp index 5c913d139..a911399c3 100644 --- a/include/morph/forms/views.hpp +++ b/include/morph/forms/views.hpp @@ -239,9 +239,11 @@ concept HasViewActions = requires { /// @brief The table column kind of a row property (spec 7 §4), by the names /// `morph::table::ColumnKind` reads: `integer`, `decimal`, `quantity`, -/// `number`, `text`, `date`, `dateTime`, `bool`, `custom`. +/// `number`, `text`, `date`, `dateTime`, `bool`, `custom`, `measure`. /// -/// `x-comparator` makes a column `custom`; an exact value (`num`/`den`) is +/// `x-comparator` makes a column `custom`; `x-measure` makes it `measure`, +/// tested before the exact-value rule since a measure's object has `num` and +/// `den` too; an exact value (`num`/`den`) is /// `quantity` when it carries units and `decimal` otherwise; an integer with /// `x-widget` `epochDays` or `epochSeconds` is a `date` or `dateTime`; a /// string with `format` `date` or `date-time` likewise; a boolean is `bool`; @@ -254,6 +256,10 @@ concept HasViewActions = requires { if (findMember(prop, "x-comparator") != nullptr) { return "custom"; } + if (auto const* const measure = findMember(prop, "x-measure"); + measure != nullptr && measure->is_boolean() && measure->get_boolean()) { + return "measure"; + } auto const& node = *resolveSchemaRef(rowDom, prop); auto const* const properties = findMember(node, "properties"); if (properties != nullptr && findMember(*properties, "num") != nullptr && @@ -339,11 +345,12 @@ concept HasViewActions = requires { // What a table needs beyond the forms view: the column's kind, the // schema's title (the header a table shows when no label is declared), // the unit alternatives a quantity column offers, the values of a closed - // set, and the name of a custom comparator. Each is a write into the + // set, the name of a custom comparator, the data level the column's + // cells need, and the declared group it is in. Each is a write into the // entry being built; see the directive above. // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) entry["kind"] = std::string{inferColumnKind(rowDom, prop)}; - for (std::string_view const key : {"title", "x-unitAlternatives", "x-comparator"}) { + for (std::string_view const key : {"title", "x-unitAlternatives", "x-comparator", "x-level", "x-column-group"}) { if (auto const* const value = ::morph::forms::detail::findMember(prop, key)) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) entry[std::string{key}] = *value; diff --git a/include/morph/qt_quick/backend.hpp b/include/morph/qt_quick/backend.hpp index 6d72d722e..ff29c3334 100644 --- a/include/morph/qt_quick/backend.hpp +++ b/include/morph/qt_quick/backend.hpp @@ -3,6 +3,7 @@ #pragma once #include #include +#include #include #include #include @@ -81,6 +82,15 @@ class Backend final : public ui::IViewBackend { /// @copydoc ui::IViewBackend::setOnWidthClass void setOnWidthClass(std::function onWidthClass) override; + /// @brief Puts text on the system clipboard, `QGuiApplication::clipboard()`. + /// @param text The text, UTF-8. + /// @return True when the application has a clipboard. + bool copyText(std::string_view text) override; + + /// @brief Reads the system clipboard's text, `QGuiApplication::clipboard()`. + /// @return The text, UTF-8; nothing when the application has no clipboard or it holds no text. + [[nodiscard]] std::optional pasteText() override; + /// @copydoc ui::IViewBackend::createText [[nodiscard]] std::unique_ptr createText(ui::ContainerWidget* parent) override; /// @copydoc ui::IViewBackend::createButton diff --git a/include/morph/table/bands.hpp b/include/morph/table/bands.hpp new file mode 100644 index 000000000..f4967d4a1 --- /dev/null +++ b/include/morph/table/bands.hpp @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file table/bands.hpp +/// @brief `BandInfo`: a header band over a table's columns, light enough for the view tree to hold. +/// +/// See `docs/spec/table/editing.md`, "Header bands". + +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table { + +/// @brief A heading over columns, drawn above their headers, with the bands one level down beneath it. +// NOLINTNEXTLINE(misc-no-recursion): a band holds its child bands. +struct BandInfo { + /// @brief The band's text. + std::string label; + /// @brief The unit shown after the label, as a column's is ("Mass retained [g]"); empty for none. A column under + /// the band whose unit is the same does not repeat it. + std::string unit; + /// @brief The ids of the columns under the band. + std::vector columns; + /// @brief The bands one level down, each over a subset of `columns`. + std::vector bands; + + /// @brief Member-wise equality. + /// @param other The band to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(BandInfo const& other) const = default; +}; + +/// @brief How many levels of bands a table may nest: a band, its children and theirs. +inline constexpr std::size_t kMaxBandLevels = 3; + +namespace detail { + +/// @brief Why bands of one level cannot be drawn over the columns their parent covers, recursing into each band's own. +/// @param bands The bands of one level. +/// @param known Every column id of the table; null leaves the ids unchecked. +/// @param parent The columns the enclosing band covers; null at the top level. +/// @param level The level of @p bands, 1 for the top. +/// @return The refusal, naming the band's label; nothing when the bands can be drawn. +// NOLINTNEXTLINE(misc-no-recursion): a band's children are bands one level down. +[[nodiscard]] inline std::optional bandLevelRefusal(std::span bands, + std::span const* known, + std::vector const* parent, + std::size_t level) { + std::vector claimed; + for (BandInfo const& band : bands) { + std::string const named = "band `" + band.label + "` "; + if (level > kMaxBandLevels) { + return named + "nests past " + std::to_string(kMaxBandLevels) + " levels"; + } + if (band.columns.empty()) { + return named + "names no column"; + } + for (std::string const& columnId : band.columns) { + if (known != nullptr && !std::ranges::contains(*known, columnId)) { + return std::format("{}names `{}`, which is not a column of the table", named, columnId); + } + if (parent != nullptr && !std::ranges::contains(*parent, columnId)) { + return std::format("{}covers `{}`, which its parent band does not", named, columnId); + } + if (std::ranges::contains(claimed, columnId)) { + return std::format("{}covers `{}`, which another band of its level covers", named, columnId); + } + claimed.push_back(columnId); + } + if (auto refused = bandLevelRefusal(band.bands, known, &band.columns, level + 1)) { + return refused; + } + } + return std::nullopt; +} + +} // namespace detail + +/// @brief Why header bands cannot be drawn: a band nested past `kMaxBandLevels` levels, a band naming no column, a +/// band naming a column id the table does not have, a child band over a column its parent lacks, or a column in +/// two bands of one level. +/// @param bands The bands, outermost first. +/// @param known Every column id of the table; empty leaves the ids unchecked (a document's bands over a model's +/// table, whose columns come with its description). +/// @return The refusal, naming the band's label; nothing when the bands can be drawn. +[[nodiscard]] inline std::optional bandRefusal(std::span bands, + std::span known) { + return detail::bandLevelRefusal(bands, known.empty() ? nullptr : &known, nullptr, 1); +} + +} // namespace morph::table diff --git a/include/morph/table/data_source.hpp b/include/morph/table/data_source.hpp index b4e20a77f..787312690 100644 --- a/include/morph/table/data_source.hpp +++ b/include/morph/table/data_source.hpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -28,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -57,6 +59,7 @@ enum class ColumnKind : std::uint8_t { Bool, ///< `false` before `true`. Key, ///< An `int64` key, compared numerically. Custom, ///< Ordered by a named comparator from `Services::comparators`. + Measure, ///< An exact amount in a unit each cell names, ordered by dimension and then by base amount. }; /// @brief A row's identity: the table's key, stable across reloads. @@ -73,14 +76,58 @@ struct QuantityCell { math::Rational amount; /// @brief Multiplier from the cell's unit to the column's canonical unit. math::Rational toCanonical; + + /// @brief Member-wise equality, by value: `Rational`'s equality ignores decimal places, so two cells that + /// differ only in places are equal. + /// @param other The cell to compare with. + /// @return `true` when the amounts are equal and the factors are equal. + [[nodiscard]] bool operator==(QuantityCell const& other) const = default; +}; + +/// @brief A cell whose value is not loaded yet. It is neither a value nor empty. +/// +/// Only a column with a data level (`ColumnInfo::level`) may hold one. It sorts +/// after every other cell in either direction, and every filter operator is +/// unknown on it, so a row whose filter depends on it is undecided rather than +/// shown or rejected. +struct Unloaded { + /// @brief Every unloaded cell equals every other. + /// @return `true`. + friend constexpr bool operator==(Unloaded, Unloaded) noexcept = default; +}; + +/// @brief A unit's number in one `UnitRegistry` lineage: a place in the registry, stable across its successors. +using UnitId = std::uint32_t; + +/// @brief The number no registry gives a unit: a cell holding it is invalid. +inline constexpr UnitId kUnknownUnit = std::numeric_limits::max(); + +/// @brief An exact amount in a named unit: a cell of a `Measure` column. +/// +/// The unit is a number of the registry the cell was made with (`Services::units`); on the wire it is always the +/// unit's string id. +struct Measure { + /// @brief The amount, in the cell's own unit. + math::Rational amount; + /// @brief The unit's number in the registry. + UnitId unit = 0; + + /// @brief Member-wise equality: the amounts by `Rational`'s equality, which ignores decimal places. + /// @param other The cell to compare with. + /// @return `true` when the amounts are equal and the units are the same number. + [[nodiscard]] bool operator==(Measure const& other) const = default; }; /// @brief One cell as a data source hands it out. /// /// `std::monostate` is an empty cell. A `std::string` in a non-text column is /// parsed for the column's kind when its key is built; text that does not parse -/// is an invalid cell. -using Cell = std::variant; +/// is an invalid cell. `Unloaded` is a cell whose value has not arrived. `Measure` is an amount with its unit. +using Cell = std::variant; + +// A measure is no larger than a quantity, so adding it does not grow a cell. +static_assert(sizeof(Measure) <= sizeof(QuantityCell)); /// @brief A column's identity and kind. struct ColumnInfo { @@ -92,10 +139,15 @@ struct ColumnInfo { std::string comparator; /// @brief For a `Date` or `DateTime` column holding text, the format handed to the `DateParser`. std::string format; + /// @brief The data level the column's cells need. Empty is the base level, which every row has when it exists. + std::string level; + /// @brief For a `Measure` column, the dimensions it allows, in the order their groups sort; empty allows every + /// dimension of the registry, in the registry's order. + std::vector dimensions; /// @brief Member-wise equality. /// @param other The column to compare with. - /// @return `true` when id, kind, comparator and format match. + /// @return `true` when id, kind, comparator, format, level and dimensions match. [[nodiscard]] bool operator==(ColumnInfo const& other) const = default; }; @@ -109,6 +161,8 @@ enum class TableErrorCode : std::uint8_t { ColumnNotReadable, ///< A sort or filter on a column the principal may not read. Unavailable, ///< An operation the table's mode does not offer. ServiceFailed, ///< An injected service (collator, date parser, comparator) threw. + SourceContract, ///< The source broke its contract: an unloaded cell in a base-level column. + ViewChanged, ///< A selection of the view resolved under `Exact` after the view's rows changed. }; /// @brief The error every fallible table call returns. @@ -188,21 +242,402 @@ struct TableError { math::DecimalPlaces{fractionDigits}}; } +// ── Units ─────────────────────────────────────────────────────────────────── + +/// @brief A unit known to a table: which dimension it measures and how it converts to that dimension's base unit. +/// +/// Not `ui::UnitInfo` (`ui/expression.hpp`), which describes a form field's unit. +struct UnitInfo { + /// @brief What a cell and an operand name: `"kg"`, `"g"`, `"percent"`; the ratio's unit is the one empty id. + std::string id; + /// @brief What is shown: `"kg"`, `"g"`, `"%"`. + std::string symbol; + /// @brief The dimension it measures: `"mass"`, `"ratio"`. + std::string dimension; + /// @brief The exact factor to the dimension's base unit: 1 for kg, 1/1000 for g, 1/100 for percent. + math::Rational toBase; + /// @brief The places an amount in this unit is shown to. + std::uint32_t decimals = 0; + + /// @brief Member-wise equality. + /// @param other The unit to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(UnitInfo const& other) const = default; +}; + +namespace detail { + +/// @brief A transparent string hash, so a unit is found by a view and nothing is copied. +struct UnitIdHash { + /// @brief Marks the hash transparent. + using is_transparent = void; + /// @brief Hashes @p text. + /// @param text The text. + /// @return The hash. + [[nodiscard]] std::size_t operator()(std::string_view text) const noexcept { + return std::hash{}(text); + } +}; + +/// @brief The next registry lineage of the process: one per registry built from nothing. +/// @return A lineage no registry of the process has had; never 0. +[[nodiscard]] MORPH_PROCESS_UNIQUE inline std::uint64_t nextUnitLineage() noexcept { + static std::atomic counter{0}; + return counter.fetch_add(1, std::memory_order_relaxed) + 1; +} + +} // namespace detail + +class UnitRegistryBuilder; + +/// @brief The units of a process, immutable once built and safe to read from any thread. +/// +/// A unit's number (`UnitId`) is its place in the registry. A registry is changed by building its successor from it +/// (`UnitRegistryBuilder{previous}`), which keeps every number, so cells holding numbers keep their meaning under +/// the successor; a removed unit's number stays a tombstone that `find` does not return and that no unit is given +/// again. A registry and its successors share a `lineage()`. +class UnitRegistry { +public: + /// @brief The live unit of id @p unitId. + /// @param unitId The unit's id. + /// @return Its number, or nothing when no live unit has the id. Each call is counted in `findCalls()`. + [[nodiscard]] std::optional find(std::string_view unitId) const { + _findCalls.fetch_add(1, std::memory_order_relaxed); + auto const found = _ids.find(unitId); + return found == _ids.end() ? std::nullopt : std::optional{found->second}; + } + + /// @brief A unit by number. + /// @param unit A number for which `contains` is `true`. + /// @return The unit. + [[nodiscard]] UnitInfo const& info(UnitId unit) const { return _units[unit]; } + + /// @brief Whether @p unit is the number of a live unit. + /// @param unit A number. + /// @return `false` for a tombstone, a number beyond the registry, and `kUnknownUnit`. + [[nodiscard]] bool contains(UnitId unit) const noexcept { return unit < _units.size() && _live[unit] != 0; } + + /// @brief How many numbers the registry has given out, tombstones included: every number below it is a unit's. + /// @return The count. + [[nodiscard]] std::size_t size() const noexcept { return _units.size(); } + + /// @brief The dimensions, in the order they were first registered. + /// @return The dimensions' names. + [[nodiscard]] std::span dimensions() const noexcept { return _dimensions; } + + /// @brief The live units of one dimension, largest base factor first. + /// @param dimension The dimension's name. + /// @return The units' numbers; none for a dimension the registry does not have. + [[nodiscard]] std::span unitsOf(std::string_view dimension) const { + auto const found = std::ranges::find(_dimensions, dimension); + if (found == _dimensions.end()) { + return {}; + } + return _byDimension[static_cast(found - _dimensions.begin())]; + } + + /// @brief The registry's lineage: shared with the registry it was built from and with its successors. + /// @return The lineage, never 0. + [[nodiscard]] std::uint64_t lineage() const noexcept { return _lineage; } + + /// @brief How often `find` was called. + /// @return The count, read relaxed: a measurement, not a synchronisation. + [[nodiscard]] std::uint64_t findCalls() const noexcept { return _findCalls.load(std::memory_order_relaxed); } + +private: + friend class UnitRegistryBuilder; + + std::vector _units; + std::vector _live; + std::unordered_map> _ids; + std::vector _dimensions; + std::vector> _byDimension; + std::uint64_t _lineage = 0; + mutable std::atomic _findCalls{0}; +}; + +/// @brief Builds an immutable `UnitRegistry`, from nothing or as the successor of another. +class UnitRegistryBuilder { +public: + /// @brief A builder of a new lineage, holding the ratio's unit `{"", "", "ratio", 1, 6}` as number 0. + UnitRegistryBuilder() : _lineage{detail::nextUnitLineage()} { + _units.push_back(UnitInfo{.id = {}, + .symbol = {}, + .dimension = "ratio", + .toBase = math::Rational{1, math::DecimalPlaces{0}}, + .decimals = 6}); + _live.push_back(1); + } + + /// @brief A builder of @p previous's successor: its units keep their numbers, its tombstones stay, and the + /// lineage is the same. + /// @param previous The registry to build from; null builds from nothing, as the default constructor does. + explicit UnitRegistryBuilder(std::shared_ptr const& previous) : UnitRegistryBuilder{} { + if (previous == nullptr) { + return; + } + _units = previous->_units; + _live = previous->_live; + _lineage = previous->_lineage; + } + + /// @brief Adds a unit, giving it the next number. + /// @param unit The unit. Its id is 1 to 32 bytes, holds no white space and does not begin with a digit, a sign, + /// a point or a comma, since an operand is an amount, a space and an id; its factor is positive and + /// its dimension named. + /// @return The unit's number; `InvalidSpec` naming the id for an id, factor or dimension that breaks a rule, or + /// for an id a live unit already has. + std::expected add(UnitInfo unit) { + auto const refuse = [&unit](std::string const& why) { + return std::unexpected(TableError{ + .code = TableErrorCode::InvalidSpec, .column = unit.id, .message = "unit \"" + unit.id + "\" " + why}); + }; + constexpr std::size_t kMaxIdBytes = 32; + auto const& unitId = unit.id; + if (unitId.empty() || unitId.size() > kMaxIdBytes) { + return refuse("has an id of " + std::to_string(unitId.size()) + " bytes, not 1 to 32"); + } + if (unitId.find_first_of(" \t\n\r\f\v") != std::string::npos) { + return refuse("has white space in its id"); + } + if (char const first = unitId.front(); + (first >= '0' && first <= '9') || first == '+' || first == '-' || first == '.' || first == ',') { + return refuse("has an id that begins like a number"); + } + if (unit.toBase.numerator <= 0 || unit.toBase.denominator <= 0) { + return refuse("has a factor that is not positive"); + } + if (unit.dimension.empty()) { + return refuse("names no dimension"); + } + for (std::size_t at = 0; at < _units.size(); ++at) { + if (_live[at] != 0 && _units[at].id == unitId) { + return refuse("is registered already"); + } + } + _units.push_back(std::move(unit)); + _live.push_back(1); + return static_cast(_units.size() - 1); + } + + /// @brief Removes a live unit; its number becomes a tombstone. + /// @param unitId The unit's id; the ratio's unit `""` cannot be removed. + /// @return `false` when no live unit has the id, or it is the ratio's. + bool remove(std::string_view unitId) { + if (unitId.empty()) { + return false; + } + for (std::size_t at = 0; at < _units.size(); ++at) { + if (_live[at] != 0 && _units[at].id == unitId) { + _live[at] = 0; + return true; + } + } + return false; + } + + /// @brief The base unit the builder holds for a dimension: its first live unit of factor 1. + /// @param dimension The dimension's name. + /// @return The unit's id, or nothing when the dimension has no such unit. + [[nodiscard]] std::optional baseOf(std::string_view dimension) const { + auto const one = math::Rational{1, math::DecimalPlaces{0}}; + for (std::size_t at = 0; at < _units.size(); ++at) { + if (_live[at] != 0 && _units[at].dimension == dimension && _units[at].toBase == one) { + return _units[at].id; + } + } + return std::nullopt; + } + + /// @brief Whether the builder holds a live unit of a dimension. + /// @param dimension The dimension's name. + /// @return `true` when a live unit measures it. + [[nodiscard]] bool holds(std::string_view dimension) const { + for (std::size_t at = 0; at < _units.size(); ++at) { + if (_live[at] != 0 && _units[at].dimension == dimension) { + return true; + } + } + return false; + } + + /// @brief The registry. + /// @return An immutable registry of the units added, numbered as they were. + [[nodiscard]] std::shared_ptr build() && { + auto out = std::make_shared(); + out->_units = std::move(_units); + out->_live = std::move(_live); + out->_lineage = _lineage; + for (std::size_t at = 0; at < out->_units.size(); ++at) { + auto const& unit = out->_units[at]; + auto dimension = std::ranges::find(out->_dimensions, unit.dimension); + if (dimension == out->_dimensions.end()) { + out->_dimensions.push_back(unit.dimension); + out->_byDimension.emplace_back(); + dimension = std::prev(out->_dimensions.end()); + } + if (out->_live[at] == 0) { + continue; + } + out->_ids.emplace(unit.id, static_cast(at)); + out->_byDimension[static_cast(dimension - out->_dimensions.begin())].push_back( + static_cast(at)); + } + for (auto& units : out->_byDimension) { + std::ranges::stable_sort(units, [&out](UnitId left, UnitId right) { + return out->_units[left].toBase > out->_units[right].toBase; + }); + } + return out; + } + +private: + std::vector _units; + std::vector _live; + std::uint64_t _lineage = 0; +}; + +/// @brief Adds the units of one of morph's compile-time unit enums, as a convenience for an application that has +/// them. +/// +/// Within a dimension the base is the unit the builder already holds for it (`UnitRegistryBuilder::baseOf`: `""` +/// for `ratio`), reached through the enumerator of @p units whose `UnitMeta::id` is its id; or else the first +/// enumerator of @p units in that dimension, added with factor 1. Every other unit's factor is the product of +/// `UnitRelation::fromTo` along a path of `UnitTraits::relations` to the base, each relation usable in both +/// directions, the reverse taking the reciprocal. A dimension the builder holds units of but no unit of factor 1 +/// has no base to convert to, and none of its units is added. A unit's `symbol` is `UnitMeta::display` and its +/// `decimals` `UnitMeta::defaultDecimals`. Every unit that resolves is added, in the order of @p units; one that +/// does not is left out. +/// @tparam E The unit enum. +/// @param builder The builder to add to. +/// @param units The enumerators to add. +/// @param dimensionOf The dimension of an enumerator. +/// @return Nothing, or the first refusal: `InvalidSpec` naming a unit with no path to its dimension's base, or what +/// `UnitRegistryBuilder::add` refuses. +template +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +std::expected addUnitsOf(UnitRegistryBuilder& builder, std::span units, + std::string_view (*dimensionOf)(E)) { + using Base = std::pair>; + auto const metaOf = [](E unit) -> units::UnitMeta { return units::UnitTraits::meta(unit); }; + auto const one = math::Rational{1, math::DecimalPlaces{0}}; + // The factor that converts one `from` to `to`: a breadth-first search of the relations. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + auto const factor = [&one](E from, E target) -> std::optional { + if (from == target) { + return one; + } + if constexpr (units::HasUnitRelations) { + std::vector> frontier{{from, one}}; + std::vector seen{from}; + for (std::size_t next = 0; next < frontier.size(); ++next) { + auto const [at, product] = frontier[next]; + for (auto const& relation : units::UnitTraits::relations) { + E reached{}; + math::Rational step; + if (relation.from == at) { + reached = relation.to; + step = relation.fromTo; + } else if (relation.to == at) { + auto const reverse = relation.fromTo.reciprocal(); + if (!reverse) { + continue; + } + reached = relation.from; + step = *reverse; + } else { + continue; + } + if (std::ranges::find(seen, reached) != seen.end()) { + continue; + } + auto const scaled = math::checkedMul(product, step); + if (!scaled) { + continue; + } + if (reached == target) { + return *scaled; + } + seen.push_back(reached); + frontier.emplace_back(reached, *scaled); + } + } + } + return std::nullopt; + }; + std::optional first; + auto const keep = [&first](TableError error) { + if (!first) { + first = std::move(error); + } + }; + auto const add = [&](units::UnitMeta const& meta, std::string const& dimension, math::Rational const& toBase) { + if (auto added = builder.add(UnitInfo{.id = std::string{meta.id}, + .symbol = std::string{meta.display}, + .dimension = dimension, + .toBase = toBase, + .decimals = meta.defaultDecimals}); + !added) { + keep(std::move(added.error())); + } + }; + // Per dimension met, the enumerator its base is reached through: none when the builder's base has none. + std::vector bases; + for (auto const unit : units) { + auto const meta = metaOf(unit); + auto const dimension = std::string{dimensionOf(unit)}; + auto base = std::ranges::find(bases, dimension, &Base::first); + if (base == bases.end()) { + auto const held = builder.baseOf(dimension); + if (!held && !builder.holds(dimension)) { + bases.emplace_back(dimension, unit); + add(meta, dimension, one); + continue; + } + // Held with no unit of factor 1: no enumerator reaches a base, so every unit of it is refused. + std::optional through; + for (auto const candidate : units) { + if (held && metaOf(candidate).id == *held) { + through = candidate; + } + } + bases.emplace_back(dimension, through); + base = std::prev(bases.end()); + } + if (base->second == unit) { + continue; // the dimension's base, which the builder holds + } + auto const toBase = base->second ? factor(unit, *base->second) : std::nullopt; + if (!toBase) { + keep(TableError{ + .code = TableErrorCode::InvalidSpec, + .column = std::string{meta.id}, + .message = "unit \"" + std::string{meta.id} + "\" has no relation to the base of " + dimension}); + continue; + } + add(meta, dimension, *toBase); + } + if (first) { + return std::unexpected(std::move(*first)); + } + return {}; +} + /// @brief The text a cell shows when it has to be ordered or matched as text. /// @param cell The cell. /// @return Its text: the string itself, a number in decimal form (a decimal -/// to its own places, `"12.5"`), `true` or `false`, or empty for an -/// empty cell. +/// to its own places, `"12.5"`; a quantity's or a measure's amount, without its unit, whose symbol is the +/// display layer's), `true` or `false`, or empty for an empty or an unloaded cell. [[nodiscard]] inline std::string displayText(Cell const& cell) { return std::visit( [](T const& value) -> std::string { - if constexpr (std::is_same_v) { + if constexpr (std::is_same_v || std::is_same_v) { return {}; } else if constexpr (std::is_same_v) { return value; } else if constexpr (std::is_same_v) { return value ? "true" : "false"; - } else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v || std::is_same_v) { return units::detail::formatRationalDecimal(value.amount); } else if constexpr (std::is_same_v) { return units::detail::formatRationalDecimal(value); @@ -213,6 +648,32 @@ struct TableError { cell); } +/// @brief The bytes a row key owns: what a cache of keys counts against its bound. +/// @param key The key. +/// @return `sizeof(RowId)`, plus a text key's heap buffer and its terminator when the text is not in the string's +/// own small buffer. +[[nodiscard]] inline std::size_t rowIdBytes(RowId const& key) noexcept { + std::size_t bytes = sizeof(RowId); + if (auto const* const text = std::get_if(&key); + text != nullptr && text->capacity() > std::string{}.capacity()) { + bytes += text->capacity() + 1; + } + return bytes; +} + +/// @brief The bytes a cell owns: what a cache of cells counts against its bound. +/// @param cell The cell. +/// @return `sizeof(Cell)`, plus a string's heap buffer and its terminator when the text is not in the string's +/// own small buffer. +[[nodiscard]] inline std::size_t cellBytes(Cell const& cell) noexcept { + std::size_t bytes = sizeof(Cell); + if (auto const* const text = std::get_if(&cell); + text != nullptr && text->capacity() > std::string{}.capacity()) { + bytes += text->capacity() + 1; + } + return bytes; +} + // ── Services ──────────────────────────────────────────────────────────────── /// @brief Orders and matches text. The renderer injects the toolkit's collator @@ -402,6 +863,9 @@ struct Services { std::map> comparators; /// @brief Optional progress receiver. std::shared_ptr progress; + /// @brief The units a `Measure` column's cells and operands name; a `Measure` column with none is a + /// `SourceContract` error. + std::shared_ptr units; /// @brief The collator to use. /// @return `collator`, or the shared default. @@ -434,6 +898,51 @@ struct Services { } }; +/// @brief The units a table's description lists: the live units of every dimension a `Measure` column of +/// @p columns allows. +/// @param registry The registry. +/// @param columns The columns; a `Measure` column with no `dimensions` allows every dimension of @p registry. +/// @return The units, in registry order; none when no column is `Measure`. +[[nodiscard]] inline std::vector unitsFor(UnitRegistry const& registry, + std::span columns) { + std::vector allowed; + for (auto const& column : columns) { + if (column.kind != ColumnKind::Measure) { + continue; + } + if (column.dimensions.empty()) { + allowed.assign(registry.dimensions().begin(), registry.dimensions().end()); + break; + } + allowed.insert(allowed.end(), column.dimensions.begin(), column.dimensions.end()); + } + std::vector out; + for (UnitId unit = 0; unit < registry.size(); ++unit) { + if (registry.contains(unit) && + std::ranges::contains(allowed, std::string_view{registry.info(unit).dimension})) { + out.push_back(registry.info(unit)); + } + } + return out; +} + +namespace detail { + +/// @brief Whether a `Measure` column is read without a registry: a broken contract, not a column to guess units for. +/// @param info The column. +/// @param services The services it is read with. +/// @return `SourceContract` naming the column when it is `Measure` and `services.units` is null; else nothing. +[[nodiscard]] inline std::optional unitsMissing(ColumnInfo const& info, Services const& services) { + if (info.kind != ColumnKind::Measure || services.units != nullptr) { + return std::nullopt; + } + return TableError{.code = TableErrorCode::SourceContract, + .column = info.id, + .message = "column " + info.id + " holds measures and the table has no unit registry"}; +} + +} // namespace detail + // ── Snapshots ─────────────────────────────────────────────────────────────── /// @brief Receives a run of one column's cells. @@ -490,6 +999,13 @@ class RowSnapshot { } } + /// @brief What the rows are, as an address: two snapshots with one identity hold the same rows. + /// + /// What a cache of views compares to know its view still describes the rows. A snapshot that wraps another + /// does not forward the other's identity, since its rows are its own. + /// @return This snapshot's address, unless an override names storage that outlives it. + [[nodiscard]] virtual void const* identity() const { return this; } + protected: /// @brief Copies the base of a snapshot: a derived snapshot makes a changed /// copy of itself this way. @@ -712,6 +1228,33 @@ struct RowChange { std::vector rows; }; +/// @brief A declared group of columns, filtered together. +struct ColumnGroupInfo { + /// @brief The group's id, which a column's `group` names. + std::string id; + /// @brief The group's text. + std::string label; + /// @brief The ids of its columns, 2 to 16 of one kind. + std::vector columns; + + /// @brief Member-wise equality. + /// @param other The group to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(ColumnGroupInfo const& other) const = default; +}; + +/// @brief One group of a typed row's `columnGroups()`: how a row type declares its groups, at compile time. +/// +/// A row type declares its groups once, as +/// `static constexpr std::array columnGroups() noexcept`; each group's `columns` views +/// an array of static storage duration. +struct ColumnGroup { + /// @brief The group's id. + std::string_view id; + /// @brief Its columns, by the members' JSON names. + std::span columns; +}; + /// @brief Receives a `DataSource`'s change notifications, on the owner thread. // NOLINTBEGIN(cppcoreguidelines-special-member-functions) class ChangeListener { @@ -748,11 +1291,55 @@ class DataSource { /// @brief Removes @p listener. /// @param listener A listener previously subscribed. virtual void unsubscribe(ChangeListener& listener) = 0; + + /// @brief The table's declared column groups: what a `GroupFilter` naming a `group` resolves through. + /// @return The groups; none unless the source declares some. + [[nodiscard]] virtual std::span groups() const { return {}; } }; // NOLINTEND(cppcoreguidelines-special-member-functions) namespace detail { +/// @brief Checks a source's declared groups against its columns. +/// +/// Each group has 2 to 16 columns, every one of them a column of the source and all of one kind, and no column is +/// in two groups. Run where the columns are read (`apply`, `distinctValues`, `Engine::setFilter`, a server's +/// reply), since a declaration is the source's contract. +/// @param columns The source's columns. +/// @param groups Its declared groups. +/// @return `SourceContract` naming the first group that breaks a rule, or nothing. +[[nodiscard]] inline std::optional checkGroups(std::span columns, + std::span groups) { + constexpr std::size_t kMaxColumns = 16; + std::vector seen; + for (auto const& group : groups) { + auto const broken = [&group](std::string why) { + return TableError{.code = TableErrorCode::SourceContract, + .column = group.id, + .message = "column group " + group.id + " " + std::move(why)}; + }; + if (group.columns.size() < 2 || group.columns.size() > kMaxColumns) { + return broken("has " + std::to_string(group.columns.size()) + " columns, not 2 to 16"); + } + std::optional kind; + for (auto const& columnId : group.columns) { + auto const column = std::ranges::find(columns, columnId, &ColumnInfo::id); + if (column == columns.end()) { + return broken("names no column " + columnId); + } + if (kind && *kind != column->kind) { + return broken("mixes column kinds"); + } + kind = column->kind; + if (std::ranges::find(seen, std::string_view{columnId}) != seen.end()) { + return broken("shares column " + columnId + " with another group, or names it twice"); + } + seen.emplace_back(columnId); + } + } + return std::nullopt; +} + /// @brief A source's listeners, notified so that a listener may unsubscribe /// itself or another, or destroy the source, from inside a notification. /// @@ -896,6 +1483,14 @@ class VectorSource final : public DataSource, public RowPatcher { return found == _index.end() ? std::nullopt : std::optional{found->second}; } + /// @brief Declares the table's column groups; notifies nothing. Checked where the columns are read. + /// @param groups The groups. + void setGroups(std::vector groups) { _groups = std::move(groups); } + + /// @brief The groups `setGroups` declared. + /// @return The groups. + [[nodiscard]] std::span groups() const override { return _groups; } + private: void reindex() { _index.clear(); @@ -905,6 +1500,7 @@ class VectorSource final : public DataSource, public RowPatcher { } std::vector _columns; + std::vector _groups; std::shared_ptr _snapshot; std::unordered_map _index; detail::Listeners _listeners; @@ -919,9 +1515,9 @@ template <> struct glz::meta { using enum morph::table::ColumnKind; /// @brief Each enumerator after its JSON name. - static constexpr auto value = - glz::enumerate("integer", Integer, "decimal", Decimal, "quantity", Quantity, "number", Number, "text", Text, - "date", Date, "dateTime", DateTime, "bool", Bool, "key", Key, "custom", Custom); + static constexpr auto value = glz::enumerate("integer", Integer, "decimal", Decimal, "quantity", Quantity, + "number", Number, "text", Text, "date", Date, "dateTime", DateTime, + "bool", Bool, "key", Key, "custom", Custom, "measure", Measure); }; /// @brief JSON names of `morph::table::TableErrorCode`, for a typed error on the wire. @@ -932,5 +1528,6 @@ struct glz::meta { static constexpr auto value = glz::enumerate("unknownColumn", UnknownColumn, "unsupportedOperator", UnsupportedOperator, "invalidValue", InvalidValue, "invalidSpec", InvalidSpec, "limitExceeded", LimitExceeded, "columnNotReadable", - ColumnNotReadable, "unavailable", Unavailable, "serviceFailed", ServiceFailed); + ColumnNotReadable, "unavailable", Unavailable, "serviceFailed", ServiceFailed, "sourceContract", + SourceContract, "viewChanged", ViewChanged); }; diff --git a/include/morph/table/description.hpp b/include/morph/table/description.hpp new file mode 100644 index 000000000..cbad97b4d --- /dev/null +++ b/include/morph/table/description.hpp @@ -0,0 +1,1512 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file table/description.hpp +/// @brief A table's description and the generic page: a table a client draws +/// and reads with no compile-time knowledge of its rows. +/// +/// A `TableDescription` says everything a client needs to draw a table: its +/// columns, their labels and groups, which column is the key. `describe` stamps +/// it with a revision, a hash of the rest, so two descriptions are equal +/// exactly when their revisions are. +/// +/// A `GenericPage` is a page of such a table: row arrays under one header of +/// column ids. Each cell is written by its `Cell` alternative and read back by +/// its JSON shape and its column's kind, so a cell the server keyed as invalid +/// is invalid on the client too. +/// +/// A model serves a table by a function returning a `ServedTable`, registered +/// with `BRIDGE_REGISTER_TABLE`; the registration makes the table's actions +/// (`QueryTable`, `DescribeTable`) and its record (`TableOf`). +/// +/// See `docs/spec/table/table.md`, "A table is a description", "A model's tables" and "Rows on the wire". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table { + +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- cell and column indices are bounded by the page's own counts, checked before they are used + +/// @brief How a column rounds a value it shows at fewer places than the value has: the expression language's two +/// modes, so a value a document rounds and the same value a column shows agree. JSON `"halfEven"`, `"halfUp"`. +enum class Rounding : std::uint8_t { + HalfEven, ///< A half rounds to the even last kept digit: 0.125 at 2 places is 0.12. + HalfUp, ///< A half rounds away from zero: 0.125 at 2 places is 0.13, -0.125 is -0.13. +}; + +} // namespace morph::table + +/// @brief JSON names of `morph::table::Rounding`: `halfEven`, `halfUp`. +template <> +struct glz::meta { + using enum morph::table::Rounding; + /// @brief Each enumerator after its JSON name. + static constexpr auto value = glz::enumerate("halfEven", HalfEven, "halfUp", HalfUp); +}; + +namespace morph::table { + +/// @brief A text a column shows for one particular value: a code's word, a flag in words. +struct ValueLabel { + /// @brief The value as a filter entry takes it: `"true"`, `"3"`, `"V"`. + std::string operand; + /// @brief What the cell shows for it. + std::string text; + + /// @brief Member-wise equality. + /// @param other The label to compare with. + /// @return `true` when both members match. + [[nodiscard]] bool operator==(ValueLabel const& other) const = default; +}; + +/// @brief How a column turns its cells into text on the client. It changes what a cell shows and nothing a sort, a +/// filter, a distinct value or a selection uses. +struct ColumnDisplay { + /// @brief Places shown for an `Integer`, `Decimal`, `Quantity` or `Number` cell; absent shows the value's own + /// places (a `Rational`'s declared places, a `double`'s shortest round trip). + std::optional decimals; + /// @brief How a value with more places than `decimals` is rounded for showing. + Rounding rounding = Rounding::HalfEven; + /// @brief With `decimals`, whether a value of fewer places is padded with zeros: 2 places shows 1.5 as "1.50". + bool padPlaces = true; + /// @brief Whether digits are grouped by the locale: 12,500. + bool grouping = false; + /// @brief What an empty cell shows: "-", "n/a". Empty shows nothing. + std::string empty; + /// @brief The unit of a plain numeric column, shown in its header; a `Measure` column's units are its cells'. + std::string unit; + /// @brief A `Date` or `DateTime` column's pattern; empty takes the session's. + std::string date; + /// @brief Text for particular values; a value no entry names shows as `decimals` says. + std::vector labels; + + /// @brief Member-wise equality. + /// @param other The display to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(ColumnDisplay const& other) const = default; +}; + +/// @brief The action that edits a column's cells, on a model's table (`docs/spec/table/editing.md`, "Cells of a +/// model's +/// table"). +struct EditInfo { + /// @brief The action's id: it takes a `CellEdit` or a `RowEdit` of the column's table. + std::string action; + /// @brief For a `RowEdit`, the member of its `values` the column edits; empty for a `CellEdit`. + std::string member; + /// @brief The id of a companion column whose `true` makes the row's cell read-only; empty for none. + std::string readonly; + + /// @brief Member-wise equality. + /// @param other The edit to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(EditInfo const& other) const = default; +}; + +/// @brief One column of a table's description. +struct TableColumn { + /// @brief The column's id and kind, as the engine reads them. + ColumnInfo info; + /// @brief The header's text. + std::string label; + /// @brief The id of the declared column group the column belongs to, or empty. + std::string group; + /// @brief Whether the user may sort by the column. + bool sortable = true; + /// @brief Whether the user may filter the column. + bool filterable = true; + /// @brief Whether the column is shown by default. + bool shown = true; + /// @brief How the column's cells are shown. + ColumnDisplay display; + /// @brief The id of the `Text` column whose cell names this column's cell's tone (`neutral`, `info`, `ok`, + /// `warn`, `err`); empty for none. + std::string tone; + /// @brief The id of the `Text` column whose cell is this column's cell's tooltip; empty for none. + std::string tooltip; + /// @brief The action that edits the column's cells on a model's table; none leaves the column read-only. + std::optional edit; + + /// @brief Member-wise equality. + /// @param other The column to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(TableColumn const& other) const = default; +}; + +} // namespace morph::table + +/// @brief The JSON of `morph::table::TableColumn`: every member by its name, `display`, `tone`, `tooltip` and `edit` +/// left +/// out while they hold their defaults, so a column that shows its cells plainly costs nothing for them. A +/// reader restores a member left out to its default. +template <> +struct glz::meta { + /// @brief The column type. + using T = morph::table::TableColumn; + /// @brief Whether a member is left out. + /// @tparam V The member's type. + /// @param member The member. + /// @param key Its JSON name. + /// @param context Unused. + /// @return `true` for a default `display`, an empty `tone` or `tooltip`, and no `edit`. + template + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks this hook up by name. + static constexpr bool skip_if(V const& member, std::string_view key, glz::meta_context const& context) { + static_cast(context); + if constexpr (std::is_same_v) { + return key == "display" && member == morph::table::ColumnDisplay{}; + } else if constexpr (std::is_same_v) { + return (key == "tone" || key == "tooltip") && member.empty(); + } else if constexpr (std::is_same_v>) { + return !member.has_value(); + } else { + return false; + } + } + /// @brief Each member after its JSON name. + static constexpr auto value = + glz::object("info", &T::info, "label", &T::label, "group", &T::group, "sortable", &T::sortable, "filterable", + &T::filterable, "shown", &T::shown, "display", &T::display, "tone", &T::tone, "tooltip", + &T::tooltip, "edit", &T::edit); +}; + +// The JSON above names each member: a member added to `TableColumn` and not listed there would never reach the wire. +static_assert(glz::detail::count_members == 10, + "a TableColumn member is missing from glz::meta: list it there, then update " + "this count"); + +namespace morph::table { + +/// @brief What the server offers on a table beyond paging, sorting and filtering. +struct TableCapabilities { + /// @brief Keyed queries. + bool keys = true; + /// @brief Distinct values of a column. + bool distinct = true; + /// @brief Sort keys a query may hold. + std::uint32_t maxSortKeys = 8; + + /// @brief Member-wise equality. + /// @param other The capabilities to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(TableCapabilities const& other) const = default; +}; + +/// @brief Everything a client needs to draw a table, with no compile-time +/// knowledge of its rows. +struct TableDescription { + /// @brief The table's id, unique in the process across every model. + std::string id; + /// @brief The table's text. + std::string label; + /// @brief The columns, in the declared order. + std::vector columns; + /// @brief The id of the column that is the row's key. + std::string key; + /// @brief The declared column groups, as a client draws them: the source's `groups()`, which the server + /// evaluates. + std::vector groups; + /// @brief The header bands over the columns, outermost first (`checkBands` says what a band may be). + std::vector bands; + /// @brief Every data level a column names, the base level excluded. + std::vector levels; + /// @brief The units of the dimensions the table's `Measure` columns allow (`unitsFor`): the only place a client + /// learns units from, to parse, convert and show a measure. + std::vector units; + /// @brief What the server offers on the table. + TableCapabilities capabilities; + /// @brief The id of the `Text` column whose cell names a row's tone; empty for none. + std::string rowTone; + /// @brief The id of the `Text` column whose cell, when it holds text, locks the row and is its tooltip; empty + /// for none. + std::string rowLock; + /// @brief A hash of every other member, set by `describe`; a model leaves it empty. + std::string revision; + + /// @brief Member-wise equality. + /// @param other The description to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(TableDescription const& other) const = default; +}; + +/// @brief Stamps @p description with its revision. +/// +/// The revision is the 64-bit FNV-1a hash of the description's JSON as glaze +/// writes it, members in declaration order, with the revision itself empty: so +/// describing a described description gives the same revision, and any change +/// of a member a client reads gives another. +/// @param description The description; its `revision` is ignored. +/// @return The description with `revision` set to 16 lowercase hex digits. +[[nodiscard]] MORPH_API TableDescription describe(TableDescription description); + +/// @brief The columns of @p description as the engine reads them. +/// @param description The description. +/// @return Each column's `info`, in the description's order. +[[nodiscard]] MORPH_API std::vector columnInfos(TableDescription const& description); + +/// @brief A registry of the units @p description lists: how a client resolves the unit ids of its measures. +/// +/// The ratio's unit `""` is the builder's own and is skipped when listed; the numbers are this registry's, not the +/// server's, since the wire names a unit by its id. +/// @param description The description. +/// @return The registry, or what `UnitRegistryBuilder::add` refuses for a listed unit. +[[nodiscard]] MORPH_API std::expected, TableError> registryOf( + TableDescription const& description); + +/// @brief Refuses a column display or a companion that cannot apply to @p description. +/// +/// `decimals` or `unit` on a `Measure` column is refused, naming that column: a measure shows in its own unit, to +/// that unit's decimals. A `tone`, `tooltip`, `rowTone` or `rowLock` that names no column, or a column that is not +/// `Text`, is refused, naming the id it gives. +/// @param description The description. +/// @return Nothing, or `SourceContract` naming the offending column. +[[nodiscard]] MORPH_API std::expected validateDisplay(TableDescription const& description); + +/// @brief Refuses header bands a table cannot draw. +/// +/// A band nested past `kMaxBandLevels` levels, a band naming no column, a band naming a column id the table does not +/// have, a child band over a column its parent lacks, and a column in two bands of one level are each refused. +/// @param bands The bands, outermost first. +/// @param columns The table's columns. +/// @return Nothing, or `SourceContract` whose message names the band's label. +[[nodiscard]] MORPH_API std::expected checkBands(std::span bands, + std::span columns); + +/// @brief Which companions a document overrides with its own expressions. +struct CompanionOverrides { + /// @brief The column ids whose document part gives `tone`. + std::set> tone; + /// @brief The column ids whose document part gives `tooltip`. + std::set> tooltip; + /// @brief Whether the node gives `rowTone`. + bool rowTone = false; +}; + +/// @brief The columns a query fetches for @p columns: each with its companions, then the row's. +/// +/// For each id of @p columns in order: the id, then its `tone` companion unless @p overrides gives that column's +/// tone, then its `tooltip` companion likewise; then `rowTone` unless overridden; then `rowLock`, which travels with +/// every row since a locked row cannot be drawn without it. Empty names are skipped, and an id already listed is not +/// listed again. +/// @param description The description. +/// @param columns The column ids, in the order the query names them. +/// @param overrides What the document gives itself. +/// @return The ids. +[[nodiscard]] MORPH_API std::vector columnsWithCompanions(TableDescription const& description, + std::span columns, + CompanionOverrides const& overrides = {}); + +/// @brief Every column @p description names as a companion: columns no user arranges. +/// @param description The description. +/// @return Every non-empty `tone`, `tooltip`, `rowTone` and `rowLock` name, sorted, without duplicates. +[[nodiscard]] MORPH_API std::vector companionColumns(TableDescription const& description); + +/// @brief One row of a generic page: one cell per entry of the page's `columns`. +using GenericRow = std::vector; + +/// @brief A page of a table read through its description: row arrays under one +/// header of column ids. +/// +/// Its JSON members, in order: `revision`, `columns`, `keys`, `rows`, `total` +/// (absent when not counted), `totalKind`, `offset`, `unloadedRows`, +/// `undecided`, `awaiting`, `failed`, `indices` and `distinct`. An empty +/// `failed` or `indices` is left out, as is a row's empty `failed` in +/// `unloadedRows`, and `distinct` is written only on a distinct-values reply; +/// the reader takes each member from `unloadedRows` on as present or absent, so +/// a page without them is a fully loaded page that is not a keyed reply. +struct GenericPage { + /// @brief The revision of the description the page was written against. + std::string revision; + /// @brief The columns of each row, in the description's order. + std::vector columns; + /// @brief Each row's key, whether or not the key column is among `columns`. + std::vector keys; + /// @brief The rows, in view order. + std::vector rows; + /// @brief Rows in the whole filtered view, or a lower bound (see `totalKind`); + /// absent when the server did not count them. + std::optional total; + /// @brief Whether `total` is the count or a lower bound. + TotalKind totalKind = TotalKind::Exact; + /// @brief The view row of `rows[0]`. + std::int64_t offset = 0; + /// @brief The rows of this page that have unloaded levels, ascending by index. A row not listed is fully + /// loaded; a cell at a listed level is `null` on the wire. + std::vector unloadedRows; + /// @brief Rows the filter can neither admit nor reject until a level loads. They are in no page. + std::int64_t undecided = 0; + /// @brief The order levels with a load wanted or in flight for at least one row. + std::vector awaiting; + /// @brief The order levels whose load failed for at least one row, and is not being tried again yet. + std::vector failed; + /// @brief A keyed reply only: the view row of each of `rows`. + std::vector indices; + /// @brief A distinct-values reply only: the values; the page then has no rows. + std::optional distinct; + /// @brief The indices, into `rows`, of the retained rows (`TableQuery::retain`) the filter rejects, ascending. + /// Left out of the JSON when empty. + std::vector unmatched; + /// @brief The view's membership (`MembershipDigest::text`): two pages with the same one are of views of the same + /// rows, whatever their sort. Empty on a distinct-values reply, and then left out of the JSON. + std::string viewRevision; + /// @brief The id of each unit number the page's `Measure` cells hold, by which they are written: filled by + /// `writeGenericPage` and `readGenericPage`. Not a member of the JSON, where a measure names its unit's id. + std::map units; +}; + +namespace detail { + +/// @brief `10^k` for `k` in `[0, kMaxDecimalPlaces]`. +/// @param k The exponent, at most `math::kMaxDecimalPlaces`. +/// @return The power. +[[nodiscard]] constexpr std::int64_t powerOfTen(std::uint32_t k) noexcept { + std::int64_t out = 1; + for (std::uint32_t i = 0; i < k; ++i) { + out *= 10; + } + return out; +} + +/// @brief Appends an integer as JSON. +/// @param out The text to append to. +/// @param value The integer. +MORPH_API void appendInteger(std::string& out, std::int64_t value); + +/// @brief Appends a string as a JSON string, escaped as glaze escapes it. +/// @param out The text to append to. +/// @param text The string. +MORPH_API void appendJsonString(std::string& out, std::string_view text); + +/// @brief Appends a `Rational` as `[numerator, denominator]`. +/// +/// With `p` its decimal places, the pair is scaled to `[n × 10^p / d, 10^p]` +/// when `10^p` is a multiple of the denominator and the scaled numerator fits +/// `int64`, so a reader takes the places back from the denominator; otherwise +/// it is the canonical pair. +/// @param out The text to append to. +/// @param value The value. +MORPH_API void appendRational(std::string& out, math::Rational const& value); + +/// @brief Appends a finite or non-finite `double`. +/// +/// A finite value is written as glaze writes it, with `.0` added when that +/// text has no fraction or exponent, so it never reads back as an integer. A +/// non-finite one, which JSON cannot hold as a number, is the string `"nan"`, +/// `"inf"` or `"-inf"`. +/// @param out The text to append to. +/// @param value The value. +MORPH_API void appendDouble(std::string& out, double value); + +/// @brief Appends one cell as JSON, by its `Cell` alternative. +/// +/// Empty and unloaded are `null`; an integer, a string and a boolean are themselves; a +/// `double` is written by `appendDouble`; a `Rational` is a pair by +/// `appendRational`; a `QuantityCell` is `[n, d, [fn, fd]]`, its amount and +/// factor each written as a `Rational`, or the plain pair of its amount when +/// the factor is 1; a `Measure` is `[n, d, ""]`, its unit `null` when +/// @p units has no id for its number. +/// @param out The text to append to. +/// @param cell The cell. +/// @param units The id of each unit number a measure may hold. +MORPH_API void appendCellJson(std::string& out, Cell const& cell, std::map const& units = {}); + +/// @brief Reads JSON text token by token, for the shapes a cell has. +class MORPH_API CellCursor { +public: + /// @brief A cursor at the start of @p text. + /// @param text The JSON text. + explicit CellCursor(std::string_view text) noexcept : _text{text} {} + + /// @brief Skips JSON whitespace. + void skipSpace() noexcept; + + /// @brief Consumes @p character after any whitespace. + /// @param character The character expected. + /// @return `true` when it was next and is consumed. + [[nodiscard]] bool eat(char character) noexcept; + + /// @brief Whether only whitespace is left. + /// @return `true` at the end of the text. + [[nodiscard]] bool atEnd() noexcept; + + /// @brief The text not consumed yet, after any whitespace. + /// @return The rest of the text. + [[nodiscard]] std::string_view rest() noexcept; + + /// @brief Consumes a JSON integer token that fits `int64`. + /// @return The integer, or nothing (and nothing consumed) when the next + /// token is not one. + [[nodiscard]] std::optional integer() noexcept; + + /// @brief The JSON number token at the start of @p text. + /// @param text The text. + /// @return The token: `-?digits(.digits)?([eE][+-]?digits)?`, or empty when + /// @p text does not start with one. + [[nodiscard]] static std::string_view numberToken(std::string_view text) noexcept; + +private: + std::string_view _text; + std::size_t _at = 0; +}; + +/// @brief The decimal places a denominator implies. +/// @param denominator A positive denominator. +/// @return `k` when it is `10^k` with `k ≤ kMaxDecimalPlaces`, otherwise +/// `kMaxDecimalPlaces`. +[[nodiscard]] constexpr std::uint32_t placesOf(std::int64_t denominator) noexcept { + for (std::uint32_t k = 0; k <= math::kMaxDecimalPlaces; ++k) { + if (powerOfTen(k) == denominator) { + return k; + } + } + return math::kMaxDecimalPlaces; +} + +/// @brief Reads `n, d` of a pair whose `[` is consumed, and the `]` after it. +/// @param cursor The cursor. +/// @return The `Rational`, its places from the denominator, or nothing when +/// the pair is not two integers with a positive denominator. +[[nodiscard]] MORPH_API std::optional readPair(CellCursor& cursor); + +/// @brief Reads an exact cell: `[n, d]` or `[n, d, [fn, fd]]`. +/// @param text The JSON text, starting with `[`. +/// @return The `Rational` or `QuantityCell`, or nothing when the array has +/// another shape. +[[nodiscard]] MORPH_API std::optional readExactCell(std::string_view text); + +/// @brief Reads a measure's JSON: `[n, d, ""]`, or `[n, d, null]` for a unit its writer had no id for. +/// @param text The JSON text, starting with `[`. +/// @return The amount and the unit's id (nothing for `null`), or nothing when the array has another shape. +[[nodiscard]] MORPH_API std::optional>> readMeasureCell( + std::string_view text); + +/// @brief The `double` a `Number` column holds for the strings JSON writes +/// a non-finite value as. +/// @param text The decoded string. +/// @return NaN, +inf or -inf, or nothing for any other string. +[[nodiscard]] MORPH_API std::optional nonFinite(std::string_view text) noexcept; + +/// @brief Reads one cell from its JSON text, by the text's shape. +/// +/// `null` is empty. A number token with no `.`, `e` or `E` is an `int64`, +/// unless @p kind is `Number` or it does not fit, when it is a `double`; any +/// other number is a `double` whatever the kind, so a `double` held in an +/// integer or exact column stays invalid there. A string is text, except +/// `"nan"`, `"inf"` and `"-inf"` in a `Number` column. `true` and `false` are +/// booleans. `[n, d]` with `d > 0` is a `Rational` whose places are `k` when +/// `d` is `10^k` and `kMaxDecimalPlaces` otherwise; `[n, d, [fn, fd]]` is a +/// `QuantityCell`. Anything else is the text of its JSON, which no kind but +/// `Text` reads as valid. +/// @param json The cell's JSON text. +/// @param kind The column's kind, or nothing when it is not known. +/// @return The cell. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] MORPH_API Cell cellFromJson(std::string_view json, std::optional kind); + +/// @brief Reads a page's rows with no column kinds; `readGenericPage` reads +/// them again with their columns' kinds. +/// @param page The page to fill. +/// @param rows Each row's cells as JSON text. +MORPH_API void readPageRows(GenericPage& page, std::vector> const& rows); + +/// @brief Writes a page's rows, each cell by `appendCellJson`. +/// @param page The page. +/// @return The `rows` array as JSON. +[[nodiscard]] MORPH_API glz::raw_json writePageRows(GenericPage const& page); + +} // namespace detail + +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + +} // namespace morph::table + +/// @brief The JSON of `morph::table::GenericPage`: its members in declaration +/// order, `rows` written and read cell by cell. +template <> +struct glz::meta { + /// @brief The page type. + using T = morph::table::GenericPage; + /// @brief Whether a member is left out of the JSON written. + /// @tparam V The member's type. + /// @param member The member. + /// @param key Its JSON name. + /// @param context Unused. + /// @return `true` for an empty `failed`, `indices`, `unmatched` or `viewRevision`. + template + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks this hook up by name. + static constexpr bool skip_if(V const& member, std::string_view key, glz::meta_context const& context) { + static_cast(context); + return morph::table::detail::omittedPageMember(member, key); + } + /// @brief Each member after its JSON name. + static constexpr auto value = glz::object( + "revision", &T::revision, "columns", &T::columns, "keys", &T::keys, "rows", + glz::custom<[](T& page, std::vector> const& rows) { + morph::table::detail::readPageRows(page, rows); + }, + [](T const& page) { return morph::table::detail::writePageRows(page); }>, + "total", &T::total, "totalKind", &T::totalKind, "offset", &T::offset, "unloadedRows", &T::unloadedRows, + "undecided", &T::undecided, "awaiting", &T::awaiting, "failed", &T::failed, "indices", &T::indices, "distinct", + &T::distinct, "unmatched", &T::unmatched, "viewRevision", &T::viewRevision); +}; + +namespace morph::table { + +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- cell and column indices are bounded by the page's own counts, checked before they are used + +/// @brief Builds the generic page of @p page's rows. +/// +/// Reads only the cells of @p columns, for the page's rows only, so a source +/// may produce every other cell lazily or not at all. A row is listed in +/// `unloadedRows` with the levels of the named columns whose cell it holds as +/// `Unloaded`, sorted; a level no named column has is not looked up. Every +/// member of @p page beyond its rows is copied but `distinct`: a distinct-values +/// reply is built by `detail::answerQuery`, not from a page of rows. A measure +/// is written with its unit's id from @p units; a unit @p units does not hold +/// is written `null`, which reads back as an invalid cell. +/// @param page The page's source rows and the view's state, as `apply` returns them. +/// @param source The rows; read through one snapshot. +/// @param columns The column ids to write, already ordered and without +/// duplicates (`validate` makes a query's list so). An id the +/// source lacks is written as empty cells. +/// @param units The registry the source's measures are numbered in. Not null when a written column is `Measure`: +/// a precondition, which `detail::answerQuery` checks before it calls this. +/// @return The page, its `revision` left empty for the caller to set. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] MORPH_API GenericPage writeGenericPage(PageRows const& page, DataSource const& source, + std::span columns, + UnitRegistry const* units = nullptr); + +/// @brief Reads a generic page against its table's description. +/// +/// Each cell is read by `detail::cellFromJson` with its column's kind. A cell +/// that does not read as its kind keeps the page and is an invalid cell; a +/// page whose structure is wrong is refused. A cell of a `Measure` column +/// written `[n, d, ""]` is a `Measure` whose unit is the id's number +/// in @p units, or `kUnknownUnit`, an invalid cell, for an id it lacks. +/// @param json The page's JSON. +/// @param description The table's description. +/// @param units The registry a measure's unit id is resolved through. Null resolves through +/// `registryOf(description)`, built once for the call and only when a column of the page is +/// `Measure`: a client has no registry of its own, only the description's units. +/// @return The page, or `UnknownColumn` naming a `columns` entry the +/// description lacks, or `InvalidValue` when the text is not a page, a +/// row's length differs from `columns`, `keys` and `rows` differ in +/// length, an `unloadedRows` index is outside the rows or not above the +/// one before it, `indices` is neither empty nor one non-negative +/// view row per row, or what `registryOf` refuses. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] MORPH_API std::expected readGenericPage(std::string_view json, + TableDescription const& description, + UnitRegistry const* units = nullptr); + +namespace detail { + +/// @brief The cells of one page of a generic window, by column, so a column can be added or dropped without +/// touching the others. +struct MORPH_API GenericWindowCells { + /// @brief Each held column's cells, one per row. + std::map, std::less<>> cells; + + /// @brief Whether the page holds a column. + /// @param column The column's id. + /// @return `true` when held. + [[nodiscard]] bool holds(std::string_view column) const { return cells.contains(column); } + /// @brief The columns held, which a rest-of-page fetch names. + /// @return The ids, sorted. + [[nodiscard]] std::vector columns() const; + /// @brief Keeps the first @p count rows of every column. + /// @param count Rows kept. + void truncate(std::size_t count); +}; + +} // namespace detail + +/// @brief The window of every `table` node: generic pages, a row's key its entry of the page's `keys`, and the +/// columns of each page held by column. +/// +/// The rules are `PageWindow`'s. In addition `visible` names the columns shown: a page held complete that +/// lacks some of them is fetched again for the same rows naming only those, and the reply's cells are added +/// when its keys are the page's, row for row. A page holds at most `maxColumns` columns; over that, the columns +/// least recently named by `visible` go first. A patch drops from a page the columns its reply lacks, so the +/// next `visible` fetches them again rather than showing a cell older than its row. +template <> +class MORPH_API PageWindow : public detail::WindowCore { + using Core = detail::WindowCore; + +public: + /// @brief An empty window. + /// @param pageSize Rows per page (default 200). + /// @param maxPages Pages held at most; the farthest from the visible rows go first. + /// @param maxKeys Keys one keyed fetch asks for at most; more refetch the pages instead. + /// @param maxColumns Columns a page holds at most. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) - sizes and bounds, each documented above + explicit PageWindow(std::int64_t pageSize = 200, std::size_t maxPages = 8, std::size_t maxKeys = 1000, + std::size_t maxColumns = 96) + : Core{pageSize, maxPages, true, maxKeys, maxColumns} {} + + /// @brief Declares the visible rows and the columns shown; returns the fetches to send. + /// @param first First visible view row. + /// @param count Visible rows. + /// @param columns The columns shown, in order; empty asks for every column. + /// @return The fetches to send, each now in flight. + [[nodiscard]] std::vector visible(std::int64_t first, std::int64_t count, + std::span columns = {}) { + return visibleColumns(first, count, columns); + } + + /// @brief Stores a page reply. + /// @param fetch The fetch the reply answers, as `visible` returned it. + /// @param page The page the server returned. + /// @return `false` when the reply was ignored: its fetch belongs to an earlier query, or is not the one in + /// flight for its page. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + bool accept(PageFetch const& fetch, GenericPage page); + + /// @brief Patches held rows from the reply to a `RowsFetch`. + /// @param fetch The keyed fetch the reply answers, as `refresh` or `owed` returned it. + /// @param reply The keyed reply. + /// @return The view rows replaced, ascending; empty when the reply was ignored or the window invalidated. + std::vector patch(RowsFetch const& fetch, GenericPage reply); + + /// @brief The key of the held row at a view row. + /// @param index View row. + /// @return The key, or null when the row is not held. + [[nodiscard]] RowId const* key(std::int64_t index) const; + + /// @brief The cell of a held row in a column. + /// @param index View row. + /// @param column The column's id. + /// @return The cell, or null when the row or the column is not held. + [[nodiscard]] Cell const* cell(std::int64_t index, std::string_view column) const; + + /// @brief Whether a held row's column is held. + /// @param index View row. + /// @param column The column's id. + /// @return `true` when `cell(index, column)` is not null. + [[nodiscard]] bool holds(std::int64_t index, std::string_view column) const { + return cell(index, column) != nullptr; + } + +private: + [[nodiscard]] static detail::WindowReply replyOf(GenericPage const& page); + + // Over the bound, the columns least recently named by `visible` go first, and a column shown now never goes: + // dropping one would make the next `visible` fetch it again, and the next accept drop it again. `visible` + // takes at most `maxColumns` columns, so the columns not shown always cover the excess. + void limitColumns(detail::GenericWindowCells& content) const; +}; + +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + +} // namespace morph::table + +// ── A model's tables ─────────────────────────────────────────────────────── + +namespace morph::table { + +/// @brief Who asks for a table: what a table's function reads to decide what it serves. +struct TableContext { + /// @brief The caller's session; an empty one outside a dispatch. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members): a read-only view of the dispatching session, valid for the dispatch it is built in; never reseated or assigned. + session::Context const& session; +}; + +/// @brief What a model's table function returns: everything the framework needs to answer a query. +/// +/// The function runs per request on the model's strand and returns shared, immutable things; the framework +/// pins the source's snapshot there and builds the reply off the strand. +struct ServedTable { + /// @brief The table as this caller sees it; its `revision` is set by the framework. + TableDescription description; + /// @brief The rows the caller may see, held in memory or read lazily: `apply` runs over it. + std::shared_ptr source; + /// @brief The slow levels, one per level the description names. + std::vector> levels; + /// @brief Whether the caller may read a column; empty allows every column of the description. + std::function mayRead; + /// @brief Names everything about the caller that changes the view beyond the query: the row scope and the + /// collation. Empty when every caller sees the same rows in the same order. + std::string scope; + /// @brief The collator, date parser, comparators and progress sink this caller's order uses. + Services services; + /// @brief The bounds a query to this table is held to. + QueryLimits limits; +}; + +/// @brief The most sort keys a table's `limits` may allow. +inline constexpr std::size_t kMaxSortKeysBound = 32; + +/// @brief The description a served table answers with: its sort bound from `limits` and its units, then its +/// revision. +/// +/// The bound is set before `describe` takes the revision, because `capabilities` is part of what it hashes: a +/// table whose limits raise the bound has another revision than the same table at the default. Every reply that +/// names the table's revision, a page included, takes it from here, so a page and the describe reply agree. +/// +/// A table with a `Measure` column lists its units (`TableDescription::units`) from `services.units` by `unitsFor` +/// when its function left them empty, also before the revision is taken, so a client learns them from the +/// description and from every page's revision alike. +/// @param served The table as its function returned it. +/// @return The description, its `capabilities.maxSortKeys` the limits', its units listed and its revision set; +/// `SourceContract` when `limits.maxSortKeys` is 0 or above `kMaxSortKeysBound`, or when a column is +/// `Measure` and `services.units` is null. +[[nodiscard]] MORPH_API std::expected servedDescription(ServedTable const& served); + +/// @brief One row of a table that an action changed. +struct ChangedRow { + /// @brief The row's key. + RowId key; + /// @brief The key the row had before the action gave it `key`, when the action changed it: saving a modified row + /// as a new one. The result walk collects it beside `key`, so the change event names both. + std::optional from; + + /// @brief Member-wise equality. + /// @param other The row to compare with. + /// @return `true` when the keys and the previous keys match. + [[nodiscard]] bool operator==(ChangedRow const& other) const = default; +}; + +/// @brief One row of a table an action could not change, and why. +struct FailedRow { + /// @brief The row's key. + RowId key; + /// @brief What the action says went wrong, for the person who ran it. + std::string message; + + /// @brief Member-wise equality. + /// @param other The row to compare with. + /// @return `true` when key and message match. + [[nodiscard]] bool operator==(FailedRow const& other) const = default; +}; + +/// @brief What `BRIDGE_REGISTER_TABLE` declares about a table, by its function. +/// +/// The primary template is no table; the registration specialises it with `model`, `row` (`void` for a table +/// whose function returns a `ServedTable`, the row type for a `typed` one), `registered`, `id` and `serve`. +/// @tparam Function The table's function. +template +struct TableTraits { + /// @brief `false`: no registration names @p Function. + static constexpr bool registered = false; +}; + +/// @brief A table's record type: a tag made from the table's function, distinct for each table. +/// +/// Named by `updatesTable`, `changesTable`, `ChangedRows` and the record registry. A function no registration +/// names does not compile as a table. +/// @tparam Function The table's function. +template +struct TableOf { + static_assert(TableTraits::registered, + "not a registered table: BRIDGE_REGISTER_TABLE must name this function before it is used"); +}; + +/// @brief The rows of one table that an action changed: the slot an `updatesTable` effect reads. +/// +/// Its JSON is `{"rows": [{"key": …, "from": …}, …], "failed": [{"key": …, "message": …}, …]}`. The result walk +/// reports `TableOf` at its `rows` member, keyed by `key` and by `from`, so an action's changed rows are +/// collected as any record's are; a `failed` row is not changed, and is not collected. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` names it. +template +struct ChangedRows { + /// @brief The rows changed, in any order. + std::vector rows; + /// @brief The rows the action could not change, each with why. + std::vector failed; + + /// @brief The record the rows belong to. + using heldRecord = TableOf; + + /// @brief The member that holds the record's rows. + /// @return `"rows"`. + [[nodiscard]] static constexpr std::string_view heldMember() noexcept { return "rows"; } +}; + +/// @brief A table function that returns typed rows, as `typed` registers it. +/// @tparam Row The row type: a glaze-reflectable aggregate registered as a record. +/// @tparam Fn The function's type: `std::shared_ptr const> (Model::*)(TableContext const&)`. +template +struct Typed { + /// @brief The model's function. + Fn function; +}; + +/// @brief Registers a table from typed rows: its description is built from @p Row and its rows are served +/// through a `RowsSource`. +/// @tparam Row The row type: a glaze-reflectable aggregate registered as a record, whose key is the table's. +/// @tparam Fn The function's type, deduced. +/// @param function The model's function returning the rows the caller may see. +/// @return The registration's function, for `BRIDGE_REGISTER_TABLE`. +template +[[nodiscard]] constexpr Typed typed(Fn function) noexcept { + static_assert(std::is_member_function_pointer_v, "table::typed: the function is a member of the model"); + return Typed{function}; +} + +/// @brief Registration option: callers see different rows, so the table's record keeps its keys private. +// NOLINTNEXTLINE(readability-identifier-naming): a registration option, spelled in lower case like the registration call it is passed to. +struct rowScoped {}; + +/// @brief Registration option: a change of any of @p Records is a change of the table's record. +/// @tparam Records Registered record types. +template +// NOLINTNEXTLINE(readability-identifier-naming): a registration option, spelled in lower case like the registration call it is passed to. +struct derivedFrom {}; + +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- row indices are bounded by the snapshot's own counts + +namespace detail { + +/// @brief A source holding one snapshot: what a reply is built from off the owner's thread. +/// +/// A `DataSource` is owner-affine and only its snapshot may cross threads, so the snapshot is taken on the +/// owner's thread and this source carries it, with a copy of the columns and the groups. It never changes. +class MORPH_API PinnedSource final : public DataSource { +public: + /// @brief Holds @p snapshot under @p columns and @p groups. + /// @param snapshot The rows. + /// @param columns The source's columns when the snapshot was taken. + /// @param groups The source's declared groups when the snapshot was taken. + PinnedSource(std::shared_ptr snapshot, std::vector columns, + std::vector groups = {}) + : _snapshot{std::move(snapshot)}, + _columns{std::move(columns)}, + _groups{std::move(groups)}, + _pinnedAt{nextPin()} {} + + PinnedSource(PinnedSource const&) = delete; + PinnedSource& operator=(PinnedSource const&) = delete; + PinnedSource(PinnedSource&&) = delete; + PinnedSource& operator=(PinnedSource&&) = delete; + ~PinnedSource() override = default; + + /// @brief When the snapshot was pinned, among every pin of the process: larger for later. + /// @return The pin's sequence number. + [[nodiscard]] std::uint64_t pinnedAt() const noexcept { return _pinnedAt; } + + /// @brief The columns. + /// @return The copy taken with the snapshot. + [[nodiscard]] std::span columns() const override { return _columns; } + + /// @brief The declared groups. + /// @return The copy taken with the snapshot. + [[nodiscard]] std::span groups() const override { return _groups; } + + /// @brief The one snapshot. + /// @return The snapshot. + [[nodiscard]] std::shared_ptr snapshot() const override { return _snapshot; } + + /// @brief Does nothing: the source never changes. + /// @param listener Ignored. + void subscribe(ChangeListener& listener) override { static_cast(listener); } + + /// @brief Does nothing: the source never changes. + /// @param listener Ignored. + void unsubscribe(ChangeListener& listener) override { static_cast(listener); } + +private: + [[nodiscard]] MORPH_PROCESS_UNIQUE static std::uint64_t nextPin() noexcept; + + std::shared_ptr _snapshot; + std::vector _columns; + std::vector _groups; + std::uint64_t _pinnedAt; +}; + +/// @brief The rows of a shared snapshot whose keys a scope holds, in the shared snapshot's order. +class ScopedSnapshot final : public RowSnapshot { +public: + /// @brief Maps @p rows onto @p base. + /// @param base The shared rows. + /// @param rows The rows of @p base in the scope, in order. + ScopedSnapshot(std::shared_ptr base, std::vector rows) + : _base{std::move(base)}, _rows{std::move(rows)} {} + + /// @brief The rows in the scope. + /// @return Row count. + [[nodiscard]] std::size_t rowCount() const override { return _rows.size(); } + + /// @brief A row's key. + /// @param row Row index in the scope. + /// @return The shared row's key. + [[nodiscard]] RowId rowId(std::size_t row) const override { return _base->rowId(_rows[row]); } + + /// @brief One cell, read from the shared row. + /// @param row Row index in the scope. + /// @param column Column index. + /// @return The cell. + [[nodiscard]] Cell cell(std::size_t row, std::size_t column) const override { + return _base->cell(_rows[row], column); + } + +private: + std::shared_ptr _base; + std::vector _rows; +}; + +/// @brief A scope's view of a shared source: the rows whose key the scope holds, sharing every cell. +/// +/// Its row map is rebuilt, under a mutex, on the first `snapshot()` after the shared source's snapshot +/// changed. It notifies no change of its own: a reader sees the shared source's changes on its next snapshot. +class MORPH_API ScopedSource final : public DataSource { +public: + /// @brief Scopes @p source to @p keys. + /// @param source The shared source. + /// @param keys The keys of the scope's rows; a key the source lacks is skipped. + ScopedSource(std::shared_ptr source, std::vector keys) + : _source{std::move(source)}, + _keys(std::make_move_iterator(keys.begin()), std::make_move_iterator(keys.end())) {} + + /// @brief The shared source's columns. + /// @return The columns. + [[nodiscard]] std::span columns() const override { return _source->columns(); } + + /// @brief The shared source's declared groups. + /// @return The groups. + [[nodiscard]] std::span groups() const override { return _source->groups(); } + + /// @brief The scope's rows of the shared source's current snapshot. + /// @return The snapshot. + [[nodiscard]] std::shared_ptr snapshot() const override; + + /// @brief Does nothing: the scope notifies no change of its own. + /// @param listener Ignored. + void subscribe(ChangeListener& listener) override { static_cast(listener); } + + /// @brief Does nothing: the scope notifies no change of its own. + /// @param listener Ignored. + void unsubscribe(ChangeListener& listener) override { static_cast(listener); } + +private: + std::shared_ptr _source; + std::set _keys; + mutable std::mutex _mutex; + mutable std::shared_ptr _base; + mutable std::shared_ptr _scoped; +}; + +} // namespace detail + +/// @brief A source of the rows of @p source whose key is in @p keys, without copying a cell. +/// +/// What a model with row scopes keeps per scope: built when the scope is first asked for and shared from then +/// on. Its rows keep the shared source's order; keys the source lacks are skipped. A change of the shared +/// source is seen by the next `snapshot()`. +/// @param source The shared source. +/// @param keys The scope's row keys. +/// @return The scoped source. +[[nodiscard]] inline std::shared_ptr scoped(std::shared_ptr source, + std::vector keys) { + return std::make_shared(std::move(source), std::move(keys)); +} + +namespace detail { + +/// @brief What a reply is built with beyond the table and the query. +struct AnswerContext { + /// @brief The server's view cache; null computes the view for the request alone. + ViewCache* views = nullptr; + /// @brief The table's record name, `.`: the first member of a view's key. Empty caches nothing. + std::string_view record; + /// @brief The registration's `rowScoped`: a reply then needs a `ServedTable::scope`. + bool rowScoped = false; +}; + +/// @brief The canonical text of a validated query's sort and filter: the part of a view's key the query gives. +/// @param validated The query as `validate` returned it. +/// @return The JSON of `sort`, then of `filters`; nothing when either cannot be written, and the view is then +/// computed for the request alone rather than cached under a key two queries could share. +[[nodiscard]] MORPH_API std::optional viewQueryOf(TableQuery const& validated); + +/// @brief @p served with its source replaced by a `PinnedSource` of one snapshot taken now. +/// +/// Called on the source's owner thread, the model's strand, before the reply is built anywhere else. +/// @param served The table as the model served it. +/// @return The same table over a pinned source; a null source stays null. +[[nodiscard]] MORPH_API ServedTable pinned(ServedTable served); + +/// @brief A sorted, filtered or listed column of @p level: the column a refused order use names. +/// @param query The validated query. +/// @param columns The table's columns. +/// @param level The level. +/// @param services The services the filter compiles with. +/// @param groups The table's declared groups. +/// @return The first sort key's column at @p level, else the first filtered column at it, else the first column a +/// `distinct` request lists at it; empty when none is. +[[nodiscard]] MORPH_API std::string orderColumnOf(TableQuery const& query, std::span columns, + std::string_view level, Services const& services, + std::span groups = {}); + +/// @brief Answers @p query over a served table: the page a `Table.` action returns. +/// +/// The query is validated against the description's columns, its limits and `mayRead`; the page's columns +/// are the validated `columns`, or, absent, every description column `mayRead` allows, in the description's +/// order. Every base-level description column must be one of the source's, and every column of a level that +/// `served.levels` serves one of that level's columns, or nothing is read. +/// +/// The levels the query needs (`levelsNeeded`) are read from one snapshot of each, taken at the start, through a +/// `LeveledSource` over the pinned source: a level cell no snapshot holds is `Unloaded`, and a level no entry of +/// `served.levels` serves is `Unloaded` in every row. `unloadedRows` names each row of the page with the needed +/// levels its snapshot does not hold, `failed` those whose load failed; `awaiting` and `failed` name the order +/// levels unloaded, or failed, for some row of the view or of the undecided rows. Then each level is told what +/// the reply needed, with `query.retry`: an order level every row of the view and the undecided rows, a display +/// level the page's rows. An order use the level refuses refuses the query, `Unavailable` naming a sorted or +/// filtered column of the level, and no page is returned. +/// +/// The view comes from `context.views` when it is set and `context.record` is not empty: the entry of the +/// record, `served.scope` and the canonical sort and filter that is valid for the pinned source's snapshot and +/// the order levels' generations, computed once and read by every page and keyed fetch of it. A row-scoped table +/// (`context.rowScoped`) whose `scope` is empty is refused `SourceContract` before anything is read: its callers +/// would share views of different rows. +/// +/// A keyed query to a table whose capabilities exclude keyed queries is `Unavailable`, which a client answers by +/// refetching its pages. +/// +/// A query with `distinct` set is answered by `distinctValues` over a `LeveledSource` of the levels the request +/// needs (its listed column's level is an order level), each level then wanted as `Order` for every row, with +/// `query.retry`: a page with no columns, keys or rows and `distinct` set; `Unavailable` when the table's +/// capabilities exclude distinct requests, or when a level refuses the order use. +/// A group filter's or a distinct request's `group` resolves through the source's declared groups, which are +/// checked first (`detail::checkGroups`). +/// @param served The table, its source pinned (`pinned`). +/// @param query The query, as received. +/// @param context What the reply is built with. +/// @return The page, its `revision` that of `servedDescription(served)`, or the error the client shows: +/// `SourceContract` when the table's `limits.maxSortKeys` is out of range. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] MORPH_API std::expected answerQuery(ServedTable const& served, + TableQuery const& query, + AnswerContext const& context = {}); + +/// @brief The name a `TableErrorCode` has on the wire. +/// @param code The code. +/// @return Its JSON name, as `unknownColumn`, without quotes. +[[nodiscard]] MORPH_API std::string errorCodeName(TableErrorCode code); + +/// @brief The refusal a table's action throws for @p error. +/// @param error The error. +/// @return `ActionRefusal{"table." + code, {{"column", column}}, message}`. +[[nodiscard]] MORPH_API model::ActionRefusal refusalOf(TableError const& error); + +/// @brief The caller's `TableContext`: the session installed on the calling thread, or an empty one. +/// @return The context, valid while the session stays installed. +[[nodiscard]] MORPH_API TableContext callerContext(); + +/// @brief The row type of a registration's function: `void` for one returning a `ServedTable`. +/// @tparam F The registration's function type. +template +struct TableRowOf { + /// @brief `void`: the function returns a `ServedTable`. + using type = void; +}; + +/// @brief The row type of a `typed(…)` registration. +/// @tparam Row The row type. +/// @tparam Fn The function's type. +template +struct TableRowOf> { + /// @brief The row type. + using type = Row; +}; + +/// @brief The row type of a registration's function. +/// @tparam F The registration's function type, as `decltype` gives it. +template +using TableRow = TableRowOf>::type; + +/// @brief The member function a registration keys its table on. +/// @tparam F The registration's function type. +/// @param function A member function pointer, or a `typed(…)` registration. +/// @return The member function pointer. +template +[[nodiscard]] constexpr auto tableKey(F function) noexcept { + if constexpr (std::is_void_v>) { + return function; + } else { + return function.function; + } +} + +/// @brief The record option a table registration option stands for. +/// @tparam O A table registration option. +template +struct RecordOptionOf { + static_assert(sizeof(O) == 0, "BRIDGE_REGISTER_TABLE: an option is table::rowScoped or table::derivedFrom<...>"); +}; + +/// @brief `rowScoped` is the record's `privateKeys`. +template <> +struct RecordOptionOf { + /// @brief The record option. + using type = record::privateKeys; +}; + +/// @brief `derivedFrom` is the record's. +/// @tparam Records The source records. +template +struct RecordOptionOf> { + /// @brief The record option. + using type = record::derivedFrom; +}; + +/// @brief Static-init helper for `BRIDGE_REGISTER_TABLE`: registers the table's record. +/// @tparam Key The table's function. +/// @tparam Options The registration's options. +/// @param name The record's wire name, `.`. +/// @return Always true, so the result can initialise a namespace-scope variable. +template +inline bool registerTableRecord(std::string const& name) noexcept { + return record::detail::registerTableRecordOnce, typename RecordOptionOf::type...>(name); +} + +/// @brief The key of a typed row, read from its member named @p keyField. +/// @tparam Row The row type. +/// @param keyField The key member's JSON name. +/// @return The projection, or nothing when @p Row has no such member. +template +[[nodiscard]] std::optional> rowKeyNamed(std::string_view keyField) { + auto const readers = cellReaders(); + for (std::size_t index = 0; index < readers.size(); ++index) { + if (glz::reflect::keys[index] == keyField) { + return RowKey{[reader = readers[index]](Row const& row) -> RowId { + auto cell = reader(row, nullptr); + if (auto* const text = std::get_if(&cell)) { + return RowId{std::move(*text)}; + } + if (auto const* const integer = std::get_if(&cell)) { + return RowId{*integer}; + } + return RowId{std::int64_t{0}}; + }}; + } + } + return std::nullopt; +} + +/// @brief The table a `typed` registration serves: a description built from @p Row and its rows through a +/// `RowsSource`. +/// +/// The columns are `Row`'s reflected members in member order, each labelled by its field metadata or else by +/// its name made a title, each with the level `Row::columnLevels()` gives it; `levels` lists those levels, sorted +/// and each once. The groups are the source's (`Row::columnGroups()`), each labelled by its id made a title, and +/// each column names the group it is in. The key is the key member of the record registered for `Row`. @p units +/// resolves the rows' `MeasureValue` unit ids and is the table's `services.units`. +/// @tparam Row The row type. +/// @param tableId The table's id. +/// @param rows The rows the caller may see; null serves none. +/// @param units The model's unit registry (`tableUnits`); null when the model declares none. +/// @return The served table. +/// @throws std::logic_error when `Row` is not a registered record with a key. +/// @throws std::invalid_argument when `Row::columnLevels()` names no column. +template +[[nodiscard]] ServedTable typedTable(std::string_view tableId, std::shared_ptr const> rows, + std::shared_ptr units = nullptr) { + auto const& records = effects::detail::resolved().records; + auto const record = std::ranges::find(records, std::type_index{typeid(Row)}, &record::RecordInfo::type); + if (record == records.end() || !record->keyField) { + throw std::logic_error{"table " + std::string{tableId} + + ": its row type is not a registered record with a key"}; + } + auto key = rowKeyNamed(*record->keyField); + if (!key) { + throw std::logic_error{"table " + std::string{tableId} + ": its row type has no member " + *record->keyField}; + } + ServedTable served; + served.description.id = std::string{tableId}; + served.description.label = forms::detail::inferTitle(tableId); + served.description.key = *record->keyField; + for (auto& info : reflectedColumns()) { + auto const* const meta = forms::detail::findFieldMeta(info.id); + std::string label = + meta != nullptr && !meta->label.empty() ? std::string{meta->label} : forms::detail::inferTitle(info.id); + if (!info.level.empty()) { + served.description.levels.push_back(info.level); + } + served.description.columns.push_back( + TableColumn{.info = std::move(info), .label = std::move(label), .group = {}}); + } + std::ranges::sort(served.description.levels); + auto const [firstDuplicate, lastDuplicate] = std::ranges::unique(served.description.levels); + served.description.levels.erase(firstDuplicate, lastDuplicate); + if (rows == nullptr) { + rows = std::make_shared const>(); + } + auto source = std::make_shared const>( + std::move(rows), std::move(*key), std::map>{}, + std::map>{}, LevelLoaded{}, units); + served.services.units = std::move(units); + for (auto group : source->groups()) { + group.label = forms::detail::inferTitle(group.id); + for (auto& column : served.description.columns) { + if (std::ranges::find(group.columns, column.info.id) != group.columns.end()) { + column.group = group.id; + } + } + served.description.groups.push_back(std::move(group)); + } + served.source = std::move(source); + return served; +} + +/// @brief A table's `ServedTable`, from its model: the one way to it. +/// +/// Calls the registered function on @p model, on the model's strand, with @p context; for a `typed` table +/// it builds the description and the source from the rows, and a model that declares +/// `std::shared_ptr tableUnits(table::TableContext const&)` has it called there too, +/// its registry resolving the rows' measures. The description is stamped with its revision. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` keys it. +/// @tparam Model The model type. +/// @param model The model instance. +/// @param context Who asks. +/// @return The served table, its source live. +template +[[nodiscard]] ServedTable serve(Model& model, TableContext const& context) { + using Traits = TableTraits; + static_assert(Traits::registered, "not a registered table"); + ServedTable served; + if constexpr (std::is_void_v) { + served = (model.*Function)(context); + } else { + std::shared_ptr units; + if constexpr (requires { + { model.tableUnits(context) } -> std::convertible_to>; + }) { + units = model.tableUnits(context); + } + served = typedTable(Traits::id, (model.*Function)(context), std::move(units)); + } + served.description = describe(std::move(served.description)); + return served; +} + +/// @brief A table's record: its name and whether it keeps its keys private. +/// @tparam Function The table's function. +/// @return The registered record's name, valid for the process, and its `privateKeys`; empty and false when the +/// registries hold no such record. +template +[[nodiscard]] std::pair tableRecordOf() { + auto const& records = effects::detail::resolved().records; + auto const found = + std::ranges::find(records, std::type_index{typeid(TableOf)}, &record::RecordInfo::type); + if (found == records.end()) { + return {std::string_view{}, false}; + } + return {std::string_view{found->name}, found->privateKeys}; +} + +/// @brief The awaiter that builds a reply on the table executor and resumes the awaiting coroutine where it +/// was running. +/// +/// The work item owns the pinned table and the query. The coroutine resumes through the executor it was +/// running on when it suspended, its strand, or inline on the worker when it was running on none. +class MORPH_API AnswerAwaiter { + struct Shared { + std::expected answer; + std::exception_ptr error; + std::coroutine_handle<> continuation; + ::core::async::ResumeTarget context; + }; + +public: + /// @brief An answer of @p query over @p served, to run on @p work. + /// @param work The table executor; must outlive the work item. + /// @param served The table, its source pinned. + /// @param query The query. + /// @param context What the reply is built with. + AnswerAwaiter(exec::IExecutor& work MORPH_LIFETIMEBOUND, ServedTable served, TableQuery query, + AnswerContext context) + : _work{&work}, + _served{std::move(served)}, + _query{std::move(query)}, + _context{context}, + _shared{std::make_shared()} {} + + /// @return Always false: the answer is built elsewhere. + // Called through the awaiter by the compiler, so not static. + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) + [[nodiscard]] constexpr bool await_ready() const noexcept { return false; } + + /// @brief Posts the answer to the table executor. + /// @param awaiting The coroutine performing the `co_await`. + void await_suspend(std::coroutine_handle<> awaiting); + + /// @brief The answer, or what building it threw. + /// @return The answer. + std::expected await_resume(); + +private: + exec::IExecutor* _work; + ServedTable _served; + TableQuery _query; + AnswerContext _context; + std::shared_ptr _shared; +}; + +} // namespace detail + +/// @brief The action `Table.`: a page of a table, read by a `TableQuery`. +/// +/// Its JSON is the `TableQuery`'s. It runs on the model's strand: the table's function is called with the +/// caller's session and the source's snapshot is pinned there; the page is then built on the server's table +/// executor (`ServerConfig::tableWork`) and the coroutine resumes on the strand with it. With no table executor +/// installed, as on a `LocalBackend`, the page is built on the strand. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` keys it. +template +struct QueryTable { + /// @brief The query. + TableQuery query; + + /// @brief Answers the query. + /// @tparam Model The model type. + /// @param model The model instance. + /// @param action The action. + /// @return The page. + /// @throws morph::model::ActionRefusal `table.` with the argument `column`, for a query the table + /// refuses. + template + static ::core::async::Task invoke(Model& model, QueryTable& action); +}; + +/// @brief Checks every editable column of a description against its edit action's input: the field it edits must +/// exist and be of a kind the column's kind is edited with. Defined in `table/edits.hpp`, which this header +/// includes at its end. +/// +/// A column's field is the `value` member of a `CellEdit` action (an `EditInfo` with no `member`), or the named member +/// of a `RowEdit` action's `values`. The fits are `Integer` with an integer, slider, enum or choice field; `Key` with +/// an integer or choice; `Decimal` with a decimal; `Quantity` and `Measure` with a quantity; `Number` with a number or +/// slider; `Text` with a text, multiline, enum or choice; `Date` with a date or epoch date; `DateTime` with a +/// date-time or epoch date-time; `Bool` with a Boolean; `Custom` with a text, enum or choice. +/// @param description The description. +/// @param schemaOf An action's input schema by its id; nothing for an action that is not known. +/// @return `SourceContract` naming the first column whose action is unknown or does not read, whose field is missing, +/// or whose field's kind does not fit the column's; nothing when every edit fits. +[[nodiscard]] MORPH_API std::expected checkEdits( + TableDescription const& description, + std::function(std::string_view action)> const& schemaOf); + +/// @brief The action `Table..describe`: the table's description as the caller sees it. +/// +/// It runs on the model's strand and reads neither the source nor a snapshot. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` keys it. +template +struct DescribeTable { + /// @brief Describes the table. + /// @tparam Model The model type. + /// @param model The model instance. + /// @param action The action. + /// @return `servedDescription` of the served table: its sort bound from `limits`, its revision set. + /// @throws model::ActionRefusal when `servedDescription` answers `SourceContract`, or when a column's edit does + /// not fit its action's input (`checkEdits`, over the schemas the server serves). + template + static TableDescription invoke(Model& model, DescribeTable& action) { + static_cast(action); + auto const served = detail::serve(model, detail::callerContext()); + if (auto shown = validateDisplay(served.description); !shown) { + throw detail::refusalOf(shown.error()); + } + auto described = servedDescription(served); + if (!described) { + throw detail::refusalOf(described.error()); + } + if (auto const* const runtime = currentTableRuntime(); runtime != nullptr && runtime->schemaOf) { + auto const edits = + checkEdits(*described, [runtime](std::string_view tableId) -> std::optional { + std::string schema = runtime->schemaOf(tableId); + return schema.empty() ? std::nullopt : std::optional{std::move(schema)}; + }); + if (!edits) { + throw detail::refusalOf(edits.error()); + } + } + return std::move(*described); + } +}; + +/// @brief Answers the query. +/// @tparam Model The model type. +/// @param model The model instance. +/// @param action The action. +/// @return The page. +/// @throws morph::model::ActionRefusal `table.` with the argument `column`, for a query the table refuses. +template +template +// NOLINTNEXTLINE(cppcoreguidelines-avoid-reference-coroutine-parameters): the dispatcher keeps the model and the action alive until the task completes. +::core::async::Task QueryTable::invoke(Model& model, QueryTable& action) { + // Read before the first suspension: a server installs the runtime for the dispatch's first step only. + auto const* const runtime = currentTableRuntime(); + exec::IExecutor* const work = runtime != nullptr ? runtime->work : nullptr; + auto const [record, rowScoped] = detail::tableRecordOf(); + detail::AnswerContext const context{ + .views = runtime != nullptr ? runtime->views : nullptr, .record = record, .rowScoped = rowScoped}; + auto served = detail::pinned(detail::serve(model, detail::callerContext())); + std::expected answer; + if (work == nullptr) { + answer = detail::answerQuery(served, action.query, context); + } else { + // Its own statement: MSVC cannot tail-call a call that shares a full-expression with a `co_await`. + auto awaited = co_await detail::AnswerAwaiter{*work, std::move(served), action.query, context}; + answer = std::move(awaited); + } + if (!answer) { + throw detail::refusalOf(answer.error()); + } + co_return std::move(*answer); +} + +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + +} // namespace morph::table + +/// @brief The JSON of `morph::table::QueryTable`: its `TableQuery`'s. +/// @tparam Function The table's function. +template +struct glz::meta> { + /// @brief The action type. + using T = morph::table::QueryTable; + /// @brief The action is written as its query. + static constexpr auto value = &T::query; +}; + +// The selection types `BRIDGE_REGISTER_TABLE` registers `Table..resolve` with; they build on this header. +// NOLINTNEXTLINE(misc-header-include-cycle): row_selection.hpp needs the declarations above, so it is included after them. +#include + +// The commits of edited cells and the edit actions of a model's table; `checkEdits` above is defined there. +// NOLINTNEXTLINE(misc-header-include-cycle): edits.hpp needs the declarations above, so it is included after them. +#include diff --git a/include/morph/table/edits.hpp b/include/morph/table/edits.hpp index 0dbbd37cb..d12ead56f 100644 --- a/include/morph/table/edits.hpp +++ b/include/morph/table/edits.hpp @@ -14,24 +14,41 @@ /// stale from its commit until its edit settles. /// /// With an engine attached, a row holds its place while it has an edit in -/// flight (`Engine::beginEdit`), which a `Deferred` reorder honours. +/// flight (`Engine::beginEdit`), which a `Deferred` reorder honours, and an +/// edit of a cell the engine's view holds as `Unloaded` is refused on the cell: +/// it would overwrite a value the user has not seen. /// -/// See `docs/spec/table/engine.md`. +/// A model's table commits through `CellEdit` and `RowEdit` actions instead: +/// `CellEdits` built with a `RowEditCommit` sends one request per row commit, +/// one row's requests in order, and holds the cells' drafts, errors and +/// modified marks by row key and column, so a row that leaves the window and +/// comes back finds them where they were. +/// +/// See `docs/spec/table/engine.md` and `docs/spec/table/editing.md`. +#include #include +#include #include #include #include +#include +#include #include -#include -#include -#include +#include +// NOLINTNEXTLINE(misc-header-include-cycle): description.hpp includes edits.hpp at its end; the guard ends the cycle. +#include +#include +#include #include +#include #include #include +#include #include #include #include +#include #include namespace morph::table { @@ -62,13 +79,104 @@ using EditDone = std::function, FieldError> /// once with its outcome. using EditCommit = std::function; +/// @brief One cell's change on a model's table: the row and the new value of one member. Its schema carries +/// `x-cellEditOf` with the table's record at its root; which column it edits is the column's `EditInfo`. +/// +/// An application's action derives from it, so each action is its own type: +/// `struct EditSpecimenCount : table::CellEdit<&SpecimensModel::specimens, std::int64_t> {};`. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` names it. +/// @tparam T The member's type. +template +struct CellEdit { + /// @brief The row's key. + RowId key; + /// @brief The member's new value. + T value; + + /// @brief The schema keyword and its value that name the table, written at the schema's root. + /// @return `{"x-cellEditOf", "."}`; the name is empty when no such record is registered. + [[nodiscard]] static std::pair schemaValue() { + return {"x-cellEditOf", detail::recordNameOf(std::type_index{typeid(TableOf)})}; + } + + /// @brief The JSON of the action: `{"key": …, "value": …}`. Declared here so an action deriving from this type + /// reads and writes both members, which reflection over the derived type would count as one. + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks the meta type up by this name. + struct glaze { + /// @brief Each member after its JSON name. + static constexpr auto value = glz::object("key", &CellEdit::key, "value", &CellEdit::value); + }; +}; + +/// @brief Several members of one row of a model's table changed together. `Values` is the application's struct of the +/// row's editable members, each optional: a member present is changed, an absent one is left as it is. Its +/// schema carries `x-rowEditOf` with the table's record at its root. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` names it. +/// @tparam Values The struct of the row's editable members. +template +struct RowEdit { + /// @brief The row's key. + RowId key; + /// @brief The members changed. + Values values; + + /// @brief The schema keyword and its value that name the table, written at the schema's root. + /// @return `{"x-rowEditOf", "."}`; the name is empty when no such record is registered. + [[nodiscard]] static std::pair schemaValue() { + return {"x-rowEditOf", detail::recordNameOf(std::type_index{typeid(TableOf)})}; + } + + /// @brief The JSON of the action: `{"key": …, "values": …}`, for an action deriving from this type as for + /// `CellEdit`. + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks the meta type up by this name. + struct glaze { + /// @brief Each member after its JSON name. + static constexpr auto value = glz::object("key", &RowEdit::key, "values", &RowEdit::values); + }; +}; + +namespace detail { + +/// @brief Whether a form field of a kind can edit a column of a kind. +/// @param column The column's kind. +/// @param field The field's kind. +/// @return `true` when the field's kind is one the column's kind is edited with. +[[nodiscard]] MORPH_API bool editFits(ColumnKind column, forms::FieldKind field); + +} // namespace detail + +/// @brief One cell of a row commit on a model's table. +struct EditCell { + /// @brief The column's id. + std::string column; + /// @brief The value the action receives, as a JSON literal. + std::string json; + /// @brief The name the action's `FieldError` gives this cell: `value` for a `CellEdit`, the `EditInfo::member` for + /// a `RowEdit`; empty means the column's id. + std::string member; +}; + +/// @brief A row commit on a model's table: the cells of one row, sent as one request. +struct RowEditRequest { + /// @brief The row's key. + RowId row; + /// @brief The cells, in the order they were committed. + std::vector cells; +}; + +/// @brief Settles one row commit, on the owner thread: nothing on success, else the refusals. +using RowEditDone = std::function>)>; + +/// @brief Runs a row commit: the edit action for @p request, calling @p done once with its outcome. +using RowEditCommit = std::function; + /// @brief Commits cell edits row by row, in order. /// /// Owner-affine. A completion that arrives after the `CellEdits` is destroyed /// is ignored, and destroying it ends the engine edit of every row it still /// has in flight. The commit function, the patcher and the engine's handlers /// may commit again, or destroy this object, from inside a call it makes. -class CellEdits { +class MORPH_API CellEdits { public: /// @brief Builds the committer. /// @param patcher Replaces a row with the server's reply; must outlive this object. @@ -78,6 +186,11 @@ class CellEdits { CellEdits(RowPatcher& patcher, EditCommit commit, Engine* engine = nullptr) : _patcher{&patcher}, _commit{std::move(commit)}, _engine{engine} {} + /// @brief Builds the committer of a model's table: no patcher and no engine, its rows' commits sent through + /// @p commit. + /// @param commit Runs a row commit. + explicit CellEdits(RowEditCommit commit) : _patcher{nullptr}, _engine{nullptr}, _rowCommit{std::move(commit)} {} + CellEdits(CellEdits const&) = delete; CellEdits& operator=(CellEdits const&) = delete; CellEdits(CellEdits&&) = delete; @@ -86,122 +199,148 @@ class CellEdits { /// @brief Ends the engine edit of every row with an edit in flight or /// settling: its completion will be ignored, so nothing else would. // NOLINTNEXTLINE(bugprone-exception-escape) -- a handler that throws from here terminates, as from any destructor - ~CellEdits() { - if (_engine == nullptr) { - return; - } - std::vector rows{_ending.begin(), _ending.end()}; - for (auto const& [row, queue] : _queues) { - rows.push_back(row); - } - _queues.clear(); - _ending.clear(); - for (auto const& row : rows) { - _engine->endEdit(row); - } - } + ~CellEdits(); /// @brief Commits an edit: now, or after the row's earlier edits settle. + /// + /// An edit of a cell that is unloaded in the engine's view is not + /// committed: the cell's error becomes "not loaded yet" and the commit + /// function is not called. Without an engine nothing is checked. /// @param request The edit. - void commit(EditRequest request) { - auto& queue = _queues[request.row]; - queue.push_back(std::move(request)); - if (queue.size() == 1) { - start(queue.front().row); - } + void commit(EditRequest request); + + /// @brief Commits a row's cells as one request: now, or after the row's earlier row commits settle, in order. + /// @param request The row and its cells. + void commitRow(RowEditRequest request); + + /// @brief Holds a cell's draft, as the user typed it, with the error it does not encode by. + /// @param row The row's key. + /// @param column The column's id. + /// @param text The draft. + /// @param error Why it does not encode; nothing when it does. + void setDraft(RowId const& row, std::string_view column, std::string text, std::optional error); + + /// @brief A cell's draft. + /// @param row The row's key. + /// @param column The column's id. + /// @return The draft; nothing while none is held. + [[nodiscard]] std::optional draft(RowId const& row, std::string_view column) const; + + /// @brief Drops a cell's draft and its error. + /// @param row The row's key. + /// @param column The column's id. + void clearDraft(RowId const& row, std::string_view column); + + /// @brief Whether a cell is modified: from its row commit's success until the row is next fetched. + /// @param row The row's key. + /// @param column The column's id. + /// @return `true` while modified. + [[nodiscard]] bool modified(RowId const& row, std::string_view column) const; + + /// @brief Whether a row holds a modified mark or a draft in any of its cells. + /// @param row The row's key. + /// @return `true` when one does. + [[nodiscard]] bool rowEdited(RowId const& row) const; + + /// @brief The window fetched a row: its modified marks end, and so do the drafts its row commits settled. A cell + /// still stale is left as it is: its commit has not replied, so the row fetched does not hold it yet. + /// @param row The row's key. + void rowFetched(RowId const& row); + + /// @brief A fetch that named a row returned none: it was deleted, or no longer matches the filter. Its drafts, + /// errors, modified marks and the row commits not yet sent go; one in flight settles as it would and + /// leaves nothing behind. + /// @param row The row's key. + void rowAbsent(RowId const& row); + + /// @brief A row's key changed: its drafts, errors, modified marks and row commits move to the new key. Where the + /// new key holds a cell of its own, the new key's is kept. + /// @param from The row's old key. + /// @param destination The row's new key. + void moveRow(RowId const& from, RowId const& destination); + + /// @brief Keeps the drafts, errors and modified marks of these columns only: a new description dropped the others. + /// @param columns The ids of the columns kept. + void keepColumns(std::span columns); + + /// @brief Cells that show an error, wherever their row is. + /// @return The count. + [[nodiscard]] std::size_t errorCount() const; + + /// @brief Cells marked modified, wherever their row is. + /// @return The count. + [[nodiscard]] std::size_t modifiedCount() const; + + /// @brief Sets the one receiver of each row commit's settling, called once the cells took its outcome and the + /// row's next commit was sent, with the row's key now and whether the commit was refused. A commit whose + /// row went absent settles unheard. + /// @param handler The receiver; empty for none. + void onRowSettled(std::function handler) { + _rowSettled = std::move(handler); } /// @brief Whether a cell has an edit committed and not yet settled. /// @param row The row's key. /// @param column The column's id. /// @return `true` while stale. - [[nodiscard]] bool stale(RowId const& row, std::string_view column) const { - auto const found = _queues.find(row); - if (found == _queues.end()) { - return false; - } - return std::ranges::any_of(found->second, - [&](EditRequest const& request) { return request.column == column; }); - } + [[nodiscard]] bool stale(RowId const& row, std::string_view column) const; /// @brief The error a cell shows, until its next edit succeeds. /// @param row The row's key. /// @param column The column's id. /// @return The message, or nothing. - [[nodiscard]] std::optional error(RowId const& row, std::string_view column) const { - auto const found = _errors.find(row); - if (found == _errors.end()) { - return std::nullopt; - } - auto const cell = found->second.find(column); - return cell == found->second.end() ? std::nullopt : std::optional{cell->second}; - } + [[nodiscard]] std::optional error(RowId const& row, std::string_view column) const; /// @brief Edits committed and not yet settled, across rows. /// @return The count. - [[nodiscard]] std::size_t unsettled() const { - std::size_t out = 0; - for (auto const& [row, queue] : _queues) { - out += queue.size(); - } - return out; - } + [[nodiscard]] std::size_t unsettled() const; private: - void start(RowId const& row) { - if (_engine != nullptr) { - _engine->beginEdit(row); - } - // A copy: a commit that settles at once pops the queue's front, and the - // commit may still read its request afterwards. - auto const request = _queues.at(row).front(); - // The commit runs last: it may settle, commit again or destroy this object. - _commit(request, _alive.guard([this, row](std::expected, FieldError> outcome) { - settle(row, std::move(outcome)); - })); - } + // Whether the engine's view shows the edited cell as unloaded. + [[nodiscard]] bool unloadedInView(EditRequest const& request) const; + + void start(RowId const& row); // The queue is brought up to date before the patcher is called: patching // notifies the source's listeners at once, and their handlers may commit // to the same row or destroy this object. - void settle(RowId const& row, std::expected, FieldError> outcome) { - auto const found = _queues.find(row); - if (found == _queues.end() || found->second.empty()) { - return; - } - auto const request = std::move(found->second.front()); - found->second.pop_front(); - bool const more = !found->second.empty(); - if (!more) { - _queues.erase(found); - _ending.insert(row); - } - if (outcome) { - if (auto const errors = _errors.find(row); errors != _errors.end()) { - errors->second.erase(request.column); - } - auto const alive = _alive.token(); - _patcher->patchRow(row, std::move(*outcome)); - if (alive.expired()) { - return; - } - } else { - auto const column = outcome.error().column.empty() ? request.column : outcome.error().column; - _errors[row].insert_or_assign(column, std::move(outcome.error().message)); - } - if (more) { - start(row); - return; - } - _ending.erase(row); - if (_queues.contains(row)) { - // A commit made while the row was patched started its next edit. - return; - } - if (_engine != nullptr) { - _engine->endEdit(row); - } - } + void settle(RowId const& row, std::expected, FieldError> outcome); + + // A row commit: sent once it is at the front of its row's queue, and discarded on settling when its row went + // absent meanwhile. + struct RowFlight { + std::uint64_t id = 0; + RowEditRequest request; + bool sent = false; + bool discard = false; + // Each cell's draft when the commit was made, in the request's order: a success settles a cell's draft only + // while it is still this one, so a draft typed after the commit outlives the next fetch. + std::vector> drafts; + }; + + // A cell of a model's table: its draft; whether its row commit succeeded and the row was not fetched since; and + // whether its draft is the one that commit sent, which the next fetch replaces with the row's own value. + struct CellState { + std::optional draft; + bool modified = false; + bool settled = false; + }; + + [[nodiscard]] CellState const* cellOf(RowId const& row, std::string_view column) const; + + void eraseError(RowId const& row, std::string_view column); + + // Sends the front of a row's queue unless it is out already. The commit runs last: it may settle, commit again + // or destroy this object. + void startRow(RowId const& row); + + // A refusal lands by name: an error naming a cell's member (its column when it has none) is that cell's; one that + // names no cell of the request, or nothing, is every other cell's. A cell no error reached takes none. + void landErrors(RowEditRequest const& request, std::vector const& errors); + + // A row commit settled. The cells take its outcome, and the row's next commit is sent, before the receiver hears + // it: it may commit again or destroy this object. + void settleRow(std::uint64_t flightId, std::expected> outcome); RowPatcher* _patcher; EditCommit _commit; @@ -209,6 +348,11 @@ class CellEdits { std::unordered_map> _queues; std::unordered_set _ending; // last edit settled, row being patched std::unordered_map>> _errors; + RowEditCommit _rowCommit; + std::unordered_map> _rowQueues; + std::unordered_map>> _cells; + std::function _rowSettled; + std::uint64_t _nextFlight = 0; async::CallbackScope _alive; }; diff --git a/include/morph/table/engine.hpp b/include/morph/table/engine.hpp index 324666ee7..7adbbd2d5 100644 --- a/include/morph/table/engine.hpp +++ b/include/morph/table/engine.hpp @@ -44,7 +44,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -57,6 +59,7 @@ #include #include #include +#include #include #include #include @@ -110,6 +113,8 @@ struct EngineStats { std::size_t keyBuilds = 0; /// @brief Repairs of updated rows. std::size_t repairs = 0; + /// @brief Filter runs over a candidate list; a repair evaluates its dirty rows alone and runs none. + std::size_t filterRuns = 0; /// @brief Results dropped because a newer request superseded them. std::size_t dropped = 0; /// @brief Steps run on the owner thread (one-step runs included). @@ -118,14 +123,45 @@ struct EngineStats { std::size_t maxOwnerStepMicros = 0; }; -/// @brief Column order and visibility, kept apart from the engine's view. +/// @brief A column layout as it is stored: `{"order", "hidden", "pinned", "widths", "groups", "units"}`. /// -/// At least one column stays visible. +/// Read with glaze's reflection; a member the stored text leaves out reads as its default. +struct ColumnLayoutValue { + /// @brief The columns in display order. + std::vector order; + /// @brief The hidden columns, in display order. + std::vector hidden; + /// @brief How many of the first visible columns are pinned. + std::size_t pinned = 0; + /// @brief Column widths in units, by column id; every width is above zero. + std::map widths; + /// @brief The groups the user formed. + std::vector groups; + /// @brief Display units: by column id, a unit id per dimension. + std::map> units; + + /// @brief Member-wise equality. + /// @param other The layout to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(ColumnLayoutValue const& other) const = default; +}; + +/// @brief Column order, visibility, widths and pinning, kept apart from the engine's view. +/// +/// At least one column stays visible. A stored layout is fitted to the table's declared columns (`apply`): a +/// column the table no longer has is dropped from every part of it, and a column the layout does not name takes its +/// declared visibility and its declared place, right after the nearest column declared before it that the layout +/// places, or first when there is none. A user-formed group keeps the columns no earlier group holds; one left with +/// fewer than 2 or more than 16 columns, or repeating an earlier group's id, is dropped. class ColumnLayout { public: - /// @brief A layout of @p ids, all visible, in that order. - /// @param ids Column ids, the document's default order. - explicit ColumnLayout(std::vector ids) : _defaults{std::move(ids)} { reset(); } + /// @brief A layout of @p ids in that order, @p declaredHidden hidden. + /// @param ids Column ids, the declared order. + /// @param declaredHidden The columns hidden until the user shows them. + explicit ColumnLayout(std::vector ids, std::vector declaredHidden = {}) + : _defaults{std::move(ids)}, _declaredHidden{std::move(declaredHidden)} { + reset(); + } /// @brief The columns in display order. /// @return Column ids. @@ -143,9 +179,9 @@ class ColumnLayout { return out; } - /// @brief Shows or hides a column. - /// @param columnId Column columnId. - /// @param show `true` to show. + /// @brief Shows or hides a column; the pinned count follows the visible columns. + /// @param columnId The column. + /// @param show `true` to show. /// @return `false` when the column is unknown, or hiding it would leave none visible. bool setVisible(std::string const& columnId, bool show) { if (std::ranges::find(_order, columnId) == _order.end()) { @@ -159,11 +195,12 @@ class ColumnLayout { return false; } _hidden.insert(columnId); + clampPinned(); return true; } /// @brief Moves a column to a display position. - /// @param columnId Column columnId. + /// @param columnId The column. /// @param position Position in `order()`, clamped to the end. /// @return `false` when the column is unknown. bool move(std::string const& columnId, std::size_t position) { @@ -178,44 +215,328 @@ class ColumnLayout { return true; } - /// @brief Restores the default order with every column visible. + /// @brief Sets or clears a column's width. + /// @param columnId The column. + /// @param width The width in units, above zero; nothing clears it. + /// @return `false` when the column is unknown or the width is not above zero. + bool setWidth(std::string const& columnId, std::optional width) { + if (std::ranges::find(_order, columnId) == _order.end() || (width && *width <= 0)) { + return false; + } + if (width) { + _widths[columnId] = *width; + } else { + _widths.erase(columnId); + } + return true; + } + + /// @brief The widths set, by column id. + /// @return The widths. + [[nodiscard]] std::map const& widths() const noexcept { return _widths; } + + /// @brief Pins the first @p n visible columns. + /// @param n The count; clamped to the visible columns. + void setPinned(std::size_t n) { + _pinned = n; + clampPinned(); + } + + /// @brief How many of the first columns of `visible()` are pinned. + /// @return The count. + [[nodiscard]] std::size_t pinned() const noexcept { return _pinned; } + + /// @brief Forms a group of columns under a label, as the user does in the column chooser. + /// @param label The group's label. + /// @param columns The columns, 2 to 16, each a column of the layout and in no other user-formed group. + /// @return The new group's id, the first of `g1`, `g2`, … no group has; `InvalidSpec` when @p columns breaks the + /// rule above or repeats a column. + std::expected formGroup(std::string label, std::vector columns) { + auto const refuse = [](std::string message) { + return std::unexpected( + TableError{.code = TableErrorCode::InvalidSpec, .column = {}, .message = std::move(message)}); + }; + if (columns.size() < 2 || columns.size() > kMaxUserGroupColumns) { + return refuse("a group has 2 to 16 columns, not " + std::to_string(columns.size())); + } + for (std::size_t at = 0; at < columns.size(); ++at) { + auto const& columnId = columns[at]; + if (std::ranges::find(_order, columnId) == _order.end()) { + return refuse("unknown column: " + columnId); + } + if (std::ranges::find(columns.begin(), columns.begin() + static_cast(at), columnId) != + columns.begin() + static_cast(at)) { + return refuse("column " + columnId + " is named twice"); + } + for (auto const& group : _groups) { + if (std::ranges::find(group.columns, columnId) != group.columns.end()) { + return refuse("column " + columnId + " is already in group " + group.label); + } + } + } + std::string groupId; + for (std::size_t number = 1;; ++number) { + groupId = "g" + std::to_string(number); + if (std::ranges::none_of(_groups, [&](ColumnGroupInfo const& group) { return group.id == groupId; })) { + break; + } + } + _groups.push_back({.id = groupId, .label = std::move(label), .columns = std::move(columns)}); + return groupId; + } + + /// @brief Removes a user-formed group. + /// @param groupId The group's id. + /// @return `false` when no group has that id. + bool removeGroup(std::string const& groupId) { + return std::erase_if(_groups, [&](ColumnGroupInfo const& group) { return group.id == groupId; }) != 0; + } + + /// @brief The groups the user formed, in the order they were formed. + /// @return The groups. + [[nodiscard]] std::span groups() const noexcept { return _groups; } + + /// @brief Sets or clears the unit a column shows one of its dimensions in. + /// @param columnId The column. + /// @param dimension The dimension, such as `mass`. + /// @param unit The unit's id; `nullopt` clears it, and the cells show their own units. + /// @return `false` when the column is unknown, or @p dimension or @p unit is empty. + bool setUnit(std::string const& columnId, std::string const& dimension, std::optional unit) { + if (std::ranges::find(_order, columnId) == _order.end() || dimension.empty() || (unit && unit->empty())) { + return false; + } + if (unit) { + _units[columnId][dimension] = std::move(*unit); + return true; + } + if (auto const found = _units.find(columnId); found != _units.end()) { + found->second.erase(dimension); + if (found->second.empty()) { + _units.erase(found); + } + } + return true; + } + + /// @brief The display units: by column id, a unit id per dimension. + /// @return The units. + [[nodiscard]] std::map> const& units() const noexcept { + return _units; + } + + /// @brief The layout as it is stored. + /// @return Order, hidden columns in display order, pinned count, widths, groups and units. + [[nodiscard]] ColumnLayoutValue value() const { + ColumnLayoutValue out; + out.order = _order; + for (auto const& columnId : _order) { + if (_hidden.contains(columnId)) { + out.hidden.push_back(columnId); + } + } + out.pinned = _pinned; + out.widths = _widths; + out.groups = _groups; + out.units = _units; + return out; + } + + /// @brief Adopts a stored layout, fitted to the declared columns (see the class). + /// @param value The stored layout. + void apply(ColumnLayoutValue const& value) { fit(value); } + + /// @brief Restores the declared order and hidden columns, and clears widths and pinning; groups and units stay. void reset() { _order = _defaults; _hidden.clear(); + for (auto const& columnId : _declaredHidden) { + if (std::ranges::find(_order, columnId) != _order.end()) { + _hidden.insert(columnId); + } + } + if (!_order.empty() && visible().empty()) { + _hidden.erase(_order.front()); + } + _widths.clear(); + _pinned = 0; } - /// @brief Adopts a new column list: kept columns keep their place and - /// visibility, new ones are appended visible, vanished ones dropped. - /// @param ids The new columns, as the new default order. - void rebuild(std::vector ids) { + /// @brief Adopts a new declared column list and fits the current layout to it. + /// @param ids The new columns, in their declared order. + /// @param declaredHidden The new declared hidden columns. + void rebuild(std::vector ids, std::vector declaredHidden = {}) { + auto const current = value(); + _defaults = std::move(ids); + _declaredHidden = std::move(declaredHidden); + fit(current); + } + +private: + // The fitting rule: every part of `value` filtered to the declared columns, each declared column it lacks placed + // after its nearest declared predecessor that is placed, one column kept visible, and the pin count clamped. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + void fit(ColumnLayoutValue const& value) { + // Sets, not scans: a stored layout of a few hundred columns is fitted in one pass over each of its parts. + std::unordered_set const declaredIds{_defaults.begin(), _defaults.end()}; + auto const declared = [&declaredIds](std::string const& columnId) { return declaredIds.contains(columnId); }; std::vector order; - for (auto const& columnId : _order) { - if (std::ranges::find(ids, columnId) != ids.end()) { + std::unordered_set placed; + order.reserve(_defaults.size()); + for (auto const& columnId : value.order) { + if (declared(columnId) && placed.insert(columnId).second) { order.push_back(columnId); } } - for (auto const& columnId : ids) { - if (std::ranges::find(order, columnId) == order.end()) { - order.push_back(columnId); + std::vector unmentioned; + for (std::size_t at = 0; at < _defaults.size(); ++at) { + auto const& columnId = _defaults[at]; + if (placed.contains(columnId)) { + continue; } + auto place = order.begin(); + for (std::size_t before = at; before-- > 0;) { + if (auto const found = std::ranges::find(order, _defaults[before]); found != order.end()) { + place = std::next(found); + break; + } + } + order.insert(place, columnId); + unmentioned.push_back(columnId); } - std::erase_if(_hidden, - [&](std::string const& hiddenId) { return std::ranges::find(ids, hiddenId) == ids.end(); }); - _defaults = std::move(ids); _order = std::move(order); - if (!_order.empty() && visible().empty()) { - _hidden.erase(_order.front()); + _hidden.clear(); + for (auto const& columnId : value.hidden) { + if (declared(columnId)) { + _hidden.insert(columnId); + } } + // A column the stored layout predates keeps its author's visibility, so a column declared hidden is not + // shown, nor its level fetched, for every user who has a layout. + for (auto const& columnId : unmentioned) { + if (std::ranges::find(_declaredHidden, columnId) != _declaredHidden.end()) { + _hidden.insert(columnId); + } + } + _widths.clear(); + for (auto const& [columnId, width] : value.widths) { + if (declared(columnId) && width > 0) { + _widths.emplace(columnId, width); + } + } + _groups.clear(); + std::unordered_set grouped; + for (auto group : value.groups) { + if (std::ranges::any_of(_groups, [&](ColumnGroupInfo const& kept) { return kept.id == group.id; })) { + continue; + } + std::vector columns; + for (auto& columnId : group.columns) { + if (declared(columnId) && !grouped.contains(columnId) && + std::ranges::find(columns, columnId) == columns.end()) { + columns.push_back(std::move(columnId)); + } + } + if (columns.size() >= 2 && columns.size() <= kMaxUserGroupColumns) { + grouped.insert(columns.begin(), columns.end()); + group.columns = std::move(columns); + _groups.push_back(std::move(group)); + } + } + _units.clear(); + for (auto const& [columnId, units] : value.units) { + if (declared(columnId)) { + _units.emplace(columnId, units); + } + } + if (!_defaults.empty() && visible().empty()) { + _hidden.erase(_defaults.front()); + } + _pinned = value.pinned; + clampPinned(); } -private: + void clampPinned() { _pinned = std::min(_pinned, visible().size()); } + + // A group's column bound, `QueryLimits::maxGroupColumns`, which `query.hpp` holds and this header cannot include. + static constexpr std::size_t kMaxUserGroupColumns = 16; + std::vector _defaults; + std::vector _declaredHidden; std::vector _order; std::unordered_set _hidden; + std::map _widths; + std::size_t _pinned = 0; + std::vector _groups; + std::map> _units; }; namespace detail { +/// @brief A view with retained rows merged in, as `mergeRetainedOrder` returns it. +struct RetainedOrder { + /// @brief Source rows, in view order: the base order with the admitted rows at their sorted places. + std::vector order; + /// @brief The view rows of the admitted rows whose match is `No`, ascending. + std::vector unmatched; + /// @brief The retained rows the base order lacked, which the merge admitted, ascending by source row. + std::vector admitted; + /// @brief How many of `admitted` the filter could not decide (`Match::Unknown`). + std::int64_t undecided = 0; +}; + +/// @brief Merges the retained rows a base order lacks into it, each at the place the sort gives it. +/// +/// The base order must be sorted by @p before, which is a strict total order (ties to the lower source row, as +/// `RowOrder` breaks them), so the result is the order the sort gives the base rows and the admitted rows together. +/// Every admitted row is in the result whatever its match. Costs the scan of @p baseOrder for the retained rows it +/// holds, and a binary search of it for each admitted row. +/// @param baseOrder The view without retained rows: source rows, sorted by @p before. +/// @param retainedRows The retained rows, as source rows; a row named twice is admitted once. +/// @param before Whether one source row orders before another. +/// @param match What the filter says of a source row. +/// @return The merged order, the unmatched view rows, the admitted rows and how many of those were undecided. +[[nodiscard]] inline RetainedOrder mergeRetainedOrder(std::span baseOrder, + std::span retainedRows, + std::function const& before, + std::function const& match) { + RetainedOrder out; + std::unordered_set lacking(retainedRows.begin(), retainedRows.end()); + for (auto const row : baseOrder) { + if (lacking.empty()) { + break; + } + lacking.erase(row); + } + out.admitted.assign(lacking.begin(), lacking.end()); + std::ranges::sort(out.admitted); + std::vector> placed; + placed.reserve(out.admitted.size()); + for (auto const row : out.admitted) { + auto const decided = match(row); + if (decided == Match::Unknown) { + ++out.undecided; + } + placed.emplace_back(row, decided); + } + std::ranges::sort(placed, + [&before](auto const& left, auto const& right) { return before(left.first, right.first); }); + out.order.reserve(baseOrder.size() + placed.size()); + auto from = baseOrder.begin(); + for (auto const& [row, decided] : placed) { + auto const last = + std::upper_bound(from, baseOrder.end(), row, + [&before](std::uint32_t left, std::uint32_t right) { return before(left, right); }); + out.order.insert(out.order.end(), from, last); + from = last; + if (decided == Match::No) { + out.unmatched.push_back(static_cast(out.order.size())); + } + out.order.push_back(row); + } + out.order.insert(out.order.end(), from, baseOrder.end()); + return out; +} + /// @brief Everything one view job reads. Immutable once the job starts. struct JobInput { /// @brief The rows. @@ -246,12 +567,17 @@ struct JobInput { std::vector dirty; /// @brief Repair: the sorted, filtered order, without holds, that the dirty rows merge into. std::vector previousTrueView; + /// @brief Repair: the rows the filter could not decide, source rows ascending. A dirty row may have been here + /// or in the view, so a repair reads both. + std::vector previousUndecided; /// @brief The job repairs updated rows rather than recomputing. bool repair = false; /// @brief Every surviving row may have new content (a reset). bool allChanged = false; /// @brief More operations than this make the change a reset. std::size_t resetThreshold = 5000; + /// @brief Keys of rows the view keeps whatever the filter says of them; a key the snapshot lacks is ignored. + std::vector retained; }; /// @brief What a finished job hands back to the owner. @@ -262,6 +588,8 @@ struct JobResult { std::shared_ptr const> sorted; /// @brief The sorted, filtered view. std::vector view; + /// @brief The rows the filter could neither admit nor reject, source rows ascending. They are in no view. + std::vector undecided; /// @brief From `JobInput::previousView` to `view`. ViewChange change; /// @brief Every source row was sorted. @@ -270,10 +598,31 @@ struct JobResult { bool subsetSort = false; /// @brief Updated rows were merged into the previous order. bool repaired = false; + /// @brief A filter ran over a candidate list. + bool filtered = false; /// @brief Key columns built from scratch. std::size_t keyBuilds = 0; + /// @brief The retained rows in `view` the filter rejects, source rows ascending. + std::vector unmatched; }; +/// @brief The error of an unloaded cell in a base-level column: no level names that cell, so no load would +/// resolve it, and a view or a values list built on it would never settle. +/// @param info The column. +/// @return A `SourceContract` error naming the column. +[[nodiscard]] inline TableError unloadedInBaseLevel(ColumnInfo const& info) { + return TableError{.code = TableErrorCode::SourceContract, + .column = info.id, + .message = "an unloaded cell in a base-level column"}; +} + +/// @brief The error of a job an injected service failed. +/// @param what The message of the exception the service threw. +/// @return A `ServiceFailed` error. +[[nodiscard]] inline TableError serviceFailed(std::string const& what) { + return TableError{.code = TableErrorCode::ServiceFailed, .column = {}, .message = "a service failed: " + what}; +} + /// @brief One recomputation of a view, runnable in steps. /// /// Phases: build missing keys (or patch the keys of dirty rows), then either @@ -292,7 +641,9 @@ class ViewJob { /// @brief Runs until done, the deadline, or a stop request. /// /// An exception from an injected service (a collator, date parser or - /// comparator) ends the job: it is done, with `failure()` set. + /// comparator) ends the job: it is done, with `failure()` set to + /// `ServiceFailed`. So does an unloaded cell in a base-level column, with + /// `SourceContract` naming the column. /// @param deadline When to yield. /// @param stop A stop request ends the step. /// @return `true` when the job is done. @@ -300,9 +651,9 @@ class ViewJob { try { return run(deadline, stop); } catch (std::exception const& error) { - _failure = error.what(); + _failure = serviceFailed(error.what()); } catch (...) { - _failure = "unknown exception"; + _failure = serviceFailed("unknown exception"); } _phase = Phase::Done; return true; @@ -323,9 +674,9 @@ class ViewJob { /// @return `true` when done. [[nodiscard]] bool done() const noexcept { return _phase == Phase::Done; } - /// @brief Why the job failed: the message of the exception that ended it. - /// @return The message, or nothing when the job did not fail. - [[nodiscard]] std::optional const& failure() const noexcept { return _failure; } + /// @brief Why the job failed. + /// @return The error that ended it, or nothing when the job did not fail. + [[nodiscard]] std::optional const& failure() const noexcept { return _failure; } /// @brief What the job reads. /// @return The input. @@ -363,6 +714,10 @@ class ViewJob { if (!finished) { return false; } + if (_failure) { + _phase = Phase::Done; + return true; + } advance(); if (_onPhase) { auto const [doneUnits, total] = progress(); @@ -391,9 +746,19 @@ class ViewJob { } } + // Fails the job when a base-level column holds an unloaded cell (`detail::unloadedInBaseLevel`). + bool refuseUnloaded(std::size_t column, CellState state) { + if (state != CellState::Unloaded || !_in.columns[column].level.empty()) { + return false; + } + _failure = unloadedInBaseLevel(_in.columns[column]); + return true; + } + // Builds every needed column that has no keys, and patches the dirty rows // of every column that has them (on a copy: the old keys may still be // read by the owner or another job). + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. bool buildKeys(Deadline deadline, ::core::async::StopToken const& stop) { MORPH_ZONE("table.keyBuild"); auto const rows = _in.snapshot->rowCount(); @@ -405,6 +770,9 @@ class ViewJob { auto copy = std::make_shared(*_result.keys[column]); for (auto const row : _in.dirty) { copy->set(row, _in.snapshot->cell(row, column), _in.columns[column], _in.services); + if (refuseUnloaded(column, copy->states[row])) { + return true; + } } _result.keys[column] = std::move(copy); } @@ -429,6 +797,12 @@ class ViewJob { return false; } } + if (_in.columns[column].level.empty()) { + if (auto const found = std::ranges::find(_building->states, CellState::Unloaded); + found != _building->states.end() && refuseUnloaded(column, *found)) { + return true; + } + } _result.keys[column] = std::move(_building); _building = nullptr; ++_result.keyBuilds; @@ -471,26 +845,6 @@ class ViewJob { return out; } - [[nodiscard]] bool passesFilter(std::uint32_t row) const { - if (_in.filter == nullptr) { - return true; - } - for (auto const& column : _in.filter->columns()) { - if (!CompiledFilter::passes(column, *_result.keys[column.column], row)) { - return false; - } - } - for (auto const& group : _in.filter->groups()) { - bool const any = std::ranges::any_of(group.columns, [&](CompiledFilter::Column const& column) { - return CompiledFilter::passes(column, *_result.keys[column.column], row); - }); - if (!any) { - return false; - } - } - return true; - } - // Merges the dirty rows back into an order the clean rows still satisfy. [[nodiscard]] std::vector repairOrder(std::span previous, std::vector dirtyRows, @@ -513,16 +867,28 @@ class ViewJob { } // Merges the re-keyed dirty rows into the previous order (and the cached - // full order), without sorting the rest. + // full order), without sorting the rest. Each dirty row is evaluated + // again, wherever it was before: admitted rows merge into the view, + // undecided ones join the undecided rows, rejected ones join neither. The + // clean undecided rows are kept as they were, with no filter run over them. void repair() { MORPH_ZONE("table.change"); auto const orderBy = rowOrder(); + auto const keys = keyPointers(); std::vector passing; + std::vector undecided; for (auto const row : _in.dirty) { - if (passesFilter(row)) { + auto const match = _in.filter == nullptr ? Match::Yes : _in.filter->evaluateRow(keys, row); + if (match == Match::Yes) { passing.push_back(row); + } else if (match == Match::Unknown) { + undecided.push_back(row); } } + std::vector clean; + std::ranges::set_difference(_in.previousUndecided, _in.dirty, std::back_inserter(clean)); + _result.undecided.resize(clean.size() + undecided.size()); + std::ranges::merge(clean, undecided, _result.undecided.begin()); _result.view = repairOrder(_in.previousTrueView, std::move(passing), orderBy); if (_in.cachedSorted != nullptr) { _result.sorted = @@ -559,12 +925,14 @@ class ViewJob { } if (filtering && (_sorted || _sort == std::nullopt)) { _filterRun.emplace(*_in.filter, keyPointers(), std::move(_base)); + _result.filtered = true; } } bool order(Deadline deadline, ::core::async::StopToken const& stop) { if (_in.repair) { repair(); + admitRetained(); return true; } if (!_started) { @@ -576,6 +944,8 @@ class ViewJob { if (!_filterRun->run(deadline, stop)) { return false; } + _result.undecided = std::move(*_filterRun).takeUndecided(); + std::ranges::sort(_result.undecided); _base = std::move(*_filterRun).take(); _filterRun.reset(); if (!_sorted) { @@ -598,9 +968,41 @@ class ViewJob { } } _result.view = std::move(_base); + admitRetained(); return true; } + // Merges the retained rows the filter left out into the view at their sorted places; those it could not decide + // leave the undecided rows, and those it rejects are listed in `unmatched`. + void admitRetained() { + if (_in.retained.empty()) { + return; + } + std::unordered_set const wanted(_in.retained.begin(), _in.retained.end()); + std::vector rows; + for (std::size_t row = 0; row < _in.snapshot->rowCount() && rows.size() < wanted.size(); ++row) { + if (wanted.contains(_in.snapshot->rowId(row))) { + rows.push_back(static_cast(row)); + } + } + auto const orderBy = rowOrder(); + auto const keys = keyPointers(); + auto merged = mergeRetainedOrder( + _result.view, rows, [&orderBy](std::uint32_t left, std::uint32_t right) { return orderBy(left, right); }, + [this, &keys](std::uint32_t row) { + return _in.filter == nullptr ? Match::Yes : _in.filter->evaluateRow(keys, row); + }); + _result.view = std::move(merged.order); + std::vector undecided; + std::ranges::set_difference(_result.undecided, merged.admitted, std::back_inserter(undecided)); + _result.undecided = std::move(undecided); + _result.unmatched.clear(); + for (auto const column : merged.unmatched) { + _result.unmatched.push_back(_result.view[static_cast(column)]); + } + std::ranges::sort(_result.unmatched); + } + void diff() { MORPH_ZONE("table.apply"); std::vector changed = _in.dirty; @@ -648,12 +1050,15 @@ class ViewJob { std::optional _filterRun; std::optional _sort; // outcome - std::optional _failure; + std::optional _failure; std::function _onPhase; }; } // namespace detail +struct DistinctRequest; +struct DistinctValues; + /// @brief Sorts, filters and maps the view of one table. /// /// Owner-affine; see the file comment for how it executes. Holds a shared @@ -694,13 +1099,19 @@ class Engine final : private ChangeListener { /// shows once the view computed with them is applied. /// @param chain The keys, most significant first. /// @return `UnknownColumn` when a key names no column; `ServiceFailed` when - /// the sort ran inside the call and an injected service threw. The - /// sort is then unchanged. + /// the sort ran inside the call and an injected service threw; + /// `SourceContract` when it ran inside the call and a base-level + /// column holds an unloaded cell, or when a key's column is `Measure` and the services have no unit + /// registry. The sort is then unchanged. std::expected setSort(SortChain chain) { for (auto const& key : chain) { - if (!detail::findColumn(_columns, key.column)) { + auto const index = detail::findColumn(_columns, key.column); + if (!index) { return std::unexpected(detail::unknownColumn(key.column)); } + if (auto missing = detail::unitsMissing(_columns[*index], _options.services)) { + return std::unexpected(std::move(*missing)); + } } if (chain == _sort) { return {}; @@ -710,20 +1121,57 @@ class Engine final : private ChangeListener { } /// @brief Sets the filter. + /// + /// A group filter's `group` resolves through the source's declared groups, which are checked first + /// (`detail::checkGroups`). /// @param spec The filter; an empty spec shows every row. - /// @return The compile error, naming its column; or `ServiceFailed` when - /// the filter ran inside the call and an injected service threw. - /// The filter is then unchanged. + /// @return `SourceContract` when the source's declared groups are malformed; the compile error, naming its + /// column; or `ServiceFailed` or `SourceContract`, as for `setSort`, when the filter ran inside the + /// call. The filter is then unchanged. std::expected setFilter(FilterSpec spec) { + if (auto error = detail::checkGroups(_columns, _source->groups())) { + return std::unexpected(std::move(*error)); + } auto compiled = compile(spec); if (!compiled) { return std::unexpected(std::move(compiled.error())); } _filterSpec = std::move(spec); _filter = std::make_shared(std::move(*compiled)); + // The retained rows are of the filter they no longer matched. + if (!_retained.empty()) { + _retained.clear(); + ++_retainedVersion; + } + return schedule(); + } + + /// @brief Replaces the retained rows: rows the view keeps, at their sorted places, whatever the filter says of + /// them. `setFilter` clears them. + /// @param keys The rows' keys; a key the source lacks is ignored. + /// @return `ServiceFailed` or `SourceContract`, as for `setSort`, when the view was computed inside the call; the + /// retained rows are then those of the view shown. + std::expected retain(std::vector keys) { + if (keys == _retained) { + return {}; + } + _retained = std::move(keys); + ++_retainedVersion; return schedule(); } + /// @brief The retained rows asked for. + /// @return Their keys, as `retain` last set them. + [[nodiscard]] std::span retained() const noexcept { return _retained; } + + /// @brief Whether the row at a view row is retained and rejected by the filter. + /// @param viewRow View row index. + /// @return `true` for such a row; `false` past the end. + [[nodiscard]] bool isUnmatched(std::size_t viewRow) const { + auto const row = sourceRowOf(viewRow); + return row && std::ranges::binary_search(_unmatched, static_cast(*row)); + } + /// @brief The current sort chain. /// @return The chain. [[nodiscard]] SortChain const& sort() const noexcept { return _sort; } @@ -802,6 +1250,15 @@ class Engine final : private ChangeListener { /// @return The snapshot. [[nodiscard]] std::shared_ptr const& viewSnapshot() const noexcept { return _viewSnapshot; } + /// @brief Rows the filter can neither admit nor reject until an unloaded + /// cell loads. They are in no view row. + /// @return The count. + [[nodiscard]] std::size_t undecidedRowCount() const noexcept { return _undecided.size(); } + + /// @brief The undecided rows. + /// @return Source rows of `viewSnapshot()`, ascending. + [[nodiscard]] std::span undecidedRows() const noexcept { return _undecided; } + /// @brief Whether a computation is in flight. /// @return `true` from an asynchronous request until its result is applied. [[nodiscard]] bool pending() const noexcept { return _pending; } @@ -811,14 +1268,20 @@ class Engine final : private ChangeListener { /// @param handler The receiver; empty to stop receiving. void onViewChange(std::function handler) { _onViewChange = std::move(handler); } + /// @brief Sets the receiver of `undecidedRowCount()` changes, called on the + /// owner with the new count: after `onViewChange` when the same + /// result changed the view, and on its own when it changed nothing else. + /// @param handler The receiver; empty to stop receiving. + void onUndecidedChange(std::function handler) { _onUndecidedChange = std::move(handler); } + /// @brief Sets the receiver of `pending()` changes. /// @param handler The receiver; empty to stop receiving. void onPending(std::function handler) { _onPending = std::move(handler); } /// @brief Sets the receiver of errors no call could return: an injected - /// service that threw in a job that did not run inside the call - /// that asked for it. The sort and filter go back to those of the - /// view shown. + /// service that threw, or a source that broke its contract, in a job + /// that did not run inside the call that asked for it. The sort and + /// filter go back to those of the view shown. /// @param handler The receiver; empty to stop receiving. void onError(std::function handler) { _onError = std::move(handler); } @@ -826,6 +1289,17 @@ class Engine final : private ChangeListener { /// @return The engine's counters so far. [[nodiscard]] EngineStats const& stats() const noexcept { return _stats; } + /// @brief The distinct values of a column over the rows the engine's other filters leave: client mode's + /// `distinctValues`. + /// + /// Runs on the calling thread over the engine's latest snapshot, with the filter `filter()` returns less the + /// column's own entry. The key columns the engine holds for that snapshot are read; one it does not hold is built + /// for the call and not kept. The request is checked as `validate` checks it, with default `QueryLimits` and + /// every column readable. Defined in `table/query.hpp`, which declares the request and the reply. + /// @param request The column, search, bucket and page of values. + /// @return The values, or the request's error. + [[nodiscard]] std::expected distinctValues(DistinctRequest const& request) const; + /// @brief Marks a row as being edited: with `Deferred` reorder it keeps its /// place through updates until `endEdit`. /// @param key The row's key. @@ -855,6 +1329,11 @@ class Engine final : private ChangeListener { relayout(); } + /// @brief Takes in every change the source notified at once, rather than at the owner's next turn: what a + /// caller that changed the source and reads the view in the same turn calls. Nothing notified, nothing + /// done. + void flush() { flushChanges(); } + /// @brief Rows currently held in place by `Deferred` reorder. /// @return Their keys. [[nodiscard]] std::vector heldRows() const { return {_holds.begin(), _holds.end()}; } @@ -874,15 +1353,17 @@ class Engine final : private ChangeListener { // What the engine's state was when a job's input was taken, to tell on // the job's return whether a later change made its result useless. struct Ticket { - std::uint64_t epoch = 0; // structural changes absorbed - std::uint64_t changeSeq = 0; // notifications absorbed - std::uint64_t columnsVersion = 0; // column sets adopted + std::uint64_t epoch = 0; // structural changes absorbed + std::uint64_t changeSeq = 0; // notifications absorbed + std::uint64_t columnsVersion = 0; // column sets adopted + std::uint64_t retainedVersion = 0; // retained sets asked for }; // What applying a result calls out with. struct Applied { ViewChange change; bool armSettle = false; + std::optional undecided; // the new count, when it changed }; // ── changes ───────────────────────────────────────────────────────────── @@ -977,11 +1458,18 @@ class Engine final : private ChangeListener { std::erase_if(_sort, [&](SortKey const& key) { return !detail::findColumn(_columns, key.column); }); std::erase_if(_filterSpec.columns, [&](auto const& entry) { return !detail::findColumn(_columns, entry.first).has_value(); }); + // A filter on a declared group stays while the source still declares the group. + auto const declared = _source->groups(); + std::erase_if(_filterSpec.groups, [&declared](GroupFilter const& group) { + return !group.group.empty() && + std::ranges::find(declared, group.group, &ColumnGroupInfo::id) == declared.end(); + }); for (auto& group : _filterSpec.groups) { std::erase_if(group.columns, [&](std::string const& columnId) { return !detail::findColumn(_columns, columnId); }); } - std::erase_if(_filterSpec.groups, [](GroupFilter const& group) { return group.columns.empty(); }); + std::erase_if(_filterSpec.groups, + [](GroupFilter const& group) { return group.columns.empty() && group.group.empty(); }); auto compiled = compile(_filterSpec); if (compiled) { _filter = std::make_shared(std::move(*compiled)); @@ -994,11 +1482,7 @@ class Engine final : private ChangeListener { // The shared guarded compile: an exception from the collator or date parser is an error. [[nodiscard]] std::expected compile(FilterSpec const& spec) const { - return compileFilterGuarded(spec, _columns, _options.services); - } - - [[nodiscard]] static TableError serviceFailed(std::string const& what) { - return TableError{.code = TableErrorCode::ServiceFailed, .column = {}, .message = "a service failed: " + what}; + return compileFilterGuarded(spec, _columns, _options.services, _source->groups()); } // ── scheduling ────────────────────────────────────────────────────────── @@ -1006,22 +1490,24 @@ class Engine final : private ChangeListener { // Whether the shown view is out of date with the requested state. [[nodiscard]] bool hasWork() const { return !_dirty.empty() || _epoch != _viewEpoch || _sort != _appliedSort || _filter != _appliedFilter || - _columnsVersion != _viewColumnsVersion; + _columnsVersion != _viewColumnsVersion || _retainedVersion != _appliedRetainedVersion; } // A repair merges the dirty rows into the shown order: only the rows' // contents changed since that order was computed. (A structural change // advances the epoch; every row is owed a `Changed` exactly while the - // epoch is ahead of the view's.) + // epoch is ahead of the view's.) A view with retained rows is computed whole: a repair merges into an order the + // filter made, which retained rows are not part of. [[nodiscard]] bool canRepair() const { return !_dirty.empty() && _epoch == _viewEpoch && _sort == _appliedSort && _filter == _appliedFilter && - _columnsVersion == _viewColumnsVersion; + _columnsVersion == _viewColumnsVersion && _retained.empty() && + _retainedVersion == _appliedRetainedVersion; } // Whether a change since @p input was taken makes its result useless. [[nodiscard]] bool supersedes(detail::JobInput const& input, Ticket const& ticket) const { return _sort != input.sort || _filter != input.filter || _epoch != ticket.epoch || - _columnsVersion != ticket.columnsVersion; + _columnsVersion != ticket.columnsVersion || _retainedVersion != ticket.retainedVersion; } // Starts the work the requested state needs. While a job runs, a request @@ -1082,11 +1568,16 @@ class Engine final : private ChangeListener { input.dirty.erase(dupFirst, dupLast); if (input.repair) { input.previousTrueView = _trueView; + input.previousUndecided = _undecided; } input.allChanged = _obligeAll; _obligeAll = false; input.resetThreshold = _options.resetThreshold; - ticket = Ticket{.epoch = _epoch, .changeSeq = _absorbedSeq, .columnsVersion = _columnsVersion}; + input.retained = _retained; + ticket = Ticket{.epoch = _epoch, + .changeSeq = _absorbedSeq, + .columnsVersion = _columnsVersion, + .retainedVersion = _retainedVersion}; return input; } @@ -1103,6 +1594,10 @@ class Engine final : private ChangeListener { _sort = _appliedSort; _filterSpec = _appliedFilterSpec; _filter = _appliedFilter; + if (_retainedVersion != _appliedRetainedVersion) { + _retained = _appliedRetained; + _retainedVersion = _appliedRetainedVersion; + } if (_columnsVersion != _viewColumnsVersion) { fitToColumns(); } @@ -1118,7 +1613,7 @@ class Engine final : private ChangeListener { recordOwnerStep(began); giveBack(job.input(), ticket); revert(); - return std::unexpected(serviceFailed(*job.failure())); + return std::unexpected(*job.failure()); } auto const applied = install(job.input(), job.takeResult(), ticket); recordOwnerStep(began); @@ -1188,7 +1683,7 @@ class Engine final : private ChangeListener { if (job->failure()) { giveBack(input, _runningTicket); revert(); - afterJob(serviceFailed(*job->failure())); + afterJob(job->failure()); return; } auto const began = std::chrono::steady_clock::now(); @@ -1240,6 +1735,7 @@ class Engine final : private ChangeListener { _stats.fullSorts += result.fullSort ? 1 : 0; _stats.subsetSorts += result.subsetSort ? 1 : 0; _stats.repairs += result.repaired ? 1 : 0; + _stats.filterRuns += result.filtered ? 1 : 0; _keys = std::move(result.keys); _keysSnapshot = input.snapshot; if (result.sorted != nullptr) { @@ -1262,12 +1758,20 @@ class Engine final : private ChangeListener { _appliedSort = input.sort; _appliedFilter = input.filter; _appliedFilterSpec = _filterSpec; + _appliedRetained = input.retained; + _appliedRetainedVersion = ticket.retainedVersion; + _unmatched = std::move(result.unmatched); _trueView = std::move(result.view); + auto const undecidedBefore = _undecided.size(); + _undecided = std::move(result.undecided); _viewSnapshot = input.snapshot; _relayoutPending = false; _viewIndexValid = false; _keyIndexValid = false; - Applied out{.change = std::move(result.change), .armSettle = false}; + Applied out{ + .change = std::move(result.change), + .armSettle = false, + .undecided = _undecided.size() != undecidedBefore ? std::optional{_undecided.size()} : std::nullopt}; if (_options.reorder == ReorderPolicy::Deferred) { // An ended edit's token stands for the notifications up to its own // count: one the shown view had already taken in has no use. @@ -1354,7 +1858,7 @@ class Engine final : private ChangeListener { _view = std::move(displayed); _viewIndexValid = false; _keyIndexValid = false; - deliver(Applied{.change = change, .armSettle = false}); + deliver(Applied{.change = change, .armSettle = false, .undecided = std::nullopt}); } // ── calling out ───────────────────────────────────────────────────────── @@ -1379,6 +1883,13 @@ class Engine final : private ChangeListener { // A copy: the handler may replace itself or destroy the engine. auto const handler = _onViewChange; handler(applied.change); + if (alive.expired()) { + return false; + } + } + if (applied.undecided && _onUndecidedChange) { + auto const handler = _onUndecidedChange; + handler(*applied.undecided); } return !alive.expired(); } @@ -1447,6 +1958,8 @@ class Engine final : private ChangeListener { std::shared_ptr _filter; std::uint64_t _columnsVersion = 0; std::uint64_t _epoch = 0; + std::vector _retained; + std::uint64_t _retainedVersion = 0; // applied state: what the shown view was computed from std::vector _viewColumns; std::shared_ptr _viewSnapshot; @@ -1455,9 +1968,13 @@ class Engine final : private ChangeListener { std::shared_ptr _appliedFilter; std::uint64_t _viewColumnsVersion = 0; std::uint64_t _viewEpoch = 0; - std::uint64_t _viewChangeSeq = 0; // notifications the view took in - std::vector _view; // displayed - std::vector _trueView; // sorted and filtered, without holds + std::uint64_t _viewChangeSeq = 0; // notifications the view took in + std::vector _view; // displayed + std::vector _trueView; // sorted and filtered, without holds + std::vector _undecided; // neither admitted nor rejected, source rows ascending + std::vector _appliedRetained; + std::uint64_t _appliedRetainedVersion = 0; + std::vector _unmatched; // retained rows of the view the filter rejects, source rows ascending // caches, valid for `_keysSnapshot` std::shared_ptr _keysSnapshot; std::vector> _keys; @@ -1488,6 +2005,7 @@ class Engine final : private ChangeListener { Ticket _runningTicket; ::core::async::StopSource _jobStop; std::function _onViewChange; + std::function _onUndecidedChange; std::function _onPending; std::function _onError; EngineStats _stats; diff --git a/include/morph/table/filter.hpp b/include/morph/table/filter.hpp index 45f184e15..268d36a66 100644 --- a/include/morph/table/filter.hpp +++ b/include/morph/table/filter.hpp @@ -14,8 +14,14 @@ /// - the `include` entries of a column combine by `combine` (`any`, the /// default, or `all`); a match on an `exclude` entry rejects the row; /// columns, and groups, combine with each other by AND; -/// - a group matches a row when its entries match on any of its columns; +/// - a group counts the columns whose cell satisfies its entries against its +/// quantifier (`any` by default), or in `Together` mode finds each entry in a +/// column of its own; a match on one of its `exclude` entries rejects the row; /// - no operator but `isEmpty` and `notEmpty` matches an empty or invalid cell; +/// - on an unloaded cell every column filter is unknown, `isEmpty`, `notEmpty` +/// and `exclude` included: a row is rejected when any column filter or group +/// rejects it, otherwise undecided when any is unknown, otherwise admitted, +/// and a group admits a row as soon as one of its columns does; /// - text operators compare through the collator's primary-strength fold /// unless the entry sets `caseSensitive`; `%` and `_` are ordinary characters. /// @@ -28,14 +34,19 @@ #include #include #include +#include #include +#include #include #include #include #include #include #include +#include +#include #include +#include #include namespace morph::table { @@ -74,6 +85,14 @@ struct FilterEntry { std::optional notEmpty; /// @brief Text operators compare the text as given rather than folded. std::optional caseSensitive; + /// @brief Matches a cell whose value equals any of these. Each is parsed for the column's kind, as `eq`'s + /// operand is. + std::optional> oneOf; + + /// @brief Member-wise equality. + /// @param other The entry to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(FilterEntry const& other) const = default; }; /// @brief How a column's `include` entries combine. @@ -90,17 +109,107 @@ struct ColumnFilter { std::vector include; /// @brief Conditions that reject a row when any matches. std::vector exclude; + + /// @brief Member-wise equality. + /// @param other The filter to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(ColumnFilter const& other) const = default; +}; + +/// @brief How a group's `include` entries are found among its columns. +enum class GroupMode : std::uint8_t { + Columns, ///< Count the columns whose cell satisfies the entries, against `match`. + Together, ///< Every entry is found, each in a column of its own. +}; + +/// @brief How many of a group's columns must satisfy its entries, in `Columns` mode. +/// +/// Its JSON is `"any"`, `"all"`, `{"atLeast": n}` or `{"exactly": n}`. Any other shape reads as `atLeast -1`, which +/// every group refuses as malformed, in either mode. +struct ColumnCount { + /// @brief A quantifier. + enum class Kind : std::uint8_t { + Any, ///< At least one column. + All, ///< Every column. + AtLeast, ///< At least `n` columns. + Exactly, ///< Exactly `n` columns. + }; + /// @brief The quantifier. + Kind kind = Kind::Any; + /// @brief The count, for `AtLeast` and `Exactly`. + std::int64_t n = 1; + + /// @brief The JSON shape: a quantifier's name, or an object of one quantifier and its count. + using Wire = std::variant>; + + /// @brief Reads the JSON shape. + /// @param wire The shape as read. + void setWire(Wire const& wire) { + *this = ColumnCount{.kind = Kind::AtLeast, .n = -1}; + if (auto const* const name = std::get_if(&wire)) { + if (*name == "any" || *name == "all") { + *this = ColumnCount{.kind = *name == "any" ? Kind::Any : Kind::All, .n = 1}; + } + return; + } + auto const& counted = std::get>(wire); + if (counted.size() != 1) { + return; + } + auto const& [name, count] = *counted.begin(); + if (name == "atLeast" || name == "exactly") { + *this = ColumnCount{.kind = name == "atLeast" ? Kind::AtLeast : Kind::Exactly, .n = count}; + } + } + + /// @brief The JSON shape. + /// @return `"any"` or `"all"`, or `{"atLeast": n}` or `{"exactly": n}`. + [[nodiscard]] Wire getWire() const { + switch (kind) { + case Kind::All: + return std::string{"all"}; + case Kind::AtLeast: + return std::map{{"atLeast", n}}; + case Kind::Exactly: + return std::map{{"exactly", n}}; + case Kind::Any: + default: + return std::string{"any"}; + } + } + + /// @brief Member-wise equality. + /// @param other The count to compare with. + /// @return `true` when the kind and the count match. + [[nodiscard]] bool operator==(ColumnCount const& other) const = default; }; -/// @brief A filter over several columns: a row matches when the entries match -/// on any of them, which is what a quick-search box needs. +/// @brief A filter over several columns, named by a declared group or listed: in `Columns` mode a row passes when +/// the number of columns whose cell satisfies `include` meets `match`; in `Together` mode when each `include` +/// entry matches a column of its own. A match on an `exclude` entry in any column rejects the row. +/// +/// A filter that sets only `columns`, `combine` and `include` is the plain group: the entries match on any of the +/// columns, which is what a quick-search box needs. struct GroupFilter { - /// @brief The columns searched. + /// @brief A declared group's id; or empty, and `columns` lists the columns. + std::string group; + /// @brief The columns, when `group` is empty. std::vector columns; - /// @brief How `include` entries combine on one column. + /// @brief How `include` entries are found among the columns. + GroupMode mode = GroupMode::Columns; + /// @brief `Columns` mode: how many columns must satisfy `include`. + ColumnCount match; + /// @brief `Columns` mode: how one column's cell must satisfy `include`. Combine combine = Combine::Any; - /// @brief The conditions. + /// @brief The conditions; empty means the group's `exclude` alone decides. std::vector include; + /// @brief Conditions that reject a row when any matches in any of the columns. + std::vector exclude; + + /// @brief Member-wise equality. + /// @param other The filter to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(GroupFilter const& other) const = default; }; /// @brief A table's whole filter. @@ -113,8 +222,292 @@ struct FilterSpec { /// @brief Whether the spec filters nothing. /// @return `true` when it has no column filter and no group. [[nodiscard]] bool empty() const noexcept { return columns.empty() && groups.empty(); } + + /// @brief Member-wise equality. + /// @param other The filter to compare with. + /// @return `true` when every column filter and group matches. + [[nodiscard]] bool operator==(FilterSpec const& other) const = default; +}; + +/// @brief What a filter says of a row whose cells may be unloaded. +enum class Match : std::uint8_t { + No, ///< Rejected by what is loaded. + Yes, ///< Admitted by what is loaded. + Unknown, ///< Neither, until an unloaded cell loads: the row is undecided. +}; + +/// @brief What evaluating a filter cost, counted when a caller passes one to `CompiledFilter::evaluate`. +struct FilterCounters { + /// @brief Probes of a value set or of a group's value index: one per valid cell such an entry reads. + std::uint64_t setLookups = 0; + /// @brief Cells a group read. + std::uint64_t cellReads = 0; + /// @brief Augmenting-path searches a `Together` group started over its known cells. + std::uint64_t augmentations = 0; + /// @brief Augmenting-path searches a `Together` group started with its unknown columns matching every entry. + std::uint64_t wildcardAugmentations = 0; +}; + +namespace detail { + +/// @brief The golden-ratio constant a hash combine mixes in, cut to the width of `std::size_t`. +inline constexpr auto kHashSeed = static_cast(0x9e3779b97f4a7c15ULL); + +/// @brief A hash of an exact value: of its canonical numerator and denominator, which `Rational`'s equality +/// compares. +struct RationalHash { + /// @brief Hashes @p value. + /// @param value The value. + /// @return The hash. + [[nodiscard]] std::size_t operator()(math::Rational const& value) const noexcept { + auto const numerator = std::hash{}(value.numerator); + auto const denominator = std::hash{}(value.denominator); + return numerator ^ (denominator + kHashSeed + (numerator << 6U) + (numerator >> 2U)); + } +}; + +/// @brief A measure's key: its dimension's place in the column and its amount in the dimension's base unit. +struct MeasureKey { + /// @brief The dimension's place. + std::uint32_t place = 0; + /// @brief The base amount. + math::Rational amount; + + /// @brief Member-wise equality, the amount by value. + /// @param other The key to compare with. + /// @return `true` when the places and the amounts are equal. + [[nodiscard]] bool operator==(MeasureKey const& other) const = default; +}; + +/// @brief A hash of a measure's key: of its place and its amount's canonical numerator and denominator. +struct MeasureKeyHash { + /// @brief Hashes @p key. + /// @param key The key. + /// @return The hash. + [[nodiscard]] std::size_t operator()(MeasureKey const& key) const noexcept { + auto const amount = RationalHash{}(key.amount); + return amount ^ (std::hash{}(key.place) + kHashSeed + (amount << 6U) + (amount >> 2U)); + } }; +/// @brief A transparent string hash, so a set of strings is probed with a view and nothing is copied. +struct TextHash { + /// @brief Marks the hash transparent. + using is_transparent = void; + /// @brief Hashes @p text. + /// @param text The text. + /// @return The hash. + [[nodiscard]] std::size_t operator()(std::string_view text) const noexcept { + return std::hash{}(text); + } +}; + +} // namespace detail + +/// @brief The members of one `oneOf` entry, parsed for one column: a cell is matched by one lookup, whatever the +/// set's size. +/// +/// Members are keyed as the column's cells are: integers, keys, decimals and quantities exactly, `Number` as a +/// double, dates, date-times and booleans as their integer, text by its fold, or as given when the entry sets +/// `caseSensitive`, and a measure by its dimension's place and its base amount. +class ValueSet { +public: + /// @brief An empty set for a column of @p kind. + /// @param kind The column's kind. + /// @param caseSensitive Text members are kept as given rather than folded. + explicit ValueSet(ColumnKind kind, bool caseSensitive = false) noexcept + : _kind{kind}, _caseSensitive{caseSensitive} {} + + /// @brief Adds an integer member: a date, a date-time or a boolean. + /// @param value The member. + void add(std::int64_t value) { _ints.insert(value); } + + /// @brief Adds an exact member: an integer, a key, a decimal or a quantity. + /// @param value The member. + void add(math::Rational const& value) { _exact.insert(value); } + + /// @brief Adds a `Number` member; zero is one member whatever its sign. + /// @param value The member. + void add(double value) { _reals.insert(value == 0.0 ? 0.0 : value); } + + /// @brief Adds a text member, already folded unless the set is case-sensitive. + /// @param value The member. + void add(std::string value) { _texts.insert(std::move(value)); } + + /// @brief Adds a measure member. + /// @param place Its dimension's place in the column. + /// @param amount Its amount in the dimension's base unit. + void add(std::uint32_t place, math::Rational const& amount) { + _measures.insert(detail::MeasureKey{.place = place, .amount = amount}); + } + + /// @brief Whether a valid cell's value is a member: one probe of the set. + /// @param keys The column's keys; the cell at @p row is valid. + /// @param row The row. + /// @param counters Counts the probe in `setLookups` when not null. + /// @return `true` when the cell's value is in the set. + [[nodiscard]] bool contains(KeyColumn const& keys, std::uint32_t row, FilterCounters* counters) const { + if (counters != nullptr) { + ++counters->setLookups; + } + switch (_kind) { + case ColumnKind::Integer: + case ColumnKind::Key: + return _exact.contains(math::Rational{keys.ints[row], math::DecimalPlaces{0}}); + case ColumnKind::Decimal: + case ColumnKind::Quantity: + return _exact.contains(keys.exact[row]); + case ColumnKind::Number: { + auto const value = keys.reals[row]; + return _reals.contains(value == 0.0 ? 0.0 : value); + } + case ColumnKind::Date: + case ColumnKind::DateTime: + case ColumnKind::Bool: + return _ints.contains(keys.ints[row]); + case ColumnKind::Text: + return _texts.contains(std::string_view{_caseSensitive ? keys.raw[row] : keys.folded[row]}); + case ColumnKind::Measure: + return _measures.contains(detail::MeasureKey{.place = keys.places[row], .amount = keys.exact[row]}); + case ColumnKind::Custom: + default: + return false; + } + } + + /// @brief The members, duplicates merged. + /// @return The member count. + [[nodiscard]] std::size_t size() const noexcept { + return _ints.size() + _exact.size() + _reals.size() + _texts.size() + _measures.size(); + } + +private: + ColumnKind _kind; + bool _caseSensitive; + std::unordered_set _ints; + std::unordered_set _exact; + std::unordered_set _reals; + std::unordered_set> _texts; + std::unordered_set _measures; +}; + +/// @brief A group column's value entries, by value: one probe gives the bits of every `eq` and `oneOf` entry the +/// cell's value matches. +/// +/// Keyed as a `ValueSet` is; text by its fold, so only entries that are not `caseSensitive` are indexed, and a measure +/// by its dimension's place and its base amount, so equal amounts of two dimensions are two values. +class ValueIndex { +public: + /// @brief An empty index for a column of @p kind. + /// @param kind The column's kind. + explicit ValueIndex(ColumnKind kind = ColumnKind::Text) noexcept : _kind{kind} {} + + /// @brief Adds @p bits to a date, date-time or boolean value. + /// @param value The value. + /// @param bits The entries' bits. + void add(std::int64_t value, std::uint32_t bits) { _ints[value] |= bits; } + + /// @brief Adds @p bits to an exact value: an integer, a key, a decimal or a quantity. + /// @param value The value. + /// @param bits The entries' bits. + void add(math::Rational const& value, std::uint32_t bits) { _exact[value] |= bits; } + + /// @brief Adds @p bits to a `Number` value; zero is one value whatever its sign. + /// @param value The value. + /// @param bits The entries' bits. + void add(double value, std::uint32_t bits) { _reals[value == 0.0 ? 0.0 : value] |= bits; } + + /// @brief Adds @p bits to a folded text. + /// @param value The text, folded. + /// @param bits The entries' bits. + void add(std::string const& value, std::uint32_t bits) { + if (auto const found = _texts.find(std::string_view{value}); found != _texts.end()) { + found->second |= bits; + } else { + _texts.emplace(value, bits); + } + } + + /// @brief Adds @p bits to a measure. + /// @param place Its dimension's place in the column. + /// @param amount Its amount in the dimension's base unit. + /// @param bits The entries' bits. + void add(std::uint32_t place, math::Rational const& amount, std::uint32_t bits) { + _measures[detail::MeasureKey{.place = place, .amount = amount}] |= bits; + } + + /// @brief Whether the index holds no value. + /// @return `true` when nothing was added. + [[nodiscard]] bool empty() const noexcept { + return _ints.empty() && _exact.empty() && _reals.empty() && _texts.empty() && _measures.empty(); + } + + /// @brief The bits of the entries a valid cell's value matches: one probe. + /// @param keys The column's keys; the cell at @p row is valid. + /// @param row The row. + /// @param counters Counts the probe in `setLookups` when not null. + /// @return The bits; zero when no entry matches. + [[nodiscard]] std::uint32_t lookup(KeyColumn const& keys, std::uint32_t row, FilterCounters* counters) const { + if (counters != nullptr) { + ++counters->setLookups; + } + auto const countIn = [](auto const& map, auto const& key) -> std::uint32_t { + auto const found = map.find(key); + return found == map.end() ? 0U : found->second; + }; + switch (_kind) { + case ColumnKind::Integer: + case ColumnKind::Key: + return countIn(_exact, math::Rational{keys.ints[row], math::DecimalPlaces{0}}); + case ColumnKind::Decimal: + case ColumnKind::Quantity: + return countIn(_exact, keys.exact[row]); + case ColumnKind::Number: { + auto const value = keys.reals[row]; + return countIn(_reals, value == 0.0 ? 0.0 : value); + } + case ColumnKind::Date: + case ColumnKind::DateTime: + case ColumnKind::Bool: + return countIn(_ints, keys.ints[row]); + case ColumnKind::Text: + return countIn(_texts, std::string_view{keys.folded[row]}); + case ColumnKind::Measure: + return countIn(_measures, detail::MeasureKey{.place = keys.places[row], .amount = keys.exact[row]}); + case ColumnKind::Custom: + default: + return 0U; + } + } + +private: + ColumnKind _kind; + std::unordered_map _ints; + std::unordered_map _exact; + std::unordered_map _reals; + std::unordered_map> _texts; + std::unordered_map _measures; +}; + +class CompiledFilter; + +/// @brief Compiles @p spec against @p columns. +/// +/// In a group, an entry whose operator a column's kind does not define, or +/// whose value does not parse for it, does not apply to that column; it is an +/// error only when it applies to none of the group's columns. A quick-search +/// text therefore searches the text columns of a group that also holds numbers. +/// A group with no include and no exclude entry compiles to nothing. +/// @param spec The filter. +/// @param columns The table's columns. +/// @param services The collator (values of text filters are folded with it) +/// and date parser; null members mean their defaults. +/// @param groups The table's declared groups, which a group filter's `group` names. +/// @return The compiled filter, or the first error, naming its column. +[[nodiscard]] inline std::expected compileFilter( + FilterSpec const& spec, std::span columns, Services const& services, + std::span groups = {}); + /// @brief A filter compiled against a table's columns: every value parsed. class CompiledFilter { public: @@ -131,7 +524,8 @@ class CompiledFilter { StartsWith, EndsWith, IsEmpty, - NotEmpty + NotEmpty, + OneOf }; /// @brief One compiled condition. @@ -142,14 +536,19 @@ class CompiledFilter { bool caseSensitive = false; /// @brief Integer operands (dates, date-times, booleans). std::array ints{}; - /// @brief Exact operands (integers, keys, decimals, quantities). + /// @brief Exact operands (integers, keys, decimals, quantities; a measure's base amount). std::array exact{}; + /// @brief A measure operand's dimension place in the column; `Between`'s two are equal. + std::array places{}; /// @brief Floating-point operands (`Number`). std::array reals{}; /// @brief Text operand: folded, or raw when `caseSensitive`. std::string text; - /// @brief The operands as the filter spec gave them (`Between` uses both); empty for `IsEmpty` and `NotEmpty`. + /// @brief The operands as the filter spec gave them (`Between` uses both); empty for `IsEmpty`, `NotEmpty` + /// and `OneOf`. std::array operands; + /// @brief `OneOf`'s members, parsed for the column; null for every other operator. + std::shared_ptr set; }; /// @brief One column's compiled filter. @@ -164,10 +563,47 @@ class CompiledFilter { std::vector exclude; }; + /// @brief How one column of a group evaluates its entries: which entry each is, and the value index. + struct GroupColumn { + /// @brief The bit of each of the column's include entries: its place in the group's `include`. + std::vector includeBits; + /// @brief The bit of each of the column's exclude entries: its place in the group's `exclude`. + std::vector excludeBits; + /// @brief The include entries matched by value (`eq` and `oneOf`, not case-sensitive). + ValueIndex include; + /// @brief The exclude entries matched by value. + ValueIndex exclude; + /// @brief The include entries the index does not hold, by their place in `Column::include`: tested one by + /// one. + std::vector includeTested; + /// @brief The exclude entries the index does not hold, by their place in `Column::exclude`. + std::vector excludeTested; + /// @brief Every bit of `includeBits`. + std::uint32_t compiled = 0; + /// @brief Whether the column can satisfy the include entries in `Columns` mode: with `combine: all` it + /// compiled every one, with `any` at least one. A column that cannot is a known *no*. + bool usable = false; + }; + /// @brief One compiled group: per column, the entries that apply to it. struct Group { - /// @brief The group's columns, each with the entries that compiled for it. + /// @brief The group's columns that compiled at least one entry, each with those entries, in the group's + /// order. std::vector columns; + /// @brief Per entry of `columns`, its bits and value index. + std::vector index; + /// @brief The columns the group names, whether or not an entry compiled on them. + std::size_t k = 0; + /// @brief How the include entries are found. + GroupMode mode = GroupMode::Columns; + /// @brief `Columns` mode's quantifier. + ColumnCount match; + /// @brief How one column's cell satisfies the include entries in `Columns` mode. + Combine combine = Combine::Any; + /// @brief The group's include entries. + std::size_t includeCount = 0; + /// @brief The group's exclude entries. + std::size_t excludeCount = 0; }; /// @brief Whether the filter matches every row. @@ -201,34 +637,337 @@ class CompiledFilter { /// @return The groups. [[nodiscard]] std::span groups() const noexcept { return _groups; } - /// @brief Whether a row passes one column filter. - /// @param filter The column filter. - /// @param keys That column's keys. - /// @param row The row. - /// @return `true` when the row passes. - [[nodiscard]] static bool passes(Column const& filter, KeyColumn const& keys, std::uint32_t row) { + /// @brief What one column filter says of a row. + /// + /// An unloaded cell is `Unknown` whatever the entries: whether it is empty, + /// and whether an exclude entry matches it, is not known either. + /// @param filter The column filter. + /// @param keys That column's keys. + /// @param row The row. + /// @param counters Counts the lookups of value sets when not null. + /// @return `Unknown` on an unloaded cell, else `Yes` when the row passes and `No` when it does not. + [[nodiscard]] static Match evaluate(Column const& filter, KeyColumn const& keys, std::uint32_t row, + FilterCounters* counters = nullptr) { + if (keys.states[row] == CellState::Unloaded) { + return Match::Unknown; + } if (!filter.include.empty()) { bool const all = filter.combine == Combine::All; bool result = all; for (auto const& entry : filter.include) { - if (matches(entry, keys, row) != all) { + if (matches(entry, keys, row, counters) != all) { result = !all; break; } } if (!result) { + return Match::No; + } + } + bool const excluded = std::ranges::any_of( + filter.exclude, [&](Entry const& entry) { return matches(entry, keys, row, counters); }); + return excluded ? Match::No : Match::Yes; + } + + /// @brief Whether a row passes one column filter. + /// @param filter The column filter. + /// @param keys That column's keys. + /// @param row The row. + /// @return `true` when `evaluate` says `Yes`. + [[nodiscard]] static bool passes(Column const& filter, KeyColumn const& keys, std::uint32_t row) { + return evaluate(filter, keys, row) == Match::Yes; + } + + /// @brief What one group says of a row, three-valued over its unloaded cells. + /// + /// Each column's cell is read once, and gives the bits of the include entries it matches: for value entries + /// one probe of the column's index, a condition tested per entry. An unloaded cell's column is unknown. In + /// `Columns` mode, with y the columns that satisfy, q the unknown ones and r those not read yet, reading stops + /// as soon as the quantifier is decided: `any` is `Yes` at y ≥ 1 and `No` at y + q + r = 0; `all` `Yes` at + /// y = k and `No` at y + q + r < k; `atLeast n` `Yes` at y ≥ n and `No` at y + q + r < n; `exactly n` `Yes` at + /// y = n with q = r = 0 and `No` at y > n or y + q + r < n; otherwise `Unknown`. In `Together` mode every + /// column is read; a row whose known cells leave an entry unmatched and has no unknown column is `No` with no + /// matching tried; otherwise a matching of entries to distinct columns over the known cells is `Yes`, and + /// failing that one that counts each unknown column as matching every entry compiled on it is `Unknown`, and + /// none is `No`. A known cell matching an exclude entry makes the group `No`; otherwise an unknown column with + /// exclude entries makes it `Unknown`. A group with exclude entries reads every column. + /// @param group The group. + /// @param keys Key columns by column index; every column of the group must be non-null. + /// @param row The row. + /// @param counters Counts cell reads, index lookups and augmentations when not null. + /// @return The group's answer. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): a per-row hot path: one pass over the group's columns that decides early, kept in one function so the state stays in registers. + [[nodiscard]] static Match evaluateGroup(Group const& group, std::span keys, + std::uint32_t row, FilterCounters* counters = nullptr) { + constexpr std::size_t kMaxTogether = 16; + bool const together = group.mode == GroupMode::Together; + bool const hasExclude = group.excludeCount > 0; + auto include = group.includeCount == 0 ? std::optional{Match::Yes} : std::optional{}; + std::int64_t y = 0; + std::int64_t unloaded = 0; + std::int64_t remaining = 0; + for (auto const& column : group.index) { + remaining += column.usable ? 1 : 0; + } + auto const k = static_cast(group.k); + // Yes once `met`, No once `lost`, otherwise still open. + auto const settle = [](bool met, bool lost) -> std::optional { + if (met) { + return Match::Yes; + } + if (lost) { + return Match::No; + } + return std::nullopt; + }; + auto const decide = [&] { + auto const needed = group.match.n; + switch (group.match.kind) { + case ColumnCount::Kind::All: + return settle(y == k, y + unloaded + remaining < k); + case ColumnCount::Kind::AtLeast: + return settle(y >= needed, y + unloaded + remaining < needed); + case ColumnCount::Kind::Exactly: + if (y > needed || y + unloaded + remaining < needed) { + return std::optional{Match::No}; + } + return y == needed && unloaded == 0 && remaining == 0 ? std::optional{Match::Yes} + : std::optional{}; + case ColumnCount::Kind::Any: + default: + return settle(y >= 1, y + unloaded + remaining == 0); + } + }; + if (!include && !together) { + include = decide(); + if (include == Match::No) { + return Match::No; + } + } + std::array masks{}; + std::uint32_t unknownColumns = 0; + bool excludeUnknown = false; + for (std::size_t at = 0; at < group.columns.size(); ++at) { + if (include && !hasExclude) { + break; + } + auto const& column = group.columns[at]; + auto const& index = group.index[at]; + auto const& cells = *keys[column.column]; + if (counters != nullptr) { + ++counters->cellReads; + } + bool const unknown = cells.states[row] == CellState::Unloaded; + if (!include && together) { + if (unknown) { + unknownColumns |= 1U << at; + } else { + masks.at(at) = entryBits(column.include, index.includeBits, index.include, index.includeTested, + cells, row, counters); + } + } else if (!include && index.usable) { + --remaining; + if (unknown) { + ++unloaded; + } else { + auto const bits = entryBits(column.include, index.includeBits, index.include, index.includeTested, + cells, row, counters); + bool const satisfies = group.combine == Combine::All ? bits == index.compiled : bits != 0; + y += satisfies ? 1 : 0; + } + include = decide(); + if (include == Match::No) { + return Match::No; + } + } + if (hasExclude && !index.excludeBits.empty()) { + if (unknown) { + excludeUnknown = true; + } else if (entryBits(column.exclude, index.excludeBits, index.exclude, index.excludeTested, cells, row, + counters) != 0) { + return Match::No; + } + } + } + if (!include && together) { + include = matchTogether(group, std::span{masks}.first(group.columns.size()), unknownColumns, counters); + if (include == Match::No) { + return Match::No; + } + } + if (!include || *include == Match::Unknown || excludeUnknown) { + return Match::Unknown; + } + return Match::Yes; + } + +private: + /// @brief The bits of the entries of one group column that one cell matches. + /// @param entries The column's compiled entries. + /// @param bits Each entry's bit. + /// @param index The value index over the entries it holds. + /// @param tested The entries the index does not hold, by place in @p entries. + /// @param keys The column's keys. + /// @param row The row; its cell is loaded. + /// @param counters Counts the index probe when not null. + /// @return The bits; an empty or invalid cell matches only `isEmpty` or `notEmpty` entries, with no probe. + [[nodiscard]] static std::uint32_t entryBits(std::span entries, std::span bits, + ValueIndex const& index, std::span tested, + KeyColumn const& keys, std::uint32_t row, FilterCounters* counters) { + std::uint32_t out = 0; + if (keys.states[row] != CellState::Valid) { + for (std::size_t at = 0; at < entries.size(); ++at) { + if (matches(entries[at], keys, row)) { + out |= bits[at]; + } + } + return out; + } + if (!index.empty()) { + out = index.lookup(keys, row, counters); + } + for (auto const column : tested) { + if (matches(entries[column], keys, row, counters)) { + out |= bits[column]; + } + } + return out; + } + + /// @brief `Together` mode's answer once every column is read. + /// @param group The group. + /// @param masks Each column's include bits; zero for an unknown column. + /// @param unknownColumns The unknown columns, as bits of their places in `group.columns`. + /// @param counters Counts the known pass's augmentations in `augmentations` and the pass with the unknown + /// columns matching every entry in `wildcardAugmentations`, when not null. + /// @return `Yes` when a matching over the known cells covers every entry; `Unknown` when one does only with + /// every unknown column matching every entry compiled on it; `No` otherwise. + [[nodiscard]] static Match matchTogether(Group const& group, std::span masks, + std::uint32_t unknownColumns, FilterCounters* counters) { + auto const entries = group.includeCount; + std::uint32_t const full = entries >= 32 ? ~0U : (1U << entries) - 1U; + std::uint32_t covered = 0; + for (auto const mask : masks) { + covered |= mask; + } + if (covered == full && cover(masks, entries, counters)) { + return Match::Yes; + } + if (unknownColumns == 0) { + return Match::No; + } + covered = 0; + std::size_t usable = 0; + for (std::size_t at = 0; at < masks.size(); ++at) { + if (((unknownColumns >> at) & 1U) != 0U) { + masks[at] = group.index[at].compiled; + } + covered |= masks[at]; + usable += masks[at] != 0 ? 1U : 0U; + } + // Each entry needs a column of its own, so fewer columns that match any entry than there are entries + // cannot be matched (Hall's condition on the column side). The unknown columns' masks are full, so the + // covered test alone passes on nearly every row, and the search would then run a failing augmenting-path + // search for up to every entry of every such row. + if (covered != full || usable < entries) { + return Match::No; + } + return cover(masks, entries, counters, true) ? Match::Unknown : Match::No; + } + + /// @brief Whether every entry can be given a column of its own among @p masks: augmenting paths, one search an + /// entry. + /// @param masks Each column's entry bits. + /// @param entries The entries to cover, bits `0..entries-1`. + /// @param counters Counts each search when not null. + /// @param wildcard The search counts in `wildcardAugmentations` rather than `augmentations`. + /// @return `true` when a matching covers every entry. + [[nodiscard]] static bool cover(std::span masks, std::size_t entries, + FilterCounters* counters, bool wildcard = false) { + constexpr std::size_t kMaxTogether = 16; + std::array owner{}; + owner.fill(-1); + for (std::size_t entry = 0; entry < entries; ++entry) { + if (counters != nullptr) { + ++(wildcard ? counters->wildcardAugmentations : counters->augmentations); + } + std::uint32_t visited = 0; + if (!augment(static_cast(entry), masks, owner, visited)) { return false; } } - return std::ranges::none_of(filter.exclude, [&](Entry const& entry) { return matches(entry, keys, row); }); + return true; + } + + /// @brief One augmenting-path search from @p entry: a free column that matches it first, so a dense row is + /// matched without following owners; only then an owned one whose owner can move. + /// @param entry The entry to place. + /// @param masks Each column's entry bits. + /// @param owner The entry each column holds, or -1. + /// @param visited The columns this search has visited. + /// @return `true` when @p entry was placed. + // NOLINTNEXTLINE(misc-no-recursion): the augmenting-path search of a bipartite matching; the path is at most one step per column. + [[nodiscard]] static bool augment(int entry, std::span masks, std::span owner, + std::uint32_t& visited) { + auto const bit = static_cast(entry); + for (std::size_t column = 0; column < masks.size(); ++column) { + if (((masks[column] >> bit) & 1U) != 0 && owner[column] < 0 && ((visited >> column) & 1U) == 0) { + visited |= 1U << column; + owner[column] = entry; + return true; + } + } + for (std::size_t column = 0; column < masks.size(); ++column) { + if (((masks[column] >> bit) & 1U) == 0 || ((visited >> column) & 1U) != 0) { + continue; + } + visited |= 1U << column; + if (owner[column] < 0 || augment(owner[column], masks, owner, visited)) { + owner[column] = entry; + return true; + } + } + return false; + } + +public: + /// @brief What the whole filter says of a row: `No` when any column filter + /// or group says `No`, otherwise `Unknown` when any says `Unknown`, + /// otherwise `Yes`. + /// @param keys Key columns by column index; every index in `columnsUsed()` must be non-null. + /// @param row The row. + /// @return The row's answer. + [[nodiscard]] Match evaluateRow(std::span keys, std::uint32_t row) const { + auto out = Match::Yes; + for (auto const& column : _columns) { + auto const match = evaluate(column, *keys[column.column], row); + if (match == Match::No) { + return Match::No; + } + if (match == Match::Unknown) { + out = Match::Unknown; + } + } + for (auto const& group : _groups) { + auto const match = evaluateGroup(group, keys, row); + if (match == Match::No) { + return Match::No; + } + if (match == Match::Unknown) { + out = Match::Unknown; + } + } + return out; } /// @brief Whether one entry matches one cell. - /// @param entry The entry. - /// @param keys The column's keys. - /// @param row The row. + /// @param entry The entry. + /// @param keys The column's keys. + /// @param row The row. + /// @param counters Counts a value set's lookup when not null. /// @return `true` on a match. - [[nodiscard]] static bool matches(Entry const& entry, KeyColumn const& keys, std::uint32_t row) { + [[nodiscard]] static bool matches(Entry const& entry, KeyColumn const& keys, std::uint32_t row, + FilterCounters* counters = nullptr) { auto const state = keys.states[row]; if (entry.op == Op::IsEmpty) { return state == CellState::Empty; @@ -239,6 +978,9 @@ class CompiledFilter { if (state != CellState::Valid) { return false; } + if (entry.op == Op::OneOf) { + return entry.set != nullptr && entry.set->contains(keys, row, counters); + } switch (keys.kind) { case ColumnKind::Integer: case ColumnKind::Key: @@ -254,6 +996,13 @@ class CompiledFilter { return compare(entry, keys.ints[row], entry.ints); case ColumnKind::Text: return matchText(entry, entry.caseSensitive ? keys.raw[row] : keys.folded[row]); + case ColumnKind::Measure: + // `ne` matches a value of another dimension, which is not equal to the operand; every other + // comparison is false across dimensions, whose amounts do not compare. + if (entry.op == Op::Ne) { + return keys.places[row] != entry.places[0] || !(keys.exact[row] == entry.exact[0]); + } + return keys.places[row] == entry.places[0] && compare(entry, keys.exact[row], entry.exact); case ColumnKind::Custom: default: return false; @@ -263,7 +1012,8 @@ class CompiledFilter { private: friend std::expected compileFilter(FilterSpec const& spec, std::span columns, - Services const& services); + Services const& services, + std::span groups); template [[nodiscard]] static bool compare(Entry const& entry, T const& value, std::array const& operand) { @@ -287,6 +1037,7 @@ class CompiledFilter { case Op::EndsWith: case Op::IsEmpty: case Op::NotEmpty: + case Op::OneOf: default: return false; } @@ -311,6 +1062,7 @@ class CompiledFilter { case Op::Between: case Op::IsEmpty: case Op::NotEmpty: + case Op::OneOf: default: return false; } @@ -367,6 +1119,10 @@ struct RawEntry { ++set; out.op = Op::NotEmpty; } + if (entry.oneOf) { + ++set; + out.op = Op::OneOf; + } if (set != 1) { return std::unexpected(TableError{.code = TableErrorCode::InvalidSpec, .column = std::string{column}, @@ -379,11 +1135,15 @@ struct RawEntry { /// @param kind The column's kind. /// @param op The operator. /// @return `true` when the operator applies to the kind. +// NOLINTNEXTLINE(misc-no-recursion): OneOf is defined as Eq is, one call deep. [[nodiscard]] inline bool operatorDefined(ColumnKind kind, CompiledFilter::Op op) { using Op = CompiledFilter::Op; if (op == Op::IsEmpty || op == Op::NotEmpty) { return true; } + if (op == Op::OneOf) { + return operatorDefined(kind, Op::Eq); + } bool const textOp = op == Op::Contains || op == Op::StartsWith || op == Op::EndsWith; switch (kind) { case ColumnKind::Text: @@ -399,14 +1159,18 @@ struct RawEntry { case ColumnKind::Number: case ColumnKind::Date: case ColumnKind::DateTime: + case ColumnKind::Measure: default: return !textOp; } } /// @brief Parses one operand for the column's kind into a slot of @p entry. +/// +/// A `Measure` operand is a decimal, or a decimal, a space and a unit id (`detail::splitMeasureOperand`); its unit is +/// live in `services.units`, its dimension allowed by the column, and its base amount fits. /// @param info The column. -/// @param services Collator (text is folded with it) and date parser. +/// @param services Collator (text is folded with it), date parser and units. /// @param text The operand text. /// @param slot 0, or 1 for the upper bound of `between`. /// @param entry Receives the parsed operand. @@ -453,17 +1217,93 @@ struct RawEntry { case ColumnKind::Text: entry.text = entry.caseSensitive ? std::string{text} : services.collatorOrDefault()->fold(text); return true; + case ColumnKind::Measure: { + auto const operand = splitMeasureOperand(text); + if (!operand || services.units == nullptr) { + return false; + } + auto const& registry = *services.units; + auto const unit = registry.find(operand->second); + if (!unit) { + return false; + } + auto const place = dimensionPlace(info, registry, registry.info(*unit).dimension); + auto const base = math::checkedMul(operand->first, registry.info(*unit).toBase); + if (place < 0 || !base) { + return false; + } + entry.exact.at(slot) = *base; + entry.places.at(slot) = static_cast(place); + return true; + } case ColumnKind::Custom: default: return false; } } +/// @brief Parses the members of a `oneOf` entry for one column into a set. +/// +/// Each member parses as `eq`'s operand does. On an integer or key column a member that is not a whole number is +/// left out: it can never match, as `eq "1.5"` cannot. +/// @param members The members, as the filter spec gave them. +/// @param info The column. +/// @param services Collator (text is folded with it) and date parser. +/// @param caseSensitive Text members are kept as given. +/// @return The set, or `InvalidValue` naming the column when a member does not parse. +[[nodiscard]] inline std::expected compileValueSet(std::span members, + ColumnInfo const& info, + Services const& services, + bool caseSensitive) { + ValueSet out{info.kind, caseSensitive}; + CompiledFilter::Entry parsed; + parsed.caseSensitive = caseSensitive; + for (auto const& member : members) { + if (!parseOperand(info, services, member, 0, parsed)) { + return std::unexpected( + TableError{.code = TableErrorCode::InvalidValue, + .column = info.id, + .message = "value \"" + member + "\" does not parse for column " + info.id}); + } + switch (info.kind) { + case ColumnKind::Integer: + case ColumnKind::Key: + if (parsed.exact[0].isInteger()) { + out.add(parsed.exact[0]); + } + break; + case ColumnKind::Decimal: + case ColumnKind::Quantity: + out.add(parsed.exact[0]); + break; + case ColumnKind::Number: + out.add(parsed.reals[0]); + break; + case ColumnKind::Date: + case ColumnKind::DateTime: + case ColumnKind::Bool: + out.add(parsed.ints[0]); + break; + case ColumnKind::Text: + out.add(std::move(parsed.text)); + break; + case ColumnKind::Measure: + out.add(parsed.places[0], parsed.exact[0]); + break; + case ColumnKind::Custom: + default: + break; + } + } + return out; +} + /// @brief Compiles one entry for one column. /// @param entry The entry. /// @param info The column. -/// @param services Collator and date parser. -/// @return The compiled entry, or the error naming the column. +/// @param services Collator, date parser and units. +/// @return The compiled entry, or the error naming the column: `SourceContract` for a `Measure` column without a +/// unit registry, and `InvalidValue` for a `between` whose two measure operands are of two dimensions. [[nodiscard]] inline std::expected compileEntry(FilterEntry const& entry, ColumnInfo const& info, Services const& services) { @@ -471,6 +1311,9 @@ struct RawEntry { if (!raw) { return std::unexpected(raw.error()); } + if (auto missing = unitsMissing(info, services)) { + return std::unexpected(std::move(*missing)); + } if (!operatorDefined(info.kind, raw->op)) { return std::unexpected(TableError{.code = TableErrorCode::UnsupportedOperator, .column = info.id, @@ -482,6 +1325,15 @@ struct RawEntry { if (out.op == CompiledFilter::Op::IsEmpty || out.op == CompiledFilter::Op::NotEmpty) { return out; } + if (out.op == CompiledFilter::Op::OneOf) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): an entry whose operator is OneOf carries its values. + auto set = compileValueSet(*entry.oneOf, info, services, out.caseSensitive); + if (!set) { + return std::unexpected(std::move(set.error())); + } + out.set = std::make_shared(std::move(*set)); + return out; + } std::size_t const operands = out.op == CompiledFilter::Op::Between ? 2 : 1; for (std::size_t slot = 0; slot < operands; ++slot) { out.operands.at(slot) = std::string{raw->values.at(slot)}; @@ -492,6 +1344,11 @@ struct RawEntry { "\" does not parse for column " + info.id}); } } + if (info.kind == ColumnKind::Measure && out.op == CompiledFilter::Op::Between && out.places[0] != out.places[1]) { + return std::unexpected(TableError{.code = TableErrorCode::InvalidValue, + .column = info.id, + .message = "a between on column " + info.id + " spans two dimensions"}); + } return out; } @@ -558,66 +1415,229 @@ struct RawEntry { return out; } -/// @brief Compiles a group: per column, the entries that apply to it. +/// @brief Adds a compiled `eq` or `oneOf` entry's values to a group column's value index. +/// @param entry The compiled entry; not case-sensitive. +/// @param raw The entry as the spec gave it (a `oneOf`'s members are parsed again for the index). +/// @param info The column. +/// @param services Collator and date parser. +/// @param bit The entry's bit. +/// @param index The index to add to. +inline void indexEntry(CompiledFilter::Entry const& entry, FilterEntry const& raw, ColumnInfo const& info, + Services const& services, std::uint32_t bit, ValueIndex& index) { + auto const add = [&](CompiledFilter::Entry const& parsed) { + switch (info.kind) { + case ColumnKind::Integer: + case ColumnKind::Key: + if (parsed.exact[0].isInteger()) { + index.add(parsed.exact[0], bit); + } + break; + case ColumnKind::Decimal: + case ColumnKind::Quantity: + index.add(parsed.exact[0], bit); + break; + case ColumnKind::Number: + index.add(parsed.reals[0], bit); + break; + case ColumnKind::Date: + case ColumnKind::DateTime: + case ColumnKind::Bool: + index.add(parsed.ints[0], bit); + break; + case ColumnKind::Text: + index.add(parsed.text, bit); + break; + case ColumnKind::Measure: + index.add(parsed.places[0], parsed.exact[0], bit); + break; + case ColumnKind::Custom: + default: + break; + } + }; + if (entry.op == CompiledFilter::Op::Eq) { + add(entry); + return; + } + CompiledFilter::Entry parsed; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): an entry whose operator is OneOf carries its values. + for (auto const& member : *raw.oneOf) { + if (parseOperand(info, services, member, 0, parsed)) { + add(parsed); + } + } +} + +/// @brief Compiles one side of a group's entries for one column, appending what compiled to @p entries. +/// @param raw The side's entries, as the spec gave them. +/// @param info The column. +/// @param services Collator and date parser. +/// @param appliesTo Per entry, the columns it compiled on so far. +/// @param lastError The latest error of an entry that did not apply to a column. +/// @param entries Receives the compiled entries. +/// @param bits Receives each compiled entry's bit. +/// @param index Receives the values of the compiled `eq` and `oneOf` entries that are not case-sensitive. +/// @param tested Receives the place in @p entries of every other compiled entry. +/// @return Nothing, or an error that is not one column's: `InvalidSpec` for an entry that sets no operator, or +/// several, and `SourceContract` for a column read without what it needs. +[[nodiscard]] inline std::expected compileGroupSide( + std::span raw, ColumnInfo const& info, Services const& services, + std::vector& appliesTo, std::optional& lastError, + std::vector& entries, std::vector& bits, ValueIndex& index, + std::vector& tested) { + for (std::size_t i = 0; i < raw.size(); ++i) { + auto compiled = compileEntry(raw[i], info, services); + if (!compiled) { + if (compiled.error().code == TableErrorCode::InvalidSpec || + compiled.error().code == TableErrorCode::SourceContract) { + return std::unexpected(std::move(compiled.error())); + } + lastError = std::move(compiled.error()); + continue; + } + ++appliesTo[i]; + auto const bit = 1U << i; + bool const byValue = (compiled->op == CompiledFilter::Op::Eq || compiled->op == CompiledFilter::Op::OneOf) && + !compiled->caseSensitive; + if (byValue) { + indexEntry(*compiled, raw[i], info, services, bit, index); + } else { + tested.push_back(entries.size()); + } + bits.push_back(bit); + entries.push_back(std::move(*compiled)); + } + return {}; +} + +/// @brief Compiles a group: per column, the entries that apply to it, and a value index over them. +/// +/// Exactly one of `group` and `columns` names the columns (`InvalidSpec`); `group` resolves through @p groups +/// (`UnknownColumn` naming it) and a column named twice is `InvalidSpec`. `Together` takes 0, or 2 to k, include +/// entries and at most 16 columns; `atLeast` and `exactly` take `0 <= n <= k` (`InvalidSpec`). More than 32 +/// include entries, or 32 exclude entries, is `LimitExceeded`: each side's entries are bits of one 32-bit mask, +/// and the bound is checked here because a filter set on an engine is compiled without a query's limits. In a +/// group, an entry that does not apply to a column (its operator undefined, or its value not parsing, for the +/// column's kind) is left out on that column, and is an error only when it applies to none. /// @param group The group. /// @param columns The table's columns. /// @param services Collator and date parser. -/// @return The compiled group, or an error when a column is unknown, an entry -/// is malformed, or an entry applies to none of the group's columns. -[[nodiscard]] inline std::expected compileGroup(GroupFilter const& group, - std::span columns, - Services const& services) { +/// @param groups The table's declared groups. +/// @return The compiled group, or the first error. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] inline std::expected compileGroup( + GroupFilter const& group, std::span columns, Services const& services, + std::span groups) { + constexpr std::size_t kMaxSide = 32; + constexpr std::size_t kMaxTogether = 16; + auto const invalid = [](std::string message) { + return std::unexpected( + TableError{.code = TableErrorCode::InvalidSpec, .column = {}, .message = std::move(message)}); + }; + if (group.group.empty() == group.columns.empty()) { + return invalid("a filter group names a declared group or its columns"); + } + std::span names = group.columns; + if (!group.group.empty()) { + auto const declared = std::ranges::find(groups, group.group, &ColumnGroupInfo::id); + if (declared == groups.end()) { + return std::unexpected(TableError{.code = TableErrorCode::UnknownColumn, + .column = group.group, + .message = "no column group " + group.group}); + } + names = declared->columns; + } + for (std::size_t i = 0; i < names.size(); ++i) { + if (std::find(names.begin(), names.begin() + static_cast(i), names[i]) != + names.begin() + static_cast(i)) { + return invalid("a filter group names column " + names[i] + " twice"); + } + } + if (group.include.size() > kMaxSide || group.exclude.size() > kMaxSide) { + return std::unexpected(TableError{.code = TableErrorCode::LimitExceeded, + .column = {}, + .message = "a filter group has more than 32 entries on a side"}); + } + auto const k = names.size(); + bool const counted = + group.match.kind == ColumnCount::Kind::AtLeast || group.match.kind == ColumnCount::Kind::Exactly; + if (counted && group.match.n < 0) { + return invalid(R"(a group's match is not "any", "all", {"atLeast": n} or {"exactly": n} with n at least 0)"); + } + if (group.mode == GroupMode::Together) { + if (k > kMaxTogether) { + return invalid("a together group has at most 16 columns"); + } + if (!group.include.empty() && (group.include.size() < 2 || group.include.size() > k)) { + return invalid("a together group takes 2 to as many include entries as it has columns"); + } + } else if (counted && std::cmp_greater(group.match.n, k)) { + return invalid("a group's count is above its column count"); + } CompiledFilter::Group out; - std::vector appliesTo(group.include.size(), 0); + out.k = k; + out.mode = group.mode; + out.match = group.match; + out.combine = group.combine; + out.includeCount = group.include.size(); + out.excludeCount = group.exclude.size(); + std::vector includeApplies(group.include.size(), 0); + std::vector excludeApplies(group.exclude.size(), 0); std::optional lastError; - for (auto const& columnId : group.columns) { - auto const index = findColumn(columns, columnId); - if (!index) { + for (auto const& columnId : names) { + auto const found = findColumn(columns, columnId); + if (!found) { return std::unexpected(unknownColumn(columnId)); } - CompiledFilter::Column column{.column = *index, .combine = group.combine, .include = {}, .exclude = {}}; - for (std::size_t i = 0; i < group.include.size(); ++i) { - auto compiled = compileEntry(group.include[i], columns[*index], services); - if (compiled) { - ++appliesTo[i]; - column.include.push_back(std::move(*compiled)); - } else if (compiled.error().code == TableErrorCode::InvalidSpec) { - return std::unexpected(std::move(compiled.error())); - } else { - lastError = std::move(compiled.error()); - } + auto const& info = columns[*found]; + CompiledFilter::Column column{.column = *found, .combine = group.combine, .include = {}, .exclude = {}}; + CompiledFilter::GroupColumn index{.includeBits = {}, + .excludeBits = {}, + .include = ValueIndex{info.kind}, + .exclude = ValueIndex{info.kind}, + .includeTested = {}, + .excludeTested = {}, + .compiled = 0, + .usable = false}; + if (auto side = compileGroupSide(group.include, info, services, includeApplies, lastError, column.include, + index.includeBits, index.include, index.includeTested); + !side) { + return std::unexpected(std::move(side.error())); } - // With `all`, a column that cannot evaluate every entry cannot - // match; with `any`, one that evaluates none cannot either. - bool const usable = + if (auto side = compileGroupSide(group.exclude, info, services, excludeApplies, lastError, column.exclude, + index.excludeBits, index.exclude, index.excludeTested); + !side) { + return std::unexpected(std::move(side.error())); + } + for (auto const bit : index.includeBits) { + index.compiled |= bit; + } + // With `all`, a column that cannot evaluate every entry cannot satisfy them; with `any`, one that + // evaluates none cannot either. + index.usable = group.combine == Combine::All ? column.include.size() == group.include.size() : !column.include.empty(); - if (usable) { + if (!column.include.empty() || !column.exclude.empty()) { out.columns.push_back(std::move(column)); + out.index.push_back(std::move(index)); } } - if (std::ranges::find(appliesTo, std::size_t{0}) != appliesTo.end()) { - return std::unexpected(lastError.value_or(TableError{ - .code = TableErrorCode::InvalidSpec, .column = {}, .message = "a filter group names no column"})); + auto const unapplied = [](std::vector const& applies) { + return std::ranges::find(applies, std::size_t{0}) != applies.end(); + }; + if (unapplied(includeApplies) || unapplied(excludeApplies)) { + return std::unexpected(lastError.value_or(TableError{.code = TableErrorCode::InvalidSpec, + .column = {}, + .message = "a filter group entry applies to no column"})); } return out; } } // namespace detail -/// @brief Compiles @p spec against @p columns. -/// -/// In a group, an entry whose operator a column's kind does not define, or -/// whose value does not parse for it, does not apply to that column; it is an -/// error only when it applies to none of the group's columns. A quick-search -/// text therefore searches the text columns of a group that also holds numbers. -/// @param spec The filter. -/// @param columns The table's columns. -/// @param services The collator (values of text filters are folded with it) -/// and date parser; null members mean their defaults. -/// @return The compiled filter, or the first error, naming its column. [[nodiscard]] inline std::expected compileFilter(FilterSpec const& spec, std::span columns, - Services const& services) { + Services const& services, + std::span groups) { CompiledFilter out; for (auto const& [columnId, filter] : spec.columns) { auto compiled = detail::compileColumnFilter(columnId, filter, columns, services); @@ -629,11 +1649,11 @@ struct RawEntry { } } for (auto const& group : spec.groups) { - auto compiled = detail::compileGroup(group, columns, services); + auto compiled = detail::compileGroup(group, columns, services, groups); if (!compiled) { return std::unexpected(std::move(compiled.error())); } - if (!group.include.empty()) { + if (!group.include.empty() || !group.exclude.empty()) { out._groups.push_back(std::move(*compiled)); } } @@ -642,19 +1662,21 @@ struct RawEntry { /// @brief `compileFilter`, with an exception from the collator or the date parser returned as `ServiceFailed`. /// -/// The one compile step `apply`, `Engine` and `planQuery` share, so a throwing service is an error value in all three. +/// The one compile step `apply` and `Engine` share, so a throwing service is an error value in both. /// @param spec The filter. /// @param columns The table's columns. /// @param services The collator and date parser; null members mean their defaults. +/// @param groups The table's declared groups. /// @return The compiled filter, or the first error. [[nodiscard]] inline std::expected compileFilterGuarded( - FilterSpec const& spec, std::span columns, Services const& services) { + FilterSpec const& spec, std::span columns, Services const& services, + std::span groups = {}) { auto const failed = [](std::string const& what) { return std::unexpected( TableError{.code = TableErrorCode::ServiceFailed, .column = {}, .message = "a service failed: " + what}); }; try { - return compileFilter(spec, columns, services); + return compileFilter(spec, columns, services, groups); } catch (std::exception const& error) { return failed(error.what()); } catch (...) { @@ -668,6 +1690,10 @@ struct RawEntry { /// Each column filter, then each group, compacts the surviving candidates in /// place, so later columns test fewer rows. The order of the candidates is /// kept, which is how a filter over a cached sorted order stays sorted. +/// +/// A stage that answers `No` drops a row; one that answers `Unknown` keeps it +/// marked, and a later stage may still drop it. The unmarked survivors are the +/// view (`take`), the marked ones the undecided rows (`takeUndecided`). class FilterRun { public: /// @brief Prepares to filter @p candidates. @@ -676,7 +1702,11 @@ class FilterRun { /// `filter.columnsUsed()` must be non-null and outlive the run. /// @param candidates The rows to filter, in the order to keep. FilterRun(CompiledFilter const& filter, std::vector keys, std::vector candidates) - : _filter{&filter}, _keys{std::move(keys)}, _rows{std::move(candidates)}, _size{_rows.size()} {} + : _filter{&filter}, + _keys{std::move(keys)}, + _rows{std::move(candidates)}, + _marks(_rows.size(), std::uint8_t{0}), + _size{_rows.size()} {} /// @brief Filters until done, the deadline passes, or a stop is requested. /// @param deadline When to yield. @@ -689,7 +1719,9 @@ class FilterRun { auto const end = std::min(_read + detail::kCheckEvery, _size); for (; _read < end; ++_read) { auto const row = _rows[_read]; - if (keep(row)) { + auto const match = stage(row); + if (match != Match::No) { + _marks[_write] = match == Match::Unknown ? std::uint8_t{1} : _marks[_read]; _rows[_write++] = row; } } @@ -708,29 +1740,41 @@ class FilterRun { return true; } - /// @brief The surviving rows. Valid once `run` returned `true`. - /// @return The rows, moved out. - [[nodiscard]] std::vector take() && { - _rows.resize(_size); - return std::move(_rows); - } + /// @brief The rows every stage admitted. Valid once `run` returned `true`; + /// may be called once, before or after `takeUndecided`. + /// @return The rows, in candidate order. + [[nodiscard]] std::vector take() && { return survivors(0); } + + /// @brief The rows no stage rejected and some stage could not decide. + /// Valid once `run` returned `true`; may be called once, before or after `take`. + /// @return The rows, in candidate order. + [[nodiscard]] std::vector takeUndecided() && { return survivors(1); } private: - [[nodiscard]] bool keep(std::uint32_t row) const { + [[nodiscard]] Match stage(std::uint32_t row) const { auto const columns = _filter->columns(); if (_stage < columns.size()) { auto const& column = columns[_stage]; - return CompiledFilter::passes(column, *_keys[column.column], row); + return CompiledFilter::evaluate(column, *_keys[column.column], row); } - auto const& group = _filter->groups()[_stage - columns.size()]; - return std::ranges::any_of(group.columns, [&](CompiledFilter::Column const& column) { - return CompiledFilter::passes(column, *_keys[column.column], row); - }); + return CompiledFilter::evaluateGroup(_filter->groups()[_stage - columns.size()], _keys, row); + } + + // The survivors whose mark is `mark`: 0 for the admitted rows, 1 for the undecided ones. + [[nodiscard]] std::vector survivors(std::uint8_t mark) const { + std::vector out; + for (std::size_t i = 0; i < _size; ++i) { + if (_marks[i] == mark) { + out.push_back(_rows[i]); + } + } + return out; } CompiledFilter const* _filter; std::vector _keys; std::vector _rows; + std::vector _marks; // 1 once a stage answered Unknown; compacted with `_rows` std::size_t _size; std::size_t _stage = 0; std::size_t _read = 0; @@ -741,6 +1785,22 @@ class FilterRun { } // namespace morph::table +/// @brief JSON names of `morph::table::GroupMode`: `columns` and `together`. +template <> +struct glz::meta { + using enum morph::table::GroupMode; + /// @brief Each enumerator after its JSON name. + static constexpr auto value = glz::enumerate("columns", Columns, "together", Together); +}; + +/// @brief The JSON of `morph::table::ColumnCount`: `"any"`, `"all"`, `{"atLeast": n}` or `{"exactly": n}`. +template <> +struct glz::meta { + /// @brief Read and written through its wire shape. + static constexpr auto value = + glz::custom<&morph::table::ColumnCount::setWire, &morph::table::ColumnCount::getWire>; +}; + /// @brief JSON names of `morph::table::Combine`: `any` and `all`. template <> struct glz::meta { diff --git a/include/morph/table/level_cache.hpp b/include/morph/table/level_cache.hpp new file mode 100644 index 000000000..0e0f311af --- /dev/null +++ b/include/morph/table/level_cache.hpp @@ -0,0 +1,1932 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file table/level_cache.hpp +/// @brief The server's cache of a slow data level, and the source a reply reads a level through. +/// +/// A `LevelCache` holds the values of one level, as its loader returned them, for every principal. A reply takes +/// one `LevelSnapshot` of each level it needs, reads the level's cells from it through a `LeveledSource`, and +/// then says which keys it needed with `want`; the cache loads the keys it neither holds nor is loading, off the +/// caller's thread, stores them, and announces them so that the clients showing those rows ask again. +/// +/// See `docs/spec/table/table.md`, "The server level cache". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table { + +/// @brief What a level snapshot holds for one key. +enum class LevelRead : std::uint8_t { + Loaded, ///< The value is held; the cells were written. + Unloaded, ///< No value is held: never loaded, invalidated or evicted. + Failed, ///< The last load of the key returned no value. +}; + +/// @brief Why a query needs a level's keys. +enum class LevelUse : std::uint8_t { + Display, ///< The reply shows the keys' cells. + Order, ///< The query sorts or filters by the level, so it needs every candidate row's cells. +}; + +/// @brief One state of a level. Immutable: nothing it returns changes while it lives, and holding it blocks no one. +// NOLINTBEGIN(cppcoreguidelines-special-member-functions) +class LevelSnapshot { +public: + virtual ~LevelSnapshot() = default; + + /// @brief Writes the row's cells for the level's columns, in the order of `LevelSource::columns()`. + /// @param key The row's key. + /// @param out One cell per level column; written only when the value is loaded. + /// @return Whether the value is loaded, unloaded or failed. + [[nodiscard]] virtual LevelRead read(RowId const& key, std::span out) const = 0; + + /// @brief Differs between two snapshots that differ in any value. + /// @return The snapshot's generation. + [[nodiscard]] virtual std::uint64_t generation() const = 0; +}; + +/// @brief What the framework needs of a level, whatever the type of its values. +class LevelSource { +public: + virtual ~LevelSource() = default; + + /// @brief The level's name, as a column's `ColumnInfo::level` names it. + /// @return The name. + [[nodiscard]] virtual std::string_view level() const = 0; + + /// @brief The level's columns. The same for every caller. + /// @return The columns, in the order a snapshot writes a row's cells. + [[nodiscard]] virtual std::span columns() const = 0; + + /// @brief The level as it is now. + /// @return An immutable snapshot. + [[nodiscard]] virtual std::shared_ptr snapshot() const = 0; + + /// @brief Says the keys are needed. + /// @param keys The keys a reply needed. + /// @param use Why: to show them, or to sort or filter by them. + /// @param retry Load the failed keys among @p keys now, without waiting out their retry delay. + /// @return Nothing, or `Unavailable` when an order use cannot fit the cache's bound. + virtual std::expected want(std::span keys, LevelUse use, bool retry = false) = 0; + + /// @brief Says a set of keys the caller keeps is needed: what a cached view wants for its order levels. + /// + /// The set is shared and never changed, so a level may tell from its address that a want repeats one it has + /// served; the default wants its keys as `want` does. + /// @param keys The keys; not null. + /// @param use Display or order. + /// @param retry Load the failed keys among @p keys now. + /// @return Nothing, or `Unavailable` when an order use cannot fit the cache's bound. + virtual std::expected wantSet(std::shared_ptr const> const& keys, + LevelUse use, bool retry = false) { + return want(*keys, use, retry); + } + + /// @brief Takes back an order use's want of @p keys: the leases it gave end now. A reply calls it when a later + /// level refuses its order use, so the earlier levels do not hold rows for a query that was refused. + /// The default does nothing. + /// @param keys The keys an order want named. + virtual void unwant(std::span keys) { static_cast(keys); } +}; +// NOLINTEND(cppcoreguidelines-special-member-functions) + +/// @brief How a `LevelCache` is set up; fixed at construction. +struct LevelCacheOptions { + /// @brief The table records it serves: one, or several that share rows. + std::vector records; + /// @brief The level's name. + std::string level; + /// @brief The level's columns, for every caller, in a fixed order. + std::vector columns; + /// @brief The most bytes the values may own before the least recently used are evicted. + std::size_t maxBytes = 256U << 20U; + /// @brief A value's size before any is stored; 0 takes 64 bytes a column. + std::size_t expectedBytes = 0; + /// @brief Records whose change invalidates values. Empty: `records`. + std::vector invalidatedBy; + /// @brief Where the loader runs; never the server strand. Null runs it on the thread that wants the keys. + exec::IExecutor* loads = nullptr; + /// @brief The most keys handed to one loader call. + std::size_t batch = 64; + /// @brief How long an order use keeps its keys from eviction. + std::chrono::seconds orderLease{60}; + /// @brief How long a failed key waits before it is loaded again; doubles with each failure in a row. + std::chrono::seconds retryAfter{30}; + /// @brief The longest a failed key waits. + std::chrono::seconds retryMax{600}; + /// @brief The cache's "now". Empty: the steady clock. + std::function clock; + /// @brief The unit registry the loader's measures are numbered in now. Empty: the level holds no measures. + /// Values are kept under a successor of the registry they were loaded with, whose numbers mean the same, + /// and dropped when a registry of another lineage is in place. Called from any thread that wants keys, + /// stores a load or takes a snapshot, with no lock held, so it must be safe to call concurrently with + /// whatever swaps the registry. + std::function()> units; +}; + +/// @brief What a `LevelCache` has done since it was made; `bytes` is what it holds now. +struct LevelCacheStats { + /// @brief Keys a `want` found held. + std::size_t hits = 0; + /// @brief Keys a `want` found not held. + std::size_t misses = 0; + /// @brief Calls of the loader. + std::size_t loaderCalls = 0; + /// @brief Keys stored from a loader's return. + std::size_t loadedKeys = 0; + /// @brief Keys a loader call returned no value for, or that a throwing call failed. + std::size_t failedLoads = 0; + /// @brief Keys a load returned after an invalidation of them, and that were dropped. + std::size_t droppedLoads = 0; + /// @brief Held keys (values or failures) an invalidation removed. + std::size_t invalidatedKeys = 0; + /// @brief Values evicted at the bound. + std::size_t evictedKeys = 0; + /// @brief Keys an accepted order use leased. + std::size_t leasedKeys = 0; + /// @brief Order uses refused because they could not fit. + std::size_t refusedOrders = 0; + /// @brief The deep bytes of the values and failures held now, and of the keys of the order sets accepted. + std::size_t bytes = 0; +}; + +template +class LevelCache; + +namespace detail { + +/// @brief The fewest shards a level cache spreads its keys over. +inline constexpr std::size_t kMinLevelShards = 16; + +/// @brief The most entries a level cache's shard averages: the shard count, a power of two, doubles past it. +inline constexpr std::size_t kRowsPerShard = 64; + +/// @brief The most keys a `want` takes under the cache's writer mutex at once; the mutex is released between such +/// chunks, so an invalidation waits for one chunk of a large want at most. +inline constexpr std::size_t kWantChunk = 1024; + +/// @brief A cell vector's deep size: the vector, and what each cell owns. +/// @param cells The cells. +/// @return The bytes. +[[nodiscard]] MORPH_API std::size_t cellsBytes(std::vector const& cells) noexcept; + +/// @brief What fixtures and benchmarks reach of a `LevelCache` beyond its interface. +struct LevelCacheAccess { + /// @brief Stores @p values as a load would, without a loader call and without announcing them. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @param values The values by key. + template + static void store(LevelCache& cache, std::vector> values) { + cache._core->storeQuietly(std::move(values)); + } + + /// @brief How many shards stores, removals and observer calls have copied. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @return The count. + template + [[nodiscard]] static std::size_t shardCopies(LevelCache const& cache) { + return cache._core->shardCopies.load(); + } + + /// @brief How many keys wait on the cache's queues. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @return The count. + template + [[nodiscard]] static std::size_t queuedEntries(LevelCache const& cache) { + return cache._core->queuedEntries(); + } + + /// @brief How many shards the cache's published state has. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @return The count, a power of two. + template + [[nodiscard]] static std::size_t shardCount(LevelCache const& cache) { + return cache._core->shardCount(); + } + + /// @brief How many order uses have been fitted: every order `want`, and every order `wantSet` that did not + /// repeat a set accepted within its lease. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @return The count. + template + [[nodiscard]] static std::size_t fits(LevelCache const& cache) { + return cache._core->fits.load(); + } + + /// @brief Sets what `unwant` calls before each chunk of its keys, with no lock held. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @param hook The call, given the index of the chunk about to be taken; empty for none. + template + static void onReleaseChunk(LevelCache& cache, std::function hook) { + cache._core->releaseHook = std::move(hook); + } + + /// @brief Sets what a store calls between preparing its state and publishing it, with no lock held. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @param hook The call; empty for none. Set before any load runs. + template + static void onStorePrepared(LevelCache& cache, std::function hook) { + cache._core->storeHook = std::move(hook); + } + + /// @brief Sets what a want calls before each chunk of its keys, with no lock held: after an order use's fit and + /// before the first chunk, then between chunks. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @param hook The call, given the index of the chunk about to be taken; empty for none. Set before any want. + template + static void onWantChunk(LevelCache& cache, std::function hook) { + cache._core->wantHook = std::move(hook); + } + + /// @brief The end of a held value's order lease. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @param key The key. + /// @return The lease's end in clock ticks; 0 when the key is not held or its value has no lease. + template + [[nodiscard]] static std::int64_t leaseEnd(LevelCache const& cache, RowId const& key) { + auto const slot = LevelCache::findIn(*cache._core->publishedTable(), key); + return slot != nullptr ? slot->leaseUntil.load() : 0; + } + + /// @brief Whether a held key is kept from eviction by an order use: its own lease, or an accepted set. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @param key The key. + /// @return Whether the key is held and kept. + template + [[nodiscard]] static bool kept(LevelCache const& cache, RowId const& key) { + auto const slot = LevelCache::findIn(*cache._core->publishedTable(), key); + auto const nowTicks = cache._core->now().time_since_epoch().count(); + return slot != nullptr && LevelCache::Core::kept(*slot, nowTicks); + } + + /// @brief How many order sets the cache has accepted and not ended. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @return The count. + template + [[nodiscard]] static std::size_t acceptedSets(LevelCache const& cache) { + std::scoped_lock const lock{cache._core->writer}; + return cache._core->sets.size(); + } + + /// @brief Whether a key not held yet has an order lease waiting for its store. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @param key The key. + /// @return Whether the cache keeps a pending lease for @p key. + template + [[nodiscard]] static bool leasePending(LevelCache const& cache, RowId const& key) { + std::scoped_lock const lock{cache._core->writer}; + return cache._core->pendingLeases.contains(key); + } + + /// @brief Sets what each eviction scan calls first, with no lock held: how a test pauses a store mid-eviction. + /// @tparam Value The cache's value type. + /// @param cache The cache. + /// @param hook The call; empty for none. Set before any load runs. + template + static void onEvictionScan(LevelCache& cache, std::function hook) { + cache._core->evictionHook = std::move(hook); + } +}; + +} // namespace detail + +/// @brief The server's cache of one slow level: values loaded once, kept until invalidated or evicted, read by +/// every principal through immutable snapshots. +/// +/// The values live in shards by key hash, each an immutable sorted vector behind a shared pointer; the shard +/// count is a power of two that doubles as the cache grows, so a shard averages at most `detail::kRowsPerShard` +/// entries. A published state is the shard pointers and a generation behind one shared pointer, and a snapshot +/// holds it. A store, a removal, an eviction and an observer call prepare their new state from the published one +/// with no lock held: the shard copies, the scans and sorts, the re-spread. They then take a writer mutex only to +/// check that nothing was published meanwhile (and prepare again if it was) and to publish, under a second mutex +/// held for the pointer swap alone. So neither a reader nor the server strand's observer call waits behind +/// another change's slow work. A `want` takes its keys a chunk at a time under the writer mutex, so a change waits +/// for one chunk of it at most. A value's recency and order lease are atomics beside it, and neither is part of a +/// snapshot's state. +/// +/// The application's callbacks (the sink, the failure handler, `sizeOf`, `loads->post`) may throw: a throw is +/// logged, a key whose size could not be read is stored as failed, and a batch that could not be posted goes back +/// on the queue, so no callback stops the level from loading. +/// +/// One loader call runs at a time. Wanted keys wait on two queues, `Display` before `Order`, each ordered by the +/// newest want first and, inside one want, in the order given; a key is queued once, and a want of a queued key +/// moves it to that want's place. A batch takes up to `batch` keys from the front. A +/// load remembers each key's generation and stores only the keys no invalidation touched meanwhile; it publishes +/// the values, then announces their keys to every record in `records`. +/// @tparam Value What the loader returns for one key. +template +class LevelCache final : public LevelSource, public effects::IChangeObserver { +public: + /// @brief Reads the level for `keys`. Called on `options.loads`; may block. It returns a value for every key it + /// read, including a row that has nothing at this level, whose value is then empty. A key it returns no + /// value for failed; throwing fails every key of the call. + using Loader = std::function>(std::span keys)>; + /// @brief A value's deep bytes. + using SizeOf = std::function; + /// @brief Writes a value's cells, in `LevelCacheOptions::columns` order. + using Cells = std::function out)>; + + /// @brief A cache of @p options' level. + /// @param options How it is bounded, batched and invalidated. + /// @param loader Reads values. + /// @param sizeOf A value's deep bytes. + /// @param cells A value's cells. + LevelCache(LevelCacheOptions options, Loader loader, SizeOf sizeOf, Cells cells) + : _core{std::make_shared(std::move(options), std::move(loader), std::move(sizeOf), std::move(cells))} {} + + /// @brief For `Value` = `std::vector` only: the value is the cells, and its size is their deep size. + /// @param options How it is bounded, batched and invalidated. + /// @param loader Reads values. + LevelCache(LevelCacheOptions options, Loader loader) + requires std::same_as> + : LevelCache{std::move(options), std::move(loader), + [](std::vector const& value) { return detail::cellsBytes(value); }, + [](std::vector const& value, std::span out) { + auto const count = std::min(value.size(), out.size()); + std::copy_n(value.begin(), count, out.begin()); + std::fill(out.begin() + static_cast(count), out.end(), Cell{}); + }} {} + + /// @brief The level's name. + /// @return `LevelCacheOptions::level`. + [[nodiscard]] std::string_view level() const override { return _core->options.level; } + + /// @brief The level's columns. + /// @return `LevelCacheOptions::columns`. + [[nodiscard]] std::span columns() const override { return _core->options.columns; } + + /// @brief The values held now. + /// + /// When `LevelCacheOptions::units` gives a registry of another lineage than the one the values were loaded + /// with, every value is invalidated first (`invalidateAll`, counted in `invalidatedKeys`): their unit numbers mean + /// nothing under it. A `want` checks the same before it queues keys. + /// @return An immutable snapshot: the shard pointers and the generation, copied under the mutex. + [[nodiscard]] std::shared_ptr snapshot() const override { + _core->checkLineage(); + return _core->snapshot(); + } + + /// @brief Says the keys are needed, and starts a load for those neither held, in flight, queued, nor failed + /// inside their retry delay. + /// + /// A held key is a hit and its recency is renewed. An order use is first fitted: the keys times the mean + /// size of the values held (`expectedBytes` while none is), plus the bytes other keys' leases hold, against + /// `maxBytes`; over it nothing changes. Otherwise every key is leased for `orderLease`, and the use is one more + /// holder of each lease. The keys are taken `detail::kWantChunk` at a time under the writer mutex, each key + /// classified, leased and queued at once, and the mutex is released between chunks. + /// @param keys The keys. + /// @param use Display or order. + /// @param retry Load the failed keys among @p keys now. + /// @return Nothing, or `Unavailable` for an order use that does not fit. + std::expected want(std::span keys, LevelUse use, bool retry = false) override { + _core->checkLineage(); + return Core::want(_core, keys, use, retry, Core::Pass::Lease); + } + + /// @brief Says a kept set of keys is needed. An order use of a set, unretried, is held by the set: the first is + /// fitted and protects every key of the set from eviction in one pass; a repeat while the set's lease + /// runs is one more holder of the set and extends its lease, without touching a key, unless a protected + /// key was removed or a protected failure's delay has passed, when it also queues what the set misses. + /// An order use of a set whose fitting `want` another call is running waits for that call first. + /// Anything else is `want`. + /// @param keys The keys; not null. + /// @param use Display or order. + /// @param retry Load the failed keys among @p keys now. + /// @return Nothing, or `Unavailable` for an order use that does not fit. + std::expected wantSet(std::shared_ptr const> const& keys, LevelUse use, + bool retry = false) override { + _core->checkLineage(); + return Core::wantSet(_core, keys, use, retry); + } + + /// @brief Takes back an order use's want of @p keys. Of a kept set, it is one holder fewer, and the set's + /// protection of its keys ends with its last holder; of other keys, it ends one holder's lease of each, + /// and a lease ends with its last holder. + /// @param keys The keys. + void unwant(std::span keys) override { _core->release(keys); } + + /// @brief Drops what @p changes made wrong. On the server strand; removes only. + /// + /// A change of a record in `invalidatedBy` that is one of `records` invalidates its keys, or the level when + /// it has none or a key that is no row key. A change of any other record in `invalidatedBy` invalidates the + /// level and announces each of `records` without keys. + /// @param changes One fan-out's changes. + void changed(effects::Changes const& changes) override { _core->changed(changes); } + + /// @brief Takes the server's announce sink. + /// @param sink Where arrivals, failures and invalidations of the cache's own are reported. + void bind(effects::AnnounceSink sink) override { + std::scoped_lock const lock{_core->writer}; + _core->sink = std::move(sink); + } + + /// @brief Removes the values and failures of @p keys; a load of them in flight does not land. + /// @param keys The keys. + void invalidate(std::span keys) { _core->invalidate(keys); } + + /// @brief Removes every value and failure; no load in flight lands. + void invalidateAll() { _core->invalidateAll(); } + + /// @brief Sets what is called with the keys of each load that failed, after they are stored as failed. + /// @param handler The handler; called on the loading thread. + void onLoadFailed(std::function)> handler) { + std::scoped_lock const lock{_core->writer}; + _core->failedHandler = std::move(handler); + } + + /// @brief The counters. + /// @return What the cache has done, and the bytes it holds. + [[nodiscard]] LevelCacheStats stats() const { return _core->stats(); } + +private: + friend struct detail::LevelCacheAccess; + + using Clock = std::chrono::steady_clock; + + struct Slot { + std::optional value; // empty: the load failed + std::uint32_t failures = 0; + Clock::time_point failedAt; + std::size_t bytes = 0; // a value's deep bytes; a failure's own size + mutable std::atomic lastUse{0}; + mutable std::atomic leaseUntil{0}; // clock ticks; 0: no lease + mutable std::atomic leaseHolders{0}; // the order uses holding the lease + mutable std::atomic setHolds{0}; // the accepted sets protecting the key + }; + using SlotPtr = std::shared_ptr; + using Entry = std::pair; + using Shard = std::vector; // sorted by key + + // One published state: the shards, a power of two of them, the generation and the entry count. + struct Table { + std::vector> shards; + std::uint64_t generation = 0; + std::size_t entries = 0; + }; + + [[nodiscard]] static std::size_t shardOf(RowId const& key, std::size_t count) noexcept { + return std::hash{}(key) & (count - 1); + } + + [[nodiscard]] static SlotPtr findIn(Shard const& shard, RowId const& key) { + auto const found = std::ranges::lower_bound(shard, key, {}, &Entry::first); + return found != shard.end() && found->first == key ? found->second : nullptr; + } + + [[nodiscard]] static SlotPtr findIn(Table const& table, RowId const& key) { + return findIn(*table.shards[shardOf(key, table.shards.size())], key); + } + + class Snapshot final : public LevelSnapshot { + public: + Snapshot(std::shared_ptr
table, std::shared_ptr cells) + : _table{std::move(table)}, _cells{std::move(cells)} {} + + [[nodiscard]] LevelRead read(RowId const& key, std::span out) const override { + auto const slot = findIn(*_table, key); + if (slot == nullptr) { + return LevelRead::Unloaded; + } + if (!slot->value) { + return LevelRead::Failed; + } + (*_cells)(*slot->value, out); + return LevelRead::Loaded; + } + + [[nodiscard]] std::uint64_t generation() const override { return _table->generation; } + + private: + std::shared_ptr
_table; + std::shared_ptr _cells; + }; + + // A key handed to a loader call: the level epoch and the sequence number its load started at. + struct Loading { + RowId key; + std::uint64_t epoch = 0; + std::uint64_t started = 0; + }; + + struct Queued { + LevelUse use = LevelUse::Display; + std::uint64_t priority = 0; + }; + + // A change prepared against one published state with no lock held: the shards it touches, copied once each, + // and each slot it replaces or removes, for the accounting done when it is published. + class Edit { + public: + Edit(Table const& base, std::atomic& copies) : _base{&base}, _copies{&copies} {} + + [[nodiscard]] SlotPtr find(RowId const& key) const { + auto const index = shardOf(key, _base->shards.size()); + if (auto const copied = _copied.find(index); copied != _copied.end()) { + return findIn(*copied->second, key); + } + return findIn(*_base->shards[index], key); + } + + void put(RowId const& key, SlotPtr slot) { + auto& shard = copy(key); + auto const found = std::ranges::lower_bound(shard, key, {}, &Entry::first); + if (found != shard.end() && found->first == key) { + changes.emplace_back(found->second, slot); + found->second = std::move(slot); + } else { + changes.emplace_back(nullptr, slot); + shard.insert(found, Entry{key, std::move(slot)}); + ++_added; + } + } + + void erase(RowId const& key) { + auto& shard = copy(key); + auto const found = std::ranges::lower_bound(shard, key, {}, &Entry::first); + if (found != shard.end() && found->first == key) { + changes.emplace_back(found->second, nullptr); + shard.erase(found); + ++_removed; + } + } + + [[nodiscard]] bool changed() const noexcept { return !_copied.empty(); } + + // The base with the copied shards in; the shard count doubles until a shard averages at most + // `detail::kRowsPerShard` entries. Built with no lock held. + [[nodiscard]] std::shared_ptr
table() const { + auto out = std::make_shared
(); + out->generation = _base->generation + 1; + out->entries = _base->entries + _added - _removed; + out->shards = _base->shards; + for (auto const& [index, shard] : _copied) { + out->shards[index] = shard; + } + auto count = out->shards.size(); + while (out->entries > detail::kRowsPerShard * count) { + count *= 2; + } + if (count != out->shards.size()) { + std::vector spread(count); + for (auto const& shard : out->shards) { + for (auto const& entry : *shard) { + spread[shardOf(entry.first, count)].push_back(entry); + } + } + out->shards.clear(); + out->shards.reserve(count); + for (auto& shard : spread) { + std::ranges::sort(shard, {}, &Entry::first); + out->shards.push_back(std::make_shared(std::move(shard))); + } + } + return out; + } + + // (old, new) per changed key; null for none. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes): read by the cache when it publishes the edit. + std::vector> changes; + + private: + Shard& copy(RowId const& key) { + auto const index = shardOf(key, _base->shards.size()); + auto& copied = _copied[index]; + if (copied == nullptr) { + copied = std::make_shared(*_base->shards[index]); + _copies->fetch_add(1); + } + return *copied; + } + + Table const* _base; + std::atomic* _copies; + std::unordered_map> _copied; + std::size_t _added = 0; + std::size_t _removed = 0; + }; + + // What a store leaves to be done outside the mutex. + struct Told { + effects::AnnounceSink sink; + std::function)> failedHandler; + std::vector stored; + std::vector failed; + bool overBound = false; + }; + + struct Core { + Core(LevelCacheOptions opts, Loader load, SizeOf size, Cells cellsOf) + : options{std::move(opts)}, + loader{std::move(load)}, + sizeOf{std::move(size)}, + cells{std::make_shared(std::move(cellsOf))} { + if (options.invalidatedBy.empty()) { + options.invalidatedBy = options.records; + } + if (options.batch == 0) { + options.batch = 1; + } + current = emptyTable(0); + published = current; + } + + [[nodiscard]] static std::shared_ptr
emptyTable(std::uint64_t generation) { + auto out = std::make_shared
(); + out->generation = generation; + auto const empty = std::make_shared(); + out->shards.assign(detail::kMinLevelShards, empty); + return out; + } + + [[nodiscard]] Clock::time_point now() const { return options.clock ? options.clock() : Clock::now(); } + + // The clock, or the epoch when the clock throws: a failure's time is then already past its delay. + [[nodiscard]] Clock::time_point nowOrEpoch() const noexcept { + try { + return now(); + } catch (...) { + return Clock::time_point{}; + } + } + + [[nodiscard]] static std::int64_t ticks(Clock::time_point when) noexcept { + return when.time_since_epoch().count(); + } + + [[nodiscard]] Clock::duration retryDelay(std::uint32_t failures) const { + // Doubled one step at a time and stopped at the ceiling: a delay doubled in one multiplication by 2^30 + // overflows the clock's tick count, and a wrapped delay is negative, so no failure would wait at all. + Clock::duration delay = options.retryAfter; + for (std::uint32_t doubled = 1; doubled < failures && delay < options.retryMax; ++doubled) { + delay *= 2; + } + return std::min(delay, options.retryMax); + } + + [[nodiscard]] std::size_t meanBytes() const { + if (values > 0) { + return valueBytes / values; + } + return options.expectedBytes != 0 ? options.expectedBytes : 64 * options.columns.size(); + } + + [[nodiscard]] std::shared_ptr
publishedTable() const { + std::scoped_lock const lock{publishMutex}; + return published; + } + + // Under the writer mutex: publishes a prepared table and accounts for its changes; the publish mutex is + // held for the pointer swap alone. + void publish(std::shared_ptr
next, Edit const& edit) { + for (auto const& [old, slot] : edit.changes) { + forget(old.get()); + if (slot != nullptr) { + remember(*slot); + } + } + { + std::scoped_lock const lock{publishMutex}; + published = next; + } + current = std::move(next); + ++version; + } + + [[nodiscard]] std::shared_ptr snapshot() const { + return std::make_shared(publishedTable(), cells); + } + + // ── The queue ── + // Each use's queue is ordered by priority, the newest want highest and, inside one want, its first key + // highest. A key is queued once; a want of a queued key gives it the want's priority, so the keys a user + // asks for again come first. A key queued for display stays there when wanted for order. + + void enqueue(RowId const& key, LevelUse use, std::uint64_t priority) { + auto const found = queued.find(key); + if (found != queued.end()) { + if (found->second.use == LevelUse::Display && use == LevelUse::Order) { + return; + } + queues.at(static_cast(found->second.use)).erase(found->second.priority); + } + queued.insert_or_assign(key, Queued{.use = use, .priority = priority}); + queues.at(static_cast(use)).emplace(priority, key); + } + + // The priority of the `index`-th key of the next want. + [[nodiscard]] std::uint64_t priorityOf(std::uint64_t want, std::size_t index) const noexcept { + return (want << 32U) | (0xFFFF'FFFFULL - (static_cast(index) & 0xFFFF'FFFFULL)); + } + + // Under the writer mutex: the next batch, display first, highest priority first, its keys marked in flight. + [[nodiscard]] std::vector takeBatch() { + std::vector out; + auto const started = ++sequence; + for (auto const use : {LevelUse::Display, LevelUse::Order}) { + auto& queue = queues.at(static_cast(use)); + while (out.size() < options.batch && !queue.empty()) { + auto const top = std::prev(queue.end()); + auto key = std::move(top->second); + queue.erase(top); + queued.erase(key); + inFlight.insert_or_assign(key, std::pair{epoch, started}); + out.push_back(Loading{.key = std::move(key), .epoch = epoch, .started = started}); + } + } + running = !out.empty(); + return out; + } + + [[nodiscard]] bool inFlightNow(RowId const& key) const { + auto const found = inFlight.find(key); + if (found == inFlight.end() || found->second.first != epoch) { + return false; + } + auto const invalidated = invalidatedAt.find(key); + return invalidated == invalidatedAt.end() || invalidated->second < found->second.second; + } + + [[nodiscard]] bool stillCurrent(Loading const& loading) const { + if (loading.epoch != epoch) { + return false; + } + auto const invalidated = invalidatedAt.find(loading.key); + return invalidated == invalidatedAt.end() || invalidated->second < loading.started; + } + + // ── want ── + + // An order set the cache accepted, by address: the set, held so that its address names it, the order uses + // holding it, its lease's end, the value of `setEvents` it last looked at its keys for, the level's + // generation it was last wanted at, and the bytes its keys own. While the lease runs and a use holds it, + // its keys are protected. + struct AcceptedSet { + std::shared_ptr const> keys; + std::int32_t holders = 0; + std::int64_t until = 0; + std::uint64_t seenEvents = 0; + std::uint64_t generation = 0; + std::size_t bytes = 0; + }; + + // The bytes a set's keys own, counted in the bound while the set is accepted. + [[nodiscard]] static std::size_t setBytesOf(std::span keys) noexcept { + auto out = sizeof(std::vector); + for (auto const& key : keys) { + out += rowIdBytes(key); + } + return out; + } + + // Under the writer mutex: takes a set out of the accepted sets and out of the bound; the caller unprotects + // its keys. + AcceptedSet takeSet(std::unordered_map const*, AcceptedSet>::iterator found) { + auto out = std::move(found->second); + sets.erase(found); + setBytes -= std::min(setBytes, out.bytes); + storeBytes(); + return out; + } + + // How a want's pass treats an order key: a lease of its own, or protection by an accepted set. + enum class Pass : std::uint8_t { Lease, Protect }; + + // Ends a set's single flight: wakes the repeats that wait for it. + class Settling { + public: + Settling(Core& core, std::vector const* set) : _core{core}, _set{set} {} + Settling(Settling const&) = delete; + Settling& operator=(Settling const&) = delete; + Settling(Settling&&) = delete; + Settling& operator=(Settling&&) = delete; + ~Settling() { + { + std::scoped_lock const lock{_core.writer}; + _core.settling.erase(_set); + } + _core.setSettled.notify_all(); + } + + private: + Core& _core; + std::vector const* _set; + }; + + // An order use of a kept set. The first, fitted, protects every key of the set in one chunked pass; a + // repeat while the set's lease runs is one more holder and a longer lease, under the lock, and touches no + // key unless `setEvents` has moved since the set last looked (a protected key removed, a protected + // failure's delay passed), when it queues the keys the set misses. A fit also ends the accepted sets that + // no use has wanted since the level's generation moved past theirs: a view is found only at its level's + // generation, so such a set's view is superseded. + static std::expected wantSet(std::shared_ptr const& core, + std::shared_ptr const> const& keys, + LevelUse use, bool retry) { + if (use != LevelUse::Order || retry) { + return want(core, *keys, use, retry, Pass::Lease); + } + auto const* const set = keys.get(); + auto const instant = core->now(); + auto const nowTicks = ticks(instant); + auto const until = ticks(instant + core->options.orderLease); + core->endExpiredSets(nowTicks); + std::optional lapsed; + std::uint64_t events = 0; + { + std::unique_lock lock{core->writer}; + // A fitting want of this same set runs: wait for it, so that a repeat learns whether it was + // accepted rather than fit the same keys again beside it. + core->setSettled.wait(lock, [&] { return !core->settling.contains(set); }); + if (auto const found = core->sets.find(set); found != core->sets.end()) { + if (found->second.until > nowTicks) { + ++found->second.holders; + found->second.until = std::max(found->second.until, until); + found->second.generation = core->current->generation; + core->hits.fetch_add(keys->size()); + if (nowTicks >= core->setsRecheckAt) { + // A protected failure's delay has passed: an event every set sees once. + ++core->setEvents; + core->setsRecheckAt = std::numeric_limits::max(); + } + if (found->second.seenEvents == core->setEvents) { + return {}; + } + found->second.seenEvents = core->setEvents; + lock.unlock(); + core->requeue(core, *keys, instant); + return {}; + } + lapsed = core->takeSet(found); + } + core->settling.insert(set); + events = core->setEvents; + } + auto const bytes = setBytesOf(*keys); + std::vector superseded; + std::expected wanted; + { + Settling const settling{*core, set}; + if (lapsed) { + core->unprotect(*lapsed->keys); + } + wanted = want(core, *keys, use, retry, Pass::Protect, bytes); + if (wanted) { + std::scoped_lock const lock{core->writer}; + auto const generation = core->current->generation; + for (auto entry = core->sets.begin(); entry != core->sets.end();) { + auto const next = std::next(entry); + if (entry->second.generation < generation) { + superseded.push_back(core->takeSet(entry)); + } + entry = next; + } + core->sets.insert_or_assign(set, AcceptedSet{.keys = keys, + .holders = 1, + .until = until, + .seenEvents = events, + .generation = generation, + .bytes = bytes}); + core->setBytes += bytes; + core->storeBytes(); + } + } + // After the new set protects its keys, so that a key both sets hold is never unprotected between, and + // after the repeats waiting for the set are woken, so that none waits for this pass. + for (auto const& old : superseded) { + core->unprotect(*old.keys); + } + return wanted; + } + + // An order use is fitted first against the published state with no lock held: the fit is an estimate. + // The keys are then taken a chunk of `detail::kWantChunk` at a time under the writer mutex, which is + // released between chunks, so an invalidation or a store waits for one chunk at most. Inside a chunk a + // key is classified, leased or protected, and queued at once: a held key's slot is marked where an + // eviction's publish check sees it, and a key not held gets a pending lease, or a protection count, that + // its store moves onto its slot. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + static std::expected want(std::shared_ptr const& core, std::span keys, + LevelUse use, bool retry, Pass pass, std::size_t keyBytes = 0) { + auto const instant = core->now(); + auto const nowTicks = ticks(instant); + auto const until = ticks(instant + core->options.orderLease); + if (use == LevelUse::Order) { + core->fits.fetch_add(1); + if (auto fitted = core->fitOrder(keys, nowTicks, keyBytes); !fitted) { + return fitted; + } + } + auto const protect = use == LevelUse::Order && pass == Pass::Protect; + std::uint64_t want = 0; + std::size_t hit = 0; + std::vector batch; + for (std::size_t first = 0;; first += detail::kWantChunk) { + if (core->wantHook) { + core->wantHook(first / detail::kWantChunk); + } + std::scoped_lock const lock{core->writer}; + if (first == 0) { + want = ++core->wants; + } + auto const& table = *core->current; + auto const last = std::min(keys.size(), first + detail::kWantChunk); + for (auto index = first; index < last; ++index) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < last <= keys.size() + auto const& key = keys[index]; + auto const slot = findIn(table, key); + if (protect) { + auto const count = ++core->protectedKeys[key]; + if (slot != nullptr) { + slot->setHolds.store(count); + } + } + if (slot != nullptr && slot->value) { + ++hit; + slot->lastUse.store(core->useCounter.fetch_add(1) + 1); + if (use == LevelUse::Order && !protect) { + lease(*slot, until, nowTicks); + } + continue; + } + if (slot != nullptr && !retry && instant < slot->failedAt + core->retryDelay(slot->failures)) { + if (protect) { + core->recheckAt(slot->failedAt + core->retryDelay(slot->failures)); + } + continue; + } + if (use == LevelUse::Order && !protect) { + auto& pending = core->pendingLeases[key]; + pending.holders = pending.until > nowTicks ? pending.holders + 1 : 1; + pending.until = std::max(pending.until, until); + } + if (!core->inFlightNow(key)) { + core->enqueue(key, use, core->priorityOf(want, index)); + } + } + if (last == keys.size()) { + if (!core->running) { + batch = core->takeBatch(); + } + break; + } + } + core->hits.fetch_add(hit); + core->misses.fetch_add(keys.size() - hit); + if (use == LevelUse::Order) { + core->leasedKeys.fetch_add(keys.size()); + } + dispatch(core, std::move(batch)); + return {}; + } + + // Under the writer mutex: a repeat of an accepted set must look at its keys again once `at` has passed. + void recheckAt(Clock::time_point when) { setsRecheckAt = std::min(setsRecheckAt, ticks(when)); } + + // Queues the keys of an accepted set that are neither held, in flight, nor failed inside their delay, a + // chunk at a time under the writer mutex. Their protection is kept by key, so it needs no change. + static void requeue(std::shared_ptr const& core, std::span keys, Clock::time_point when) { + std::uint64_t want = 0; + std::vector batch; + for (std::size_t first = 0;; first += detail::kWantChunk) { + std::scoped_lock const lock{core->writer}; + if (first == 0) { + want = ++core->wants; + } + auto const& table = *core->current; + auto const last = std::min(keys.size(), first + detail::kWantChunk); + for (auto index = first; index < last; ++index) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < last <= keys.size() + auto const& key = keys[index]; + auto const slot = findIn(table, key); + if (slot != nullptr && slot->value) { + continue; + } + if (slot != nullptr && when < slot->failedAt + core->retryDelay(slot->failures)) { + core->recheckAt(slot->failedAt + core->retryDelay(slot->failures)); + continue; + } + if (!core->inFlightNow(key)) { + core->enqueue(key, LevelUse::Order, core->priorityOf(want, index)); + } + } + if (last == keys.size()) { + if (!core->running) { + batch = core->takeBatch(); + } + break; + } + } + dispatch(core, std::move(batch)); + } + + // Takes one protection of each key away, a chunk at a time under the writer mutex; a held key's slot keeps + // the count its key has. + void unprotect(std::span keys) { + for (std::size_t first = 0; first < keys.size(); first += detail::kWantChunk) { + if (releaseHook) { + releaseHook(first / detail::kWantChunk); + } + std::scoped_lock const lock{writer}; + auto const last = std::min(keys.size(), first + detail::kWantChunk); + for (auto index = first; index < last; ++index) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < last <= keys.size() + auto const& key = keys[index]; + auto const found = protectedKeys.find(key); + if (found == protectedKeys.end()) { + continue; + } + auto const count = --found->second; + if (count <= 0) { + protectedKeys.erase(found); + } + if (auto const slot = findIn(*current, key); slot != nullptr) { + slot->setHolds.store(std::max(count, 0)); + } + } + } + } + + // Ends the accepted sets whose lease has run out, and their protection. + void endExpiredSets(std::int64_t nowTicks) { + std::vector expired; + { + std::scoped_lock const lock{writer}; + for (auto entry = sets.begin(); entry != sets.end();) { + auto const next = std::next(entry); + if (entry->second.until <= nowTicks) { + expired.push_back(takeSet(entry)); + } + entry = next; + } + } + for (auto const& set : expired) { + unprotect(*set.keys); + } + } + + // Whether an order use of `keys` fits: the keys times the mean value size, plus the bytes leased or + // protected for keys other than these, plus the accepted sets' key bytes and `keyBytes`, what the use's own + // set of keys will hold, against `maxBytes`. Read from the published state with no lock held. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): a time in ticks, then a byte count, in the order the names read. + [[nodiscard]] std::expected fitOrder(std::span keys, std::int64_t nowTicks, + std::size_t keyBytes) { + std::shared_ptr
base; + std::size_t mean = 0; + std::size_t setsHeld = 0; + { + std::scoped_lock const lock{writer}; + base = current; + mean = meanBytes(); + setsHeld = setBytes; + } + std::size_t ownLeased = 0; + for (auto const& key : keys) { + if (auto const slot = findIn(*base, key); slot != nullptr && slot->value && kept(*slot, nowTicks)) { + ownLeased += slot->bytes; + } + } + auto const leasedAll = leasedBytes(*base, nowTicks); + auto const leasedOther = leasedAll - std::min(ownLeased, leasedAll); + if ((keys.size() * mean) + leasedOther + setsHeld + keyBytes <= options.maxBytes) { + return {}; + } + refusedOrders.fetch_add(1); + return std::unexpected( + TableError{.code = TableErrorCode::Unavailable, + .column = {}, + .message = "the level " + options.level + " cannot hold every row this order needs"}); + } + + // Whether an order use keeps a slot from eviction: its own lease runs, or an accepted set protects it. + [[nodiscard]] static bool kept(Slot const& slot, std::int64_t nowTicks) noexcept { + return slot.leaseUntil.load() > nowTicks || slot.setHolds.load() > 0; + } + + // Gives a held value an order lease until `until`, one more holder while its lease runs. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the lease's end, then the current time, as every caller reads them. + static void lease(Slot const& slot, std::int64_t until, std::int64_t nowTicks) { + if (slot.leaseUntil.load() > nowTicks) { + slot.leaseHolders.fetch_add(1); + } else { + slot.leaseHolders.store(1); + } + auto current = slot.leaseUntil.load(); + while (current < until && !slot.leaseUntil.compare_exchange_weak(current, until)) { + } + } + + // The bytes the order uses keep from eviction in `table`. Run with no lock held. + [[nodiscard]] static std::size_t leasedBytes(Table const& table, std::int64_t nowTicks) { + std::size_t out = 0; + for (auto const& shard : table.shards) { + for (auto const& [key, slot] : *shard) { + if (kept(*slot, nowTicks)) { + out += slot->bytes; + } + } + } + return out; + } + + // Takes back an order use's want. Of an accepted set, found by its keys' address, it is one holder fewer; + // the set's protection ends with its last holder. Of anything else, it ends one holder's lease of each key, + // a chunk at a time under the writer mutex: on a held value's slot while its lease runs, otherwise on the + // key's pending lease. + void release(std::span keys) { + bool ofSet = false; + { + std::scoped_lock const lock{writer}; + auto const found = std::ranges::find_if(sets, [&keys](auto const& entry) { + return entry.first->data() == keys.data() && entry.first->size() == keys.size(); + }); + if (found != sets.end()) { + if (--found->second.holders > 0) { + return; + } + static_cast(takeSet(found)); + ofSet = true; + } + } + if (ofSet) { + unprotect(keys); + return; + } + auto const nowTicks = ticks(now()); + for (std::size_t first = 0; first < keys.size(); first += detail::kWantChunk) { + if (releaseHook) { + releaseHook(first / detail::kWantChunk); + } + std::scoped_lock const lock{writer}; + auto const last = std::min(keys.size(), first + detail::kWantChunk); + for (auto index = first; index < last; ++index) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < last <= keys.size() + auto const& key = keys[index]; + if (auto const slot = findIn(*current, key); + slot != nullptr && slot->leaseUntil.load() > nowTicks) { + if (slot->leaseHolders.fetch_sub(1) <= 1) { + slot->leaseHolders.store(0); + slot->leaseUntil.store(0); + } + } else if (auto const pending = pendingLeases.find(key); pending != pendingLeases.end()) { + if (--pending->second.holders <= 0) { + pendingLeases.erase(pending); + } + } + } + } + } + + // ── loading ── + + static void dispatch(std::shared_ptr const& core, std::vector batch) { + if (batch.empty()) { + return; + } + if (core->options.loads == nullptr) { + while (!batch.empty()) { + batch = core->load(std::move(batch)); + } + return; + } + try { + core->options.loads->post([core, batch]() mutable { dispatch(core, core->load(std::move(batch))); }); + } catch (...) { + // Nothing will load the batch: its keys go back on the display queue, and the next want dispatches. + core->unpost(batch); + } + } + + void unpost(std::vector const& batch) { + std::scoped_lock const lock{writer}; + auto const want = ++wants; + std::size_t index = 0; + for (auto const& loading : batch) { + inFlight.erase(loading.key); + enqueue(loading.key, LevelUse::Display, priorityOf(want, index++)); + } + running = false; + } + + [[nodiscard]] std::vector load(std::vector batch) { + std::vector keys; + keys.reserve(batch.size()); + for (auto const& loading : batch) { + keys.push_back(loading.key); + } + loaderCalls.fetch_add(1); + // The registry the loader numbers its measures in is the one in place when it is called. + auto const lineage = unitLineage(); + std::vector> loaded; + try { + loaded = loader(keys); + } catch (...) { + loaded.clear(); + } + auto told = store(batch, loaded, true, lineage); + std::vector next; + { + std::scoped_lock const lock{writer}; + next = takeBatch(); + } + tell(told); + return next; + } + + // Stores a load's values and failures, then applies the bound. The new state and the eviction are + // prepared with no lock held; the writer mutex is taken only to check that nothing changed since and to + // publish. A change published meanwhile makes the store prepare again. `lineage` is the unit lineage the + // load was issued under: a load whose registry was swapped for another lineage while it ran is dropped, as + // an invalidated one is, since its unit numbers mean nothing now. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + [[nodiscard]] Told store(std::vector const& batch, std::vector>& loaded, + bool counted, std::uint64_t lineage) { + // Sizes are read once, before any lock: a throwing `sizeOf` fails its key. + std::unordered_map> returned; + returned.reserve(loaded.size()); + for (auto& [key, value] : loaded) { + try { + returned.emplace(key, std::pair{&value, sizeOf(value)}); + } catch (...) { + // Not returned: the key is stored as failed. + returned.erase(key); + } + } + auto const now = nowOrEpoch(); + checkLineage(); + bool const otherLineage = lineage != unitLineage(); + Told told; + bool leasedStored = false; + for (;;) { + std::shared_ptr
base; + std::uint64_t seen = 0; + std::vector valid(batch.size()); + { + std::scoped_lock const lock{writer}; + base = current; + seen = version; + for (std::size_t index = 0; index < batch.size(); ++index) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < batch.size() and valid has one flag per batch entry + valid[index] = !otherLineage && stillCurrent(batch[index]); + } + } + Edit edit{*base, shardCopies}; + std::vector stored; + std::vector failed; + std::size_t dropped = 0; + for (std::size_t index = 0; index < batch.size(); ++index) { + auto const& key = batch[index].key; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < batch.size() and valid has one flag per batch entry + if (!valid[index]) { + ++dropped; + continue; + } + auto const old = edit.find(key); + auto slot = std::make_shared(); + if (auto const found = returned.find(key); found != returned.end()) { + slot->value = *found->second.first; + slot->bytes = found->second.second; + stored.push_back(key); + } else { + slot->bytes = sizeof(Slot); + slot->failures = old != nullptr && !old->value ? old->failures + 1 : 1; + slot->failedAt = now; + failed.push_back(key); + } + edit.put(key, std::move(slot)); + } + auto next = edit.table(); + if (storeHook) { + storeHook(); + } + { + std::scoped_lock const lock{writer}; + if (version != seen) { + continue; // a change was published meanwhile: prepare again over it + } + for (auto const& loading : batch) { + if (auto const flight = inFlight.find(loading.key); + flight != inFlight.end() && flight->second == std::pair{loading.epoch, loading.started}) { + inFlight.erase(flight); + } + invalidatedAt.erase(loading.key); + } + for (auto const& key : stored) { + auto const slot = findIn(*next, key); + slot->lastUse.store(useCounter.fetch_add(1) + 1); + if (auto const lease = pendingLeases.find(key); lease != pendingLeases.end()) { + if (lease->second.until > ticks(now)) { + slot->leaseHolders.store(lease->second.holders); + slot->leaseUntil.store(lease->second.until); + } + pendingLeases.erase(lease); + leasedStored = true; + } + if (auto const kept = protectedKeys.find(key); kept != protectedKeys.end()) { + slot->setHolds.store(kept->second); + leasedStored = true; + } + } + for (auto const& key : failed) { + pendingLeases.erase(key); + if (auto const kept = protectedKeys.find(key); kept != protectedKeys.end()) { + auto const slot = findIn(*next, key); + slot->setHolds.store(kept->second); + recheckAt(slot->failedAt + retryDelay(slot->failures)); + } + } + if (edit.changed()) { + publish(std::move(next), edit); + } + if (!stored.empty()) { + storedLineage.store(lineage); + } + if (counted) { + loadedKeys.fetch_add(stored.size()); + } + failedLoads.fetch_add(failed.size()); + droppedLoads.fetch_add(dropped); + told.sink = sink; + told.failedHandler = failedHandler; + } + told.stored = std::move(stored); + told.failed = std::move(failed); + break; + } + // Leased bytes grow only when a leased value is stored; only then can they have passed the bound. + told.overBound = leasedStored && dropLeasesOverBound(now); + evict(told.stored, told.failed, now); + return told; + } + + // Under the writer mutex: what `stats().bytes` reads, the values, the failures and the accepted sets' keys. + void storeBytes() { bytes.store(valueBytes + failureBytes + setBytes); } + + void forget(Slot const* slot) { + if (slot == nullptr) { + return; + } + if (slot->value) { + valueBytes -= slot->bytes; + --values; + } else { + failureBytes -= slot->bytes; + } + storeBytes(); + } + + void remember(Slot const& slot) { + if (slot.value) { + valueBytes += slot.bytes; + ++values; + } else { + failureBytes += slot.bytes; + } + storeBytes(); + } + + // When the leased and protected values, with the accepted sets' keys, exceed the bound, stops loading for + // order, drops every lease and ends every accepted set. The bytes are summed and the slots cleared over the + // published state with no lock held; the queue, the pending leases and the sets are changed under it. + bool dropLeasesOverBound(Clock::time_point now) { + endExpiredSets(ticks(now)); + auto const table = publishedTable(); + std::size_t setsHeld = 0; + { + std::scoped_lock const lock{writer}; + setsHeld = setBytes; + } + if (leasedBytes(*table, ticks(now)) + setsHeld <= options.maxBytes) { + return false; + } + { + std::scoped_lock const lock{writer}; + queues.at(static_cast(LevelUse::Order)).clear(); + std::erase_if(queued, [](auto const& entry) { return entry.second.use == LevelUse::Order; }); + pendingLeases.clear(); + endAllSets(); // their keys lose their protection: a repeat of a set must be fitted again + } + for (auto const& shard : table->shards) { + for (auto const& [key, slot] : *shard) { + slot->leaseUntil.store(0); + slot->setHolds.store(0); + } + } + return true; + } + + // Evicts the least recently used unleased slots until the bound holds. The scan, the sort and the new + // state are prepared with no lock held, over the published state; the writer mutex is taken only to check + // that nothing changed and to publish. This batch's keys, stored or failed, are not candidates, nor is a + // failure still inside its retry delay; when the bound still does not hold, the stored keys are marked to + // go first. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + void evict(std::vector const& stored, std::vector const& failed, Clock::time_point now) { + auto const nowTicks = ticks(now); + endExpiredSets(nowTicks); + std::unordered_set fresh(stored.begin(), stored.end()); + fresh.insert(failed.begin(), failed.end()); + for (int attempt = 0;; ++attempt) { + if (attempt == 8) { + ::morph::log::logError( + "[levelCache] {}: eviction lost to other changes eight times; the level " + "stays over its bound until the next store", + options.level); + return; + } + std::shared_ptr
base; + std::uint64_t seen = 0; + std::size_t held = 0; + { + std::scoped_lock const lock{writer}; + base = current; + seen = version; + held = valueBytes + failureBytes + setBytes; + } + if (held <= options.maxBytes) { + return; + } + if (evictionHook) { + evictionHook(); + } + std::vector> candidates; + for (auto const& shard : base->shards) { + for (auto const& [key, slot] : *shard) { + if (kept(*slot, nowTicks) || fresh.contains(key)) { + continue; + } + if (!slot->value && now < slot->failedAt + retryDelay(slot->failures)) { + continue; + } + candidates.emplace_back(slot->value ? slot->lastUse.load() : std::int64_t{-1}, key, + slot->bytes); + } + } + std::ranges::sort(candidates); + Edit edit{*base, shardCopies}; + auto remaining = held; + std::size_t evicted = 0; + for (auto const& [use, key, size] : candidates) { + if (remaining <= options.maxBytes) { + break; + } + edit.erase(key); + remaining -= std::min(remaining, size); + ++evicted; + } + auto next = edit.changed() ? edit.table() : nullptr; + { + std::scoped_lock const lock{writer}; + if (version != seen) { + continue; // a change was published meanwhile: scan again over it + } + // A lease given since the scan protects its value: scan again. + bool leased = false; + for (auto const& [old, slot] : edit.changes) { + leased = leased || kept(*old, nowTicks); + } + if (leased) { + continue; + } + if (next != nullptr) { + publish(std::move(next), edit); + } + evictedKeys.fetch_add(evicted); + if (valueBytes + failureBytes > options.maxBytes) { + for (auto const& key : stored) { + if (auto const slot = findIn(*current, key); slot != nullptr) { + slot->lastUse.store(0); + } + } + } + } + return; + } + } + + template + static void guarded(Call&& call) noexcept { + try { + std::forward(call)(); + } catch (std::exception const& exc) { + ::morph::log::logError("[levelCache] a callback threw: {}", exc.what()); + } catch (...) { + ::morph::log::logError("[levelCache] a callback threw"); + } + } + + void tell(Told const& told) const { + if (told.sink) { + for (auto const& record : options.records) { + if (!told.stored.empty()) { + guarded([&] { told.sink(record, changeKeys(told.stored)); }); + } + if (!told.failed.empty()) { + guarded([&] { told.sink(record, changeKeys(told.failed)); }); + } + } + } + if (!told.failed.empty() && told.failedHandler) { + guarded([&] { told.failedHandler(told.failed); }); + } + if (told.overBound && told.sink) { + for (auto const& record : options.records) { + guarded([&] { told.sink(record, std::nullopt); }); + } + } + } + + void storeQuietly(std::vector> loaded) { + std::vector batch; + { + std::scoped_lock const lock{writer}; + auto const started = ++sequence; + batch.reserve(loaded.size()); + for (auto const& [key, value] : loaded) { + batch.push_back(Loading{.key = key, .epoch = epoch, .started = started}); + } + } + static_cast(store(batch, loaded, false, unitLineage())); + } + + // Removes keys. The new state is prepared with no lock held; the writer mutex is taken to check that + // nothing changed, mark the keys in flight as invalidated, and publish. + void invalidate(std::span keys) { + for (;;) { + std::shared_ptr
base; + std::uint64_t seen = 0; + { + std::scoped_lock const lock{writer}; + base = current; + seen = version; + } + Edit edit{*base, shardCopies}; + for (auto const& key : keys) { + if (findIn(*base, key) != nullptr) { + edit.erase(key); + } + } + auto next = edit.changed() ? edit.table() : nullptr; + std::scoped_lock const lock{writer}; + if (version != seen) { + continue; + } + bool recorded = false; + for (auto const& key : keys) { + if (inFlight.contains(key)) { + invalidatedAt.insert_or_assign(key, ++sequence); + recorded = true; + } + pendingLeases.erase(key); + // A protected key removed: every accepted set's next repeat queues what its set misses. + if (protectedKeys.contains(key)) { + ++setEvents; + } + } + if (next != nullptr) { + invalidatedKeys.fetch_add(edit.changes.size()); + publish(std::move(next), edit); + } else if (recorded) { + // A store preparing a key in flight checks `version` before it publishes: it must see this. + ++version; + } + return; + } + } + + // Under the writer mutex: ends every accepted set and every key's protection; the caller clears the slots + // it does not drop. + void endAllSets() { + sets.clear(); + protectedKeys.clear(); + setBytes = 0; + storeBytes(); + setsRecheckAt = std::numeric_limits::max(); + } + + // The lineage of the registry `options.units` gives now; 0 without one. + [[nodiscard]] std::uint64_t unitLineage() const { + if (!options.units) { + return 0; + } + auto const registry = options.units(); + return registry != nullptr ? registry->lineage() : 0; + } + + // Drops every value when the registry is of another lineage than the one they were loaded with. Read with + // no lock: a snapshot never waits for a writer to learn that nothing changed. + void checkLineage() { + if (!options.units) { + return; + } + auto const stored = storedLineage.load(); + if (stored == 0 || stored == unitLineage()) { + return; + } + invalidateAll(); + } + + void invalidateAll() { + std::scoped_lock const lock{writer}; + ++epoch; + storedLineage.store(0); + invalidatedKeys.fetch_add(current->entries); + auto next = emptyTable(current->generation + 1); + { + std::scoped_lock const swap{publishMutex}; + published = next; + } + current = std::move(next); + ++version; + invalidatedAt.clear(); + pendingLeases.clear(); + endAllSets(); + valueBytes = 0; + failureBytes = 0; + values = 0; + bytes.store(0); + } + + void changed(effects::Changes const& changes) { + bool other = false; + for (auto const& change : changes.records) { + if (std::ranges::find(options.invalidatedBy, change.record) == options.invalidatedBy.end()) { + continue; + } + if (std::ranges::find(options.records, change.record) == options.records.end()) { + other = true; + invalidateAll(); + continue; + } + if (!change.keys) { + invalidateAll(); + continue; + } + std::vector keys; + keys.reserve(change.keys->size()); + bool readable = true; + for (auto const& key : *change.keys) { + auto rowId = rowIdOf(key); + if (!rowId) { + readable = false; + break; + } + keys.push_back(std::move(*rowId)); + } + if (readable) { + invalidate(keys); + } else { + invalidateAll(); + } + } + if (!other) { + return; + } + effects::AnnounceSink told; + { + std::scoped_lock const lock{writer}; + told = sink; + } + if (told) { + for (auto const& record : options.records) { + guarded([&] { told(record, std::nullopt); }); + } + } + } + + [[nodiscard]] std::size_t queuedEntries() const { + std::scoped_lock const lock{writer}; + return std::get<0>(queues).size() + std::get<1>(queues).size(); + } + + [[nodiscard]] std::size_t shardCount() const { return publishedTable()->shards.size(); } + + [[nodiscard]] LevelCacheStats stats() const { + return LevelCacheStats{.hits = hits.load(), + .misses = misses.load(), + .loaderCalls = loaderCalls.load(), + .loadedKeys = loadedKeys.load(), + .failedLoads = failedLoads.load(), + .droppedLoads = droppedLoads.load(), + .invalidatedKeys = invalidatedKeys.load(), + .evictedKeys = evictedKeys.load(), + .leasedKeys = leasedKeys.load(), + .refusedOrders = refusedOrders.load(), + .bytes = bytes.load()}; + } + + LevelCacheOptions options; + Loader loader; + SizeOf sizeOf; + std::shared_ptr cells; + // Called at each eviction scan, with no lock held: what a test pauses a store with. + std::function evictionHook; + // Called by a store between preparing and publishing, and by a want and a release before each chunk of + // their keys with the chunk's index; with no lock held. What a test interleaves a change with. + std::function storeHook; + std::function wantHook; + std::function releaseHook; + // The order sets accepted, by address, and the bytes their keys own; the protection count of each of their + // keys, held or not; the events a set's keys may need a look for, counted (a protected key removed, a + // protected failure's delay passed); the earliest end of a protected failure's delay not yet counted. + // Under `writer`. + std::unordered_map const*, AcceptedSet> sets; + std::size_t setBytes = 0; + std::unordered_map protectedKeys; + std::uint64_t setEvents = 0; + std::int64_t setsRecheckAt = std::numeric_limits::max(); + // The sets a `wantSet` is fitting, and what wakes the repeats of them that wait; under `writer`. + std::unordered_set const*> settling; + std::condition_variable setSettled; + std::atomic fits{0}; + + // Orders every change; guards everything below but `published`. Held only to read or publish state, + // never across a scan, a sort or a shard copy. + mutable std::mutex writer; + // Held only to read or swap `published`. + mutable std::mutex publishMutex; + std::shared_ptr
published; + std::shared_ptr
current; // what `published` is, read under `writer` + std::uint64_t version = 0; // advances with every published change + std::uint64_t epoch = 0; + std::atomic storedLineage{0}; // the unit lineage the values held were loaded under; 0: none + std::uint64_t sequence = 0; + std::uint64_t wants = 0; + // Keys of the running batch invalidated after it started, by the sequence number of the invalidation. + std::unordered_map invalidatedAt; + std::unordered_map> inFlight; // epoch, started + std::array, 2> queues; // by priority + std::unordered_map queued; + bool running = false; + // Order leases of keys not held yet, by key, until a clock tick; a held key's lease is on its slot. + struct PendingLease { + std::int64_t until = 0; + std::int32_t holders = 0; + }; + std::unordered_map pendingLeases; + std::size_t valueBytes = 0; + std::size_t failureBytes = 0; + std::size_t values = 0; + std::atomic useCounter{0}; + effects::AnnounceSink sink; + std::function)> failedHandler; + + std::atomic hits{0}; + std::atomic misses{0}; + std::atomic loaderCalls{0}; + std::atomic loadedKeys{0}; + std::atomic failedLoads{0}; + std::atomic droppedLoads{0}; + std::atomic invalidatedKeys{0}; + std::atomic evictedKeys{0}; + std::atomic leasedKeys{0}; + std::atomic refusedOrders{0}; + std::atomic bytes{0}; + std::atomic shardCopies{0}; + }; + + std::shared_ptr _core; +}; + +/// @brief The level cache whose value is a row's cells, in the level's column order. +using CellLevelCache = LevelCache>; + +/// @brief One level a reply reads: its source and the snapshot taken at the reply's start. +struct LevelInput { + /// @brief The level. + std::shared_ptr source; + /// @brief The level's state the reply reads. + std::shared_ptr snapshot; +}; + +/// @brief One request's immutable view of a table: base-level columns from the table's source, level columns +/// from the level snapshots the request took. +/// +/// A level column is read from its level's snapshot at the column's place in `LevelSource::columns()`, found by +/// id, so a caller whose description holds the level's columns in another order or only some of them reads each +/// under its own id. A level column is `Unloaded` unless its snapshot reads the row `Loaded`; a level no input +/// serves is `Unloaded` in every row. +class MORPH_API LeveledSource final : public DataSource { +public: + /// @brief The view of @p base and @p levels under @p columns. + /// @param base The table's rows; its snapshot is taken here, once. + /// @param columns The columns the view has: the description's. + /// @param levels The levels the request read, each with its snapshot. + LeveledSource(std::shared_ptr const& base, std::vector columns, + std::vector levels); + + LeveledSource(LeveledSource const&) = delete; + LeveledSource& operator=(LeveledSource const&) = delete; + LeveledSource(LeveledSource&&) = delete; + LeveledSource& operator=(LeveledSource&&) = delete; + ~LeveledSource() override = default; + + /// @brief The view's columns. + /// @return The columns given. + [[nodiscard]] std::span columns() const override { return _columns; } + + /// @brief The view's one snapshot. + /// @return The snapshot. + [[nodiscard]] std::shared_ptr snapshot() const override { return _snapshot; } + + /// @brief The base source's declared groups, copied when the view was made. + /// @return The groups. + [[nodiscard]] std::span groups() const override { return _groups; } + + /// @brief Does nothing: the view never changes. + /// @param listener Ignored. + void subscribe(ChangeListener& listener) override { static_cast(listener); } + + /// @brief Does nothing: the view never changes. + /// @param listener Ignored. + void unsubscribe(ChangeListener& listener) override { static_cast(listener); } + + /// @brief What a level holds for a row. + /// @param row Row index of the view's snapshot. + /// @param level The level. + /// @return The level snapshot's read of the row's key; `Unloaded` for a level no input serves. + [[nodiscard]] LevelRead state(std::size_t row, std::string_view level) const { + return _snapshot->state(row, level); + } + +private: + struct Plan { + std::optional base; + std::optional level; + std::size_t place = 0; + }; + + struct Level { + std::string name; + std::shared_ptr snapshot; + std::size_t width = 0; + }; + + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- column and level indices come from the plans built against the same lists + class MORPH_API Snapshot final : public RowSnapshot { + public: + Snapshot(std::shared_ptr base, std::vector plans, std::vector levels) + : _base{std::move(base)}, _plans{std::move(plans)}, _levels{std::move(levels)} {} + + [[nodiscard]] std::size_t rowCount() const override { return _base->rowCount(); } + + [[nodiscard]] RowId rowId(std::size_t row) const override { return _base->rowId(row); } + + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): row, then column, as DataSource::cell declares them. + [[nodiscard]] Cell cell(std::size_t row, std::size_t column) const override; + + void readColumn(std::size_t column, ColumnSink& sink, std::size_t first, std::size_t last) const override; + + [[nodiscard]] MORPH_PROCESS_UNIQUE LevelRead state(std::size_t row, std::string_view level) const; + + private: + std::shared_ptr _base; + std::vector _plans; + std::vector _levels; + }; + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + + std::vector _columns; + std::vector _groups; + std::shared_ptr _snapshot; +}; + +} // namespace morph::table diff --git a/include/morph/table/plan_conformance.hpp b/include/morph/table/plan_conformance.hpp deleted file mode 100644 index 40852f149..000000000 --- a/include/morph/table/plan_conformance.hpp +++ /dev/null @@ -1,386 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -#pragma once - -/// @file table/plan_conformance.hpp -/// @brief Holds a model's translation of a `QueryPlan` to the answers of `apply`. -/// -/// A model that pages its rows in a database translates `planQuery`'s plan into its own query. This header runs a -/// corpus of queries through `apply` over the rows (in the model's key order) and through the model's callback, and -/// reports every disagreement. It depends on neither a test framework nor a database: the caller asserts that the -/// returned list is empty. See `docs/spec/table/database_pages.md`. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace morph::table { - -/// @brief What a model's translation of a plan returns. -struct ModelPage { - /// @brief The keys of the page's rows, in order. - std::vector rows; - /// @brief The reported total; absent when the model did not count. - std::optional total; - /// @brief Whether `total` is the count or a lower bound. - TotalKind totalKind = TotalKind::Exact; - /// @brief The view row of `rows[0]`. - std::int64_t offset = 0; -}; - -/// @brief A model's translation of a plan into its own query and the page that query returns. -using PlanModel = std::function(QueryPlan const&)>; - -/// @brief The inputs the oracle and the plan share. -struct ConformanceOptions { - /// @brief The bounds of `validate`. - QueryLimits limits; - /// @brief The services the oracle and the plan compile with. - Services services; - /// @brief Whether the principal may read a column; empty allows every column. - std::function mayRead; - /// @brief The columns and uses the model can translate; empty accepts all. A query this refuses is skipped: the - /// refusal runs after `validate` and before the filter compiles, so only the refusal itself is the model's. - std::function translatable; -}; - -namespace detail { - -/// @brief The operators a filter entry can carry, as the entries the corpus builds. -/// @param op The operator. -/// @param first The first operand. -/// @param second The second operand, for `Between`. -/// @return The entry. -[[nodiscard]] inline FilterEntry corpusEntry(CompiledFilter::Op op, std::string const& first, - std::string const& second) { - using Op = CompiledFilter::Op; - FilterEntry entry; - switch (op) { - case Op::Eq: - entry.eq = first; - break; - case Op::Ne: - entry.ne = first; - break; - case Op::Lt: - entry.lt = first; - break; - case Op::Le: - entry.le = first; - break; - case Op::Gt: - entry.gt = first; - break; - case Op::Ge: - entry.ge = first; - break; - case Op::Between: - entry.between = std::array{first, second}; - break; - case Op::Contains: - entry.contains = first; - break; - case Op::StartsWith: - entry.startsWith = first; - break; - case Op::EndsWith: - entry.endsWith = first; - break; - case Op::IsEmpty: - entry.isEmpty = true; - break; - case Op::NotEmpty: - default: - entry.notEmpty = true; - break; - } - return entry; -} - -/// @brief The text a corpus query uses as an operand for a cell. -/// -/// A date-time cell holds whole UTC seconds and a date cell holds days since the epoch; shown as bare numbers neither -/// parses as a date, so a query built from them is refused by `apply` and by the plan alike and compares nothing. -/// They are written as ISO 8601 (`2026-11-10T09:00:00Z`, `2026-11-10`), which the default date parser reads and which -/// lands exactly on the second or day the cell holds. Any other cell is shown as `displayText` shows it. -/// @param kind The column's kind. -/// @param cell The cell. -/// @return The operand text. -[[nodiscard]] inline std::string operandText(ColumnKind kind, Cell const& cell) { - // 0001-01-01T00:00:00Z and 9999-12-31T23:59:59Z: the years four digits can write. - constexpr std::int64_t kMinSeconds = -62'135'596'800; - constexpr std::int64_t kMaxSeconds = 253'402'300'799; - constexpr std::int64_t kSecondsPerDay = 86'400; - if (auto const* whole = std::get_if(&cell)) { - if (kind == ColumnKind::DateTime && *whole >= kMinSeconds && *whole <= kMaxSeconds) { - return std::format("{:%Y-%m-%dT%H:%M:%SZ}", std::chrono::sys_seconds{std::chrono::seconds{*whole}}); - } - if (kind == ColumnKind::Date && *whole >= kMinSeconds / kSecondsPerDay && - *whole <= kMaxSeconds / kSecondsPerDay) { - return std::format("{:%F}", std::chrono::sys_days{std::chrono::days{*whole}}); - } - } - return displayText(cell); -} - -/// @brief A description of a total for a failure message. -/// @param total The total. -/// @param kind Its kind. -/// @return The text. -[[nodiscard]] inline std::string describeTotal(std::optional const& total, TotalKind kind) { - if (!total) { - return "absent"; - } - return std::format("{}{}", kind == TotalKind::AtLeast ? ">=" : "=", *total); -} - -} // namespace detail - -/// @brief Queries derived from a source's own cells: every operator each column's kind defines (as an include, as an -/// exclude and, for text, case-sensitively), both sort directions on every column and on every pair of -/// adjacent columns, a quick-search group over the text columns, and a window of pages around the start, the -/// middle and past the end, with a zero limit. -/// -/// The operands are the cells' own text, so the corpus is only as discriminating as the data: duplicate sort keys, -/// empty cells, accents and case, sub-second instants and mixed units come from the rows the caller supplies. -/// @param source The rows the model also holds. -/// @return The queries. -[[nodiscard]] inline std::vector standardCorpus(DataSource const& source) { - using Op = CompiledFilter::Op; - constexpr std::array kOps{Op::Eq, Op::Ne, Op::Lt, Op::Le, - Op::Gt, Op::Ge, Op::Between, Op::Contains, - Op::StartsWith, Op::EndsWith, Op::IsEmpty, Op::NotEmpty}; - auto const columns = source.columns(); - auto const snapshot = source.snapshot(); - auto const rowCount = static_cast(snapshot->rowCount()); - std::vector corpus; - auto const pageOf = [&](TableQuery base, std::int64_t offset, std::int64_t limit) { - base.page = PageRequest{.offset = offset, .limit = limit}; - corpus.push_back(std::move(base)); - }; - auto const windows = [&](TableQuery const& base) { - pageOf(base, 0, 7); - pageOf(base, rowCount / 2, 7); - pageOf(base, rowCount + 10, 7); - pageOf(base, 0, 0); - }; - for (std::size_t c = 0; c < columns.size(); ++c) { - // Up to three distinct non-empty texts of the column, in row order. - std::vector samples; - for (std::size_t row = 0; row < snapshot->rowCount() && samples.size() < 3; ++row) { - auto text = detail::operandText(columns[c].kind, snapshot->cell(row, c)); - if (!text.empty() && std::ranges::find(samples, text) == samples.end()) { - samples.push_back(std::move(text)); - } - } - // A half step off a whole number, so a translation that rounds or integer-binds an operand on an integer - // column answers differently from `apply`. - if ((columns[c].kind == ColumnKind::Integer || columns[c].kind == ColumnKind::Key) && !samples.empty()) { - samples.push_back(samples.front() + ".5"); - } - for (auto const dir : {SortDirection::Ascending, SortDirection::Descending}) { - TableQuery sorted; - sorted.sort = {SortKey{.column = columns[c].id, .dir = dir}}; - windows(sorted); - if (c + 1 < columns.size()) { - sorted.sort.push_back(SortKey{.column = columns[c + 1].id, .dir = SortDirection::Descending}); - windows(sorted); - } - } - for (auto const op : kOps) { - if (!detail::operatorDefined(columns[c].kind, op)) { - continue; - } - for (std::size_t s = 0; s < std::max(samples.size(), 1); ++s) { - std::string const first = samples.empty() ? std::string{} : samples[s]; - std::string const second = samples.size() > 1 ? samples[(s + 1) % samples.size()] : first; - for (bool const caseSensitive : {false, true}) { - if (caseSensitive && columns[c].kind != ColumnKind::Text) { - continue; - } - auto entry = detail::corpusEntry(op, first, second); - if (caseSensitive) { - entry.caseSensitive = true; - } - for (bool const asExclude : {false, true}) { - TableQuery query; - ColumnFilter filter; - (asExclude ? filter.exclude : filter.include).push_back(entry); - query.filters.columns.emplace(columns[c].id, std::move(filter)); - query.sort = {SortKey{.column = columns[c].id, .dir = SortDirection::Descending}}; - windows(query); - } - } - } - } - } - GroupFilter group; - for (auto const& column : columns) { - if (column.kind == ColumnKind::Text) { - group.columns.push_back(column.id); - } - } - if (!group.columns.empty()) { - for (auto const& needle : {std::string{"a"}, std::string{"E"}}) { - TableQuery query; - GroupFilter search = group; - search.include.push_back(FilterEntry{.contains = needle}); - query.filters.groups.push_back(std::move(search)); - windows(query); - } - } - return corpus; -} - -/// @brief Runs @p corpus through `apply` over @p source and through @p model, and describes every disagreement and -/// every -/// column the corpus never compared. -/// -/// @p source must hold the rows in the model's key order, which is the order `apply` breaks ties in. For each -/// query: when the plan is refused for a reason other than the model's `translatable`, `apply` must refuse with the -/// same code and column; when the plan is accepted, the model's rows (by key), offset and total must equal -/// `apply`'s. Above `QueryLimits::totalCap` `apply` omits the total; the oracle then counts the view itself, and -/// the model must report either that exact count or a lower bound equal to the cap. -/// -/// Identical refusals count as agreement, so a corpus whose operands never parse would pass without comparing -/// anything. For each column that a corpus query filters with an operand, and for each column that a sort-only query -/// orders, the helper therefore also reports the column when at least one query on it was refused identically by -/// `apply` and the plan and none was compared with the model. Queries the model's `translatable` refuses are skipped -/// and count as neither, so a column the model declares untranslatable is not reported. -/// @param source The rows, in key order. -/// @param model The model's translation of a plan. -/// @param corpus The queries. -/// @param options Limits, services and column access shared by the oracle and the plan. -/// @return One description per disagreement; empty when the model conforms. -[[nodiscard]] inline std::vector conformanceFailures(DataSource const& source, PlanModel const& model, - std::span corpus, - ConformanceOptions const& options = {}) { - std::vector failures; - auto const snapshot = source.snapshot(); - ApplyOptions applyOptions; - applyOptions.limits = options.limits; - applyOptions.services = options.services; - applyOptions.mayRead = options.mayRead; - // Per "filter " and "sort ": queries compared with the model, and queries both sides refused. - struct Tally { - std::size_t compared = 0; - std::size_t refusedBySame = 0; - }; - std::map tallies; - auto const tallied = [&](TableQuery const& query) { - std::vector out; - if (!query.filters.columns.empty()) { - for (auto const& [column, filter] : query.filters.columns) { - // IsEmpty and NotEmpty take no operand, so they are compared whatever the operands do. - auto const hasOperand = [](FilterEntry const& entry) { - return !entry.isEmpty.value_or(false) && !entry.notEmpty.value_or(false); - }; - if (std::ranges::any_of(filter.include, hasOperand) || - std::ranges::any_of(filter.exclude, hasOperand)) { - out.push_back(&tallies["filter " + column]); - } - } - } else { - for (auto const& key : query.sort) { - out.push_back(&tallies["sort " + key.column]); - } - } - return out; - }; - for (std::size_t index = 0; index < corpus.size(); ++index) { - auto const& query = corpus[index]; - auto const name = std::format("query {}", index); - auto const planned = planQuery(query, source.columns(), options.limits, options.mayRead, options.services, - options.translatable); - auto const expected = apply(source, query, applyOptions); - if (!planned) { - if (planned.error().code == TableErrorCode::Unavailable) { - continue; - } - if (expected || expected.error().code != planned.error().code || - expected.error().column != planned.error().column) { - failures.push_back(name + ": the plan was refused (" + planned.error().message + - ") but apply answered differently"); - } else { - for (auto* tally : tallied(query)) { - ++tally->refusedBySame; - } - } - continue; - } - if (!expected) { - failures.push_back(name + ": apply refused (" + expected.error().message + ") but the plan was accepted"); - continue; - } - auto const got = model(*planned); - if (!got) { - failures.push_back(name + ": the model refused the plan: " + got.error().message); - continue; - } - for (auto* tally : tallied(query)) { - ++tally->compared; - } - std::vector wanted; - wanted.reserve(expected->rows.size()); - for (auto const row : expected->rows) { - wanted.push_back(snapshot->rowId(row)); - } - if (got->rows != wanted) { - failures.push_back( - std::format("{}: rows differ (apply {}, model {})", name, wanted.size(), got->rows.size())); - } - if (got->offset != expected->offset) { - failures.push_back(std::format("{}: offset {} but apply {}", name, got->offset, expected->offset)); - } - if (expected->total) { - if (got->total != expected->total || got->totalKind != TotalKind::Exact) { - failures.push_back(name + ": total " + detail::describeTotal(got->total, got->totalKind) + - " but apply " + detail::describeTotal(expected->total, TotalKind::Exact)); - } - } else { - // Above the cap `apply` omits the total, so the oracle counts the filtered view itself: an Exact total - // must equal that count, and a lower bound must equal the cap. - auto const cap = options.limits.totalCap; - auto counting = query; - counting.page = PageRequest{.offset = 0, .limit = 0}; - auto countOptions = applyOptions; - countOptions.limits.totalCap = std::numeric_limits::max(); - auto const counted = apply(source, counting, countOptions); - if (!counted || !counted->total) { - failures.push_back(name + ": the oracle could not count the view"); - continue; - } - bool const exactCount = got->total == counted->total && got->totalKind == TotalKind::Exact; - bool const boundAtCap = got->total && got->totalKind == TotalKind::AtLeast && *got->total == cap; - if (!exactCount && !boundAtCap) { - failures.push_back(name + ": above the cap the model reported " + - detail::describeTotal(got->total, got->totalKind) + " for a view of " + - std::to_string(*counted->total)); - } - } - } - for (auto const& [use, tally] : tallies) { - if (tally.refusedBySame > 0 && tally.compared == 0) { - failures.push_back(std::format( - "{}: {} queries were refused identically by apply and the plan and none was compared with the model " - "(an operand the source's own cells cannot supply?)", - use, tally.refusedBySame)); - } - } - return failures; -} - -} // namespace morph::table diff --git a/include/morph/table/query.hpp b/include/morph/table/query.hpp index f27fce4a5..661cfe672 100644 --- a/include/morph/table/query.hpp +++ b/include/morph/table/query.hpp @@ -8,39 +8,43 @@ /// /// In `server` mode a list action's body embeds a `TableQuery` and its reply /// is a `Page`. A server implements the action with `table::apply` over -/// its own rows, or with a database query that honours the same semantics -/// (spec 7 §5–6). `validate` applies the limits every server applies to an -/// untrusted query. On the client, `PageWindow` holds the pages fetched +/// its own rows (spec 7 §5–6). `validate` applies the limits every server +/// applies to an untrusted query. On the client, `PageWindow` holds the pages fetched /// around the visible rows. /// /// See `docs/spec/table/engine.md`. #include #include +#include #include #include #include #include #include +#include #include +#include #include +#include #include #include #include +#include #include -#include +#include #include -#include -#include -#include -#include #include #include #include +#include #include #include #include +#include +#include #include +#include #include namespace morph::table { @@ -60,6 +64,35 @@ struct PageRequest { [[nodiscard]] bool operator==(PageRequest const& other) const = default; }; +/// @brief What a distinct-values request on a date or date-time column counts by. +enum class DateBucket : std::uint8_t { + Value, ///< Each value: a date, or a date-time to the second. + Year, ///< The year a value is in. + Month, ///< The month a value is in. + Day, ///< The day a value is in. +}; + +/// @brief A request for the distinct values of a column: what a header's filter menu lists. +struct DistinctRequest { + /// @brief The column whose values are listed. + std::string column; + /// @brief In place of `column`: a declared group's id, for values pooled over its columns. + std::string group; + /// @brief Narrows to values whose text contains this, both folded; empty for all. + std::string search; + /// @brief For `Date` and `DateTime`: `Value`, or the bucket to count by. + DateBucket bucket = DateBucket::Value; + /// @brief The first value of the reply, in the list's order. + std::int64_t offset = 0; + /// @brief Values wanted; clamped to `QueryLimits::maxLimit`. + std::int64_t limit = 200; + + /// @brief Member-wise equality. + /// @param other The request to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(DistinctRequest const& other) const = default; +}; + /// @brief A table's sort, filters and page, as a list action's body carries them. /// /// The member that holds one is marked `x-table` in the action's schema, which @@ -71,6 +104,23 @@ struct TableQuery { FilterSpec filters; /// @brief The page. PageRequest page; + /// @brief The columns the reply carries, by id. Absent means every column the caller may read; empty means + /// none, and the reply then holds keys alone. `validate` puts it in the table's column order, each id + /// once. + std::optional> columns; + /// @brief When set, the reply holds only the view's rows with these keys, in view order, and `page` does not + /// apply. A key not in the view (removed, rejected or undecided) has no row in the reply. + std::optional> keys; + /// @brief The user asked for failed loads to be tried again: the level caches load the failed keys this query + /// needs without waiting out their retry delay. + bool retry = false; + /// @brief When set, the reply holds this request's distinct values and no rows; `page`, `sort` and `columns` + /// do not apply. A query may not set both `keys` and `distinct`. + std::optional distinct; + /// @brief Rows the view keeps although the filter rejects them: the rows the session's own actions changed. Each + /// one the caller may see is in the view at the place the sort gives it, and the reply's `unmatched` lists + /// those the filter rejects. Distinct values ignore it. Left out of the JSON when empty. + std::vector retain; /// @brief The schema keyword that marks a member of this type. /// @return `"x-table"`. @@ -83,7 +133,76 @@ enum class TotalKind : std::uint8_t { AtLeast, ///< `total` is a lower bound: the view has at least that many rows. }; +/// @brief One distinct value of a column and the rows that hold it. +struct DistinctValue { + /// @brief The value as the cell shows it: its first row's text. + std::string text; + /// @brief The value as a filter entry takes it: a `oneOf` member, or for a date bucket the two ends of a + /// `between` joined by `..`. + std::string operand; + /// @brief The rows that hold the value. + std::int64_t count = 0; + /// @brief A `Measure` column's value only: its dimension's name, by which a menu draws a heading. + std::string dimension; + /// @brief A `Measure` column's value only: the id of the unit its first row has it in. + std::string unit; + + /// @brief Member-wise equality. + /// @param other The value to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(DistinctValue const& other) const = default; +}; + +/// @brief A page of a column's distinct values, with what the rows held besides values. +struct DistinctValues { + /// @brief The values, in the column's ascending order. + std::vector values; + /// @brief Values matching the search, before offset and limit; counted up to `QueryLimits::totalCap`. + std::int64_t distinct = 0; + /// @brief `AtLeast` when `distinct` stopped at the cap. + TotalKind distinctKind = TotalKind::Exact; + /// @brief Rows whose cell is empty. + std::int64_t blanks = 0; + /// @brief Rows whose cell is invalid; they are under no value. + std::int64_t invalid = 0; + /// @brief Rows were left out because a cell was unloaded or another filter could not decide them. + bool partial = false; + + /// @brief Member-wise equality. + /// @param other The values to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(DistinctValues const& other) const = default; +}; + +/// @brief A row of a page with levels that are not loaded. +struct UnloadedRow { + /// @brief The row's index into `Page::rows`. + std::int64_t index = 0; + /// @brief The row's unloaded levels among those the reply needed: sorted, without duplicates, never the base + /// level. + std::vector levels; + /// @brief The subset of `levels` whose load failed; usually empty. + std::vector failed; + + /// @brief Member-wise equality. + /// @param other The row to compare with. + /// @return `true` when index, levels and failed levels match. + [[nodiscard]] bool operator==(UnloadedRow const& other) const = default; +}; + +/// @brief What is not loaded for one row: views into the page or window that holds the row. +struct UnloadedLevels { + /// @brief The row's unloaded levels, sorted. + std::span levels; + /// @brief The subset of `levels` whose load failed. + std::span failed; +}; + /// @brief One page of a list action's reply. +/// +/// The members from `unloadedRows` to `failed` say which of its cells are still coming, and `indices` places a +/// keyed reply's rows in the view. An absent `total` and an empty `failed` or `indices` are left out of the JSON +/// written; a page read without the members after `totalKind` is a fully loaded page that is not a keyed reply. /// @tparam Row The row type. template struct Page { @@ -96,6 +215,39 @@ struct Page { std::int64_t offset = 0; /// @brief Whether `total` is the count or a lower bound; meaningful only when `total` is present. TotalKind totalKind = TotalKind::Exact; + /// @brief The rows of this reply that have unloaded levels, ascending by index. A row not listed is fully + /// loaded; the members of a listed row at those levels hold whatever the server left, and are not read. + std::vector unloadedRows; + /// @brief Rows the filter can neither admit nor reject until a level loads. They are in no page. + std::int64_t undecided = 0; + /// @brief The order levels with a load wanted or in flight for at least one row. Not empty means the order and + /// the membership of the view may change without any row being edited. + std::vector awaiting; + /// @brief The order levels whose load failed for at least one row, and is not being tried again yet. + std::vector failed; + /// @brief A keyed reply only: the view row of each of `rows`. + std::vector indices; + /// @brief A distinct-values reply only: the values; the page then has no rows. + std::optional distinct; + /// @brief The indices, into `rows`, of the retained rows (`TableQuery::retain`) the filter rejects, ascending. + /// Left out of the JSON when empty. + std::vector unmatched; + /// @brief The view's membership (`MembershipDigest::text`): two pages with the same one are of views of the same + /// rows, whatever their sort. Empty on a distinct-values reply, and then left out of the JSON. + std::string viewRevision; + + /// @brief The members that open a query cache entry holding the page: while either is set, a row the page + /// does not hold may come to belong to it, so every change of its record marks the entry. A member the + /// page does not have is skipped. + /// @return `awaiting` and `distinct`. + [[nodiscard]] static constexpr std::array openMembers() noexcept { + return {"awaiting", "distinct"}; + } + + /// @brief The member that makes a query cache entry holding the page partial: while it is set, a merge by key + /// would leave it describing rows it no longer indexes, so an `updates` effect marks the entry instead. + /// @return `unloadedRows`. + [[nodiscard]] static constexpr std::string_view partialMember() noexcept { return "unloadedRows"; } }; /// @brief The bounds a server applies to every `TableQuery`, an untrusted body. @@ -118,6 +270,44 @@ struct QueryLimits { std::size_t maxTextLength = 256; /// @brief A total above this is not reported. std::int64_t totalCap = 100'000; + /// @brief Entries of `TableQuery::columns`, counted as received, duplicates included. + std::size_t maxColumns = 512; + /// @brief Entries of `TableQuery::keys`, counted as received, duplicates included. + std::size_t maxKeys = 1000; + /// @brief Members of one `oneOf` entry. + std::size_t maxSetValues = 10'000; + /// @brief Members of every `oneOf` entry of one query together. + std::size_t maxQuerySetValues = 20'000; + /// @brief Bytes of the members of every `oneOf` entry of one query together. + std::size_t maxQuerySetBytes = std::size_t{1} << 20U; + /// @brief Rows of a view a selection of the view may resolve to; a larger view is `LimitExceeded`. + std::int64_t maxSelectedRows = 1'000'000; + /// @brief Entries of `TableQuery::retain`, counted as received, duplicates included. + std::size_t maxRetained = 10'000; +}; + +/// @brief A digest of a set of row keys: what names a view's membership. +/// +/// It does not depend on the order the keys are added in, so a view's revision is the same under every sort, and +/// a retained row merged into a reply is one more `add`. Each key is hashed (FNV-1a over `"i:"` and the decimal +/// of an integer key, `"s:"` and the text of a text key) and mixed (splitmix64); the digest keeps the count, the +/// sum of the hashes and the sum of the mixes, each modulo 2^64. A caller adds each key once. +class MORPH_API MembershipDigest { +public: + /// @brief Adds one key to the set. + /// @param key The key; added once. + void add(RowId const& key) noexcept; + + /// @brief The digest as text. + /// @return The count, the sum and the mix, each as 16 lowercase hex digits: 48 digits. + [[nodiscard]] std::string text() const { + return model::detail::hex64(_count) + model::detail::hex64(_sum) + model::detail::hex64(_mix); + } + +private: + std::uint64_t _count = 0; + std::uint64_t _sum = 0; + std::uint64_t _mix = 0; }; namespace detail { @@ -126,21 +316,13 @@ namespace detail { /// @param column The column concerned, or empty. /// @param message The description. /// @return The error. -[[nodiscard]] inline TableError limitError(std::string column, std::string message) { - return TableError{ - .code = TableErrorCode::LimitExceeded, .column = std::move(column), .message = std::move(message)}; -} +[[nodiscard]] MORPH_API TableError limitError(std::string column, std::string message); /// @brief Whether any operand of an entry is longer than @p max bytes. /// @param entry The entry. /// @param max The bound. /// @return `true` when one is. -[[nodiscard]] inline bool entryTooLong(FilterEntry const& entry, std::size_t max) { - auto const tooLong = [max](std::optional const& value) { return value && value->size() > max; }; - return tooLong(entry.eq) || tooLong(entry.ne) || tooLong(entry.lt) || tooLong(entry.le) || tooLong(entry.gt) || - tooLong(entry.ge) || tooLong(entry.contains) || tooLong(entry.startsWith) || tooLong(entry.endsWith) || - (entry.between && ((*entry.between)[0].size() > max || (*entry.between)[1].size() > max)); -} +[[nodiscard]] MORPH_API bool entryTooLong(FilterEntry const& entry, std::size_t max); /// @brief Whether any of @p entries has an operand longer than @p max bytes. /// @param entries The entries. @@ -155,62 +337,80 @@ namespace detail { /// @param columns The row schema's columns. /// @param mayRead Whether the principal may read a column; empty allows every column. /// @return The error, or nothing. -[[nodiscard]] inline std::optional checkColumn(std::string const& columnId, - std::span columns, - std::function const& mayRead) { - if (!findColumn(columns, columnId)) { - return unknownColumn(columnId); - } - if (mayRead && !mayRead(columnId)) { - return TableError{.code = TableErrorCode::ColumnNotReadable, - .column = columnId, - .message = "column " + columnId + " is not readable"}; - } - return std::nullopt; -} +[[nodiscard]] MORPH_API std::optional checkColumn(std::string const& columnId, + std::span columns, + std::function const& mayRead); + +/// @brief The ids of @p asked in the order of @p columns, each once. +/// +/// An id @p columns lacks is dropped; `validate` refuses such an id before it +/// calls this. +/// @param columns The table's columns, in their declared order. +/// @param asked Column ids in any order, duplicates allowed. +/// @return The ids of @p columns that @p asked names, in the order of @p columns. +[[nodiscard]] MORPH_API std::vector orderedColumns(std::span columns, + std::vector const& asked); + +/// @brief The members of a query's `oneOf` entries, counted against the per-entry and per-query bounds. +struct MORPH_API SetTally { + /// @brief Members of every set so far. + std::size_t values = 0; + /// @brief Bytes of those members. + std::size_t bytes = 0; + + /// @brief Counts the sets of @p entries. + /// @param entries The entries of one column or group. + /// @param column The column, for the error; empty for a group. + /// @param limits The bounds. + /// @return `LimitExceeded` naming @p column when one set is over `maxSetValues`, or nothing. + [[nodiscard]] std::optional add(std::span entries, std::string const& column, + QueryLimits const& limits); +}; + +/// @brief The columns of a declared group. +/// @param groups The table's declared groups. +/// @param groupId A group's id. +/// @return Its columns, or nothing when no group has that id. +[[nodiscard]] MORPH_API std::optional> groupColumns( + std::span groups, std::string_view groupId); + +/// @brief An `UnknownColumn` error for a group id no declared group has. +/// @param groupId The id. +/// @return The error, naming the id. +[[nodiscard]] MORPH_API TableError unknownGroup(std::string const& groupId); /// @brief Checks a filter's columns, entry counts and value lengths. /// @param filters The filter. /// @param columns The row schema's columns. /// @param limits The bounds. /// @param mayRead Whether the principal may read a column. +/// @param groups The table's declared groups, which a group filter's `group` names. /// @return The first violation, or nothing. -[[nodiscard]] inline std::optional checkFilters(FilterSpec const& filters, - std::span columns, - QueryLimits const& limits, - std::function const& mayRead) { - if (filters.columns.size() > limits.maxFilterColumns) { - return limitError({}, "too many filtered columns"); - } - for (auto const& [columnId, filter] : filters.columns) { - if (auto error = checkColumn(columnId, columns, mayRead)) { - return error; - } - if (filter.include.size() + filter.exclude.size() > limits.maxEntries) { - return limitError(columnId, "too many filter entries"); - } - if (anyTooLong(filter.include, limits.maxTextLength) || anyTooLong(filter.exclude, limits.maxTextLength)) { - return limitError(columnId, "filter value too long"); - } - } - if (filters.groups.size() > limits.maxGroups) { - return limitError({}, "too many filter groups"); - } - for (auto const& group : filters.groups) { - if (group.columns.size() > limits.maxGroupColumns || group.include.size() > limits.maxEntries) { - return limitError({}, "filter group too large"); - } - for (auto const& columnId : group.columns) { - if (auto error = checkColumn(columnId, columns, mayRead)) { - return error; - } - } - if (anyTooLong(group.include, limits.maxTextLength)) { - return limitError({}, "filter value too long"); - } - } - return std::nullopt; -} +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a run of independent rules, one `if` each, in the order they are reported; splitting scatters that order. +[[nodiscard]] MORPH_API std::optional checkFilters(FilterSpec const& filters, + std::span columns, + QueryLimits const& limits, + std::function const& mayRead, + std::span groups = {}); + +/// @brief Checks a distinct-values request, clamping its `limit`. +/// +/// Exactly one of `column` and `group` is set (`InvalidSpec`). The column, or every column of the declared group, +/// exists and the caller may read it, since a values list is a read of the column (`UnknownColumn` naming a group +/// no declaration has). `search` is at most `maxTextLength` bytes and `offset` within `0..maxOffset`, `limit` not +/// negative (`LimitExceeded`). A bucket other than `Value` needs date or date-time columns (`InvalidSpec`), and +/// `Custom` columns list no values (`UnsupportedOperator`). +/// @param request The request; its `limit` is clamped to `maxLimit`. +/// @param columns The table's columns. +/// @param limits The bounds. +/// @param mayRead Whether the caller may read a column; empty allows every column. +/// @param groups The table's declared groups, which `request.group` names. +/// @return The first violation, or nothing. +[[nodiscard]] MORPH_API std::optional checkDistinct(DistinctRequest& request, + std::span columns, + QueryLimits const& limits, + std::function const& mayRead, + std::span groups = {}); } // namespace detail @@ -219,53 +419,69 @@ namespace detail { /// Every column named must be one of @p columns, a closed set, and one the /// principal may read: a filter on a hidden column is an oracle for its value, /// so hiding a column is not a security control. `page.limit` is clamped; -/// every other bound is a refusal. +/// every other bound is a refusal. A `columns` list is put in the order of +/// @p columns with each id once, so every caller of `validate` or `apply` +/// sees it that way; an absent list stays absent and an empty one empty. +/// A keyed query has no page, so `keys` with a non-zero `page.offset` is +/// `InvalidSpec`; the keys are bounded by `maxKeys`, and a text key by +/// `maxTextLength`; the retained keys by `maxRetained`, and a text one by +/// `maxTextLength`. A `distinct` request is held to `detail::checkDistinct`, +/// and a query setting both `keys` and `distinct` is `InvalidSpec`. /// @param query The query, as received. /// @param columns The row schema's columns. /// @param limits The bounds. /// @param mayRead Whether the principal may read a column; empty allows every column. -/// @return The query with its limit clamped, or the first violation. -[[nodiscard]] inline std::expected validate( +/// @param groups The table's declared groups (`DataSource::groups()`), which a group filter's or a distinct +/// request's `group` names. +/// @return The query with its limits clamped and its `columns` ordered, or the first violation. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a run of independent rules, one `if` each, in the order they are reported; splitting scatters that order. +[[nodiscard]] MORPH_API std::expected validate( TableQuery query, std::span columns, QueryLimits const& limits = {}, - std::function const& mayRead = {}) { - if (query.page.offset < 0 || query.page.offset > limits.maxOffset) { - return std::unexpected(detail::limitError({}, "page.offset out of range")); - } - if (query.page.limit < 0) { - return std::unexpected(detail::limitError({}, "page.limit is negative")); - } - query.page.limit = std::min(query.page.limit, limits.maxLimit); - if (query.sort.size() > limits.maxSortKeys) { - return std::unexpected(detail::limitError({}, "too many sort keys")); - } - for (auto const& key : query.sort) { - if (auto error = detail::checkColumn(key.column, columns, mayRead)) { - return std::unexpected(std::move(*error)); - } - } - if (auto error = detail::checkFilters(query.filters, columns, limits, mayRead)) { - return std::unexpected(std::move(*error)); - } - return query; -} + std::function const& mayRead = {}, std::span groups = {}); + +/// @brief The data levels a query needs, by what it needs them for. +struct LevelsNeeded { + /// @brief Levels of the sorted and filtered columns: the view's membership and order depend on them for every + /// row. + std::vector order; + /// @brief Levels of the columns the query names: needed only for the rows of the reply. + std::vector display; +}; -/// @brief Escapes `%`, `_` and the escape character for a SQL `LIKE` -/// pattern, so a database-backed server keeps them ordinary characters -/// as the filter semantics require. -/// @param text A filter value. -/// @param escape The `ESCAPE` character the query declares. -/// @return The escaped text; wrap it in `%` for `contains` and so on. -[[nodiscard]] inline std::string escapeLikePattern(std::string_view text, char escape = '\\') { - std::string out; - out.reserve(text.size()); - for (char const character : text) { - if (character == '%' || character == '_' || character == escape) { - out.push_back(escape); - } - out.push_back(character); - } - return out; -} +namespace detail { + +/// @brief @p levels sorted, each once. +/// @param levels Level names, views into strings that outlive the call. +/// @return The levels as strings. +[[nodiscard]] MORPH_API std::vector sortedLevels(std::vector levels); + +} // namespace detail + +/// @brief The levels @p query needs: `order` for the columns it sorts and filters, `display` for the columns it +/// names. +/// +/// `order` is the levels of the columns `apply` builds keys for: every sort key's column, and the columns the +/// compiled filter reads. The filter is compiled here as `apply` compiles it, so a filtered column without an entry, +/// a group without an `include` entry, and a group's column on which none of its entries compiles add nothing: a +/// filter that reads no cell of a level does not need it. A filter that does not compile adds nothing either, since +/// `apply` refuses the query; a group filter naming a declared group is compiled through @p groups. A `distinct` +/// request adds the level of the column, or of every column of the group, it lists, which is read for every +/// candidate row. `display` is the levels of `query.columns`, or of every column @p mayRead allows when +/// `columns` is absent: a caller that does not say what it shows is taken to show everything. Both are sorted, +/// without duplicates, and never hold the base level; a level may be in both. No row is read. Called on the query +/// `validate` returned; a name that is no column is skipped. +/// @param query The validated query. +/// @param columns The table's columns. +/// @param mayRead Whether the caller may read a column; empty allows every column. +/// @param services The services `apply` compiles the filter with: whether an entry applies to a date column depends +/// on the date parser. Null members mean their defaults. +/// @param groups The table's declared groups. +/// @return The levels. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a run of independent rules, one `if` each, in the order they are reported; splitting scatters that order. +[[nodiscard]] MORPH_API LevelsNeeded levelsNeeded(TableQuery const& query, std::span columns, + std::function const& mayRead = {}, + Services const& services = {}, + std::span groups = {}); /// @brief How `apply` runs. struct ApplyOptions { @@ -286,314 +502,530 @@ struct PageRows { std::optional total; /// @brief The view row of `rows[0]`. std::int64_t offset = 0; + /// @brief `AtLeast` while rows are undecided, since the view may still grow; `Exact` otherwise. + TotalKind totalKind = TotalKind::Exact; + /// @brief Rows the filter can neither admit nor reject until a level loads. They are in no page. + std::int64_t undecided = 0; + /// @brief The order levels with a load wanted or in flight for at least one row. + std::vector awaiting; + /// @brief The order levels whose load failed for at least one row, and is not being tried again yet. + std::vector failed; + /// @brief A keyed query only: the view row of each of `rows`. + std::vector indices; + /// @brief A distinct-values query only: the values; `rows` is then empty. + std::optional distinct; + /// @brief The view's membership (`MembershipDigest::text`); empty on a distinct-values reply. + std::string viewRevision; + /// @brief The indices, into `rows`, of the retained rows the filter rejects, ascending. + std::vector unmatched; }; -/// @brief Runs @p query over @p source in the calling thread: the reference -/// implementation of `server` mode. -/// @param source The server's rows. -/// @param query The request body's table query. -/// @param options Limits, services and column access. -/// @return The page, or the typed error the client shows. -[[nodiscard]] inline std::expected apply(DataSource const& source, TableQuery const& query, - ApplyOptions const& options = {}) { - auto const columns = source.columns(); - auto checked = validate(query, columns, options.limits, options.mayRead); - if (!checked) { - return std::unexpected(std::move(checked.error())); - } - // One copy of the services for this call, the filter's operands included: - // a collator that is not safe to share clones itself here, so concurrent - // calls never fold on the one the caller passed. - auto services = options.services.forTask(); - auto filter = compileFilterGuarded(checked->filters, columns, services); - if (!filter) { - return std::unexpected(std::move(filter.error())); - } - detail::JobInput input; - input.snapshot = source.snapshot(); - input.columns.assign(columns.begin(), columns.end()); - input.services = std::move(services); - input.keys.resize(columns.size()); - for (auto const& key : checked->sort) { - if (auto const column = detail::findColumn(columns, key.column)) { - input.needed.push_back(*column); - } - } - for (auto const column : filter->columnsUsed()) { - input.needed.push_back(column); - } - std::ranges::sort(input.needed); - auto const [first, last] = std::ranges::unique(input.needed); - input.needed.erase(first, last); - input.sort = checked->sort; - input.filter = std::make_shared(std::move(*filter)); - input.previousSnapshot = input.snapshot; - detail::ViewJob job{std::move(input)}; - static_cast(job.step(kNoDeadline, ::core::async::StopToken{})); - if (job.failure()) { - return std::unexpected(TableError{ - .code = TableErrorCode::ServiceFailed, .column = {}, .message = "a service failed: " + *job.failure()}); - } - auto const view = job.takeResult().view; - - PageRows out; - out.offset = checked->page.offset; - auto const count = static_cast(view.size()); - if (count <= options.limits.totalCap) { - out.total = count; - } - auto const begin = std::min(checked->page.offset, count); - // Compared, not added: `maxLimit` may be as large as INT64_MAX. - auto const end = checked->page.limit >= count - begin ? count : begin + checked->page.limit; - for (auto i = begin; i < end; ++i) { - out.rows.push_back(view[static_cast(i)]); - } - return out; -} +namespace detail { -// ── Query plans ───────────────────────────────────────────────────────────── +/// @brief A query's view over one snapshot: what `pageRows` pages. +struct ComputedView { + /// @brief The sorted, filtered view, as source rows. + std::vector rows; + /// @brief The rows the filter could neither admit nor reject, source rows ascending. They are in no view. + std::vector undecided; + /// @brief The keys of `rows`, as a set: the view's membership. + MembershipDigest digest; +}; -/// @brief What a sort or a filter on a column is used for, as `planQuery`'s `translatable` predicate sees it. -enum class PlanUse : std::uint8_t { - Sort, ///< The column orders the view. - Filter, ///< The column is filtered. +/// @brief Computes the view of a validated query over @p source in the calling thread. +/// @param source The rows; read through one snapshot. +/// @param validated The query as `validate` returned it. +/// @param options The services; `validate` applied its limits and `mayRead`. +/// @return The view, or the typed error: `ServiceFailed` from a throwing service, `SourceContract` when a sorted +/// or filtered base-level column holds an unloaded cell, or when a sorted or filtered column is `Measure` and +/// `options.services.units` is null. +[[nodiscard]] MORPH_API std::expected computeView(DataSource const& source, + TableQuery const& validated, + ApplyOptions const& options); + +/// @brief The source row of a key, or nothing when the snapshot has no row with that key. +using SourceRowOf = std::function(RowId const&)>; + +/// @brief What a view-row table holds for a source row that is not in the view. +inline constexpr std::uint32_t kNotInView = std::numeric_limits::max(); + +/// @brief Fills a keyed page's `rows` and `indices`: the rows of @p keys in the view, ascending by view row. +/// @param view The view. +/// @param snapshot The snapshot the view was computed over. +/// @param keys The keys asked for. +/// @param viewRowOf View row by source row, `kNotInView` for a row not in the view; built from @p view when +/// empty. +/// @param sourceRowOf A key's source row; when empty, the snapshot's row ids are scanned once. +/// @param out The page to fill. +MORPH_API void keyedRows(ComputedView const& view, RowSnapshot const& snapshot, std::span keys, + std::span viewRowOf, SourceRowOf const& sourceRowOf, PageRows& out); + +/// @brief The page of a view: its rows, total and undecided count. +/// +/// A query without `keys` gets the view rows its `page` names. A keyed query gets the source rows whose key is in +/// `keys` and whose row is in the view, ascending by view row, each one's view row in `indices`, and offset 0. +/// Either way `total`, `totalKind` and `undecided` are the whole view's. +/// @param view The view, as `computeView` returns it. +/// @param snapshot The snapshot the view was computed over. +/// @param validated The query as `validate` returned it. +/// @param limits The bounds; a total above `totalCap` is left out. +/// @param viewRowOf View row by source row, `kNotInView` for a row not in the view; built on demand when empty. +/// Read by a keyed query only. +/// @param sourceRowOf A key's source row, one call a key; when empty, a keyed query scans the snapshot's row ids +/// once. +/// @return The page. +[[nodiscard]] MORPH_API PageRows pageRows(ComputedView const& view, RowSnapshot const& snapshot, + TableQuery const& validated, QueryLimits const& limits, + std::span viewRowOf = {}, + SourceRowOf const& sourceRowOf = {}); + +/// @brief A view with retained rows merged in: what `mergeRetained` returns. +struct MergedView { + /// @brief Source rows, in view order. + std::vector order; + /// @brief View rows of retained rows the filter rejects, ascending. + std::vector unmatched; + /// @brief The rows the filter can neither admit nor reject, less the retained ones, which are in the view. + std::int64_t undecided = 0; + /// @brief The membership of `order`: the base digest with each admitted row's key added. + MembershipDigest digest; }; -/// @brief The operators a planned condition carries. -using FilterOp = CompiledFilter::Op; +/// @brief Merges retained rows into a base view: the view the sort gives over the base rows and the retained rows +/// the base lacks, each of those in it whatever the filter says. +/// +/// A retained row the filter cannot decide is in the view, not undecided; one it rejects is listed in `unmatched`. +/// Its cost is that of the retained rows: a scan of @p baseOrder and a binary search of it per admitted row. +/// @param baseOrder The view of the sort and filter, as source rows sorted by @p before. +/// @param baseUndecided The base view's undecided rows. +/// @param baseDigest The base view's membership. +/// @param retainedRows The retained rows the source has, as source rows. +/// @param before The query's comparator over the sort's keys, ties to the lower source row. +/// @param match What the filter says of a source row. +/// @param keyOf A source row's key. +/// @return The merged view. +[[nodiscard]] MORPH_API MergedView mergeRetained(std::span baseOrder, std::int64_t baseUndecided, + MembershipDigest baseDigest, + std::span retainedRows, + std::function const& before, + std::function const& match, + std::function const& keyOf); + +/// @brief The keys of a few rows of a snapshot, built as they are first asked for: what orders and filters retained +/// rows against a cached view, whose key columns are not kept. +/// +/// Each row asked for gets a local index into key columns of the needed columns alone, so the cost is that of the +/// rows read, not of the snapshot. +class MORPH_API SparseKeys { +public: + /// @brief Keys of @p needed over @p snapshot. + /// @param snapshot The rows; outlives this. + /// @param columns The snapshot's columns; outlive this. + /// @param services The services the keys are built with; outlive this. + /// @param needed The columns whose keys are read: the sort's and the filter's. + SparseKeys(RowSnapshot const& snapshot, std::span columns, Services const& services, + std::vector needed) + : _snapshot{&snapshot}, _columns{columns}, _services{&services}, _needed{std::move(needed)} { + grow(16); + } -/// @brief A planned operand, typed by its column's kind: `Rational` for integer, key, decimal and quantity columns -/// (quantities in the canonical unit), `double` for numbers, `int64` for dates (days), date-times (UTC -/// seconds) and booleans (0 or 1), `string` for text (folded, or raw for a case-sensitive condition), and -/// empty when the operator takes no operand. -using PlannedOperand = std::variant; + SparseKeys(SparseKeys const&) = delete; + SparseKeys& operator=(SparseKeys const&) = delete; + SparseKeys(SparseKeys&&) = delete; + SparseKeys& operator=(SparseKeys&&) = delete; + ~SparseKeys() = default; -/// @brief One sort key of a plan. -struct PlannedSortKey { - /// @brief The column's id. - std::string column; - /// @brief How the column orders. - ColumnKind kind = ColumnKind::Text; - /// @brief For a `Custom` column, its comparator's name; empty otherwise. - std::string comparator; - /// @brief The key's direction. - SortDirection dir = SortDirection::Ascending; -}; + /// @brief A row's local index, its keys built at the first call. + /// @param row The source row. + /// @return Its index into the key columns `pointers` gives. + [[nodiscard]] std::uint32_t local(std::uint32_t row); -/// @brief One condition of a plan: an operator and its parsed operands on one column. -struct PlannedCondition { - /// @brief The column's id. - std::string column; - /// @brief The column's kind. - ColumnKind kind = ColumnKind::Text; - /// @brief The operator. - FilterOp op = FilterOp::IsEmpty; - /// @brief The operand, typed by `kind`. - PlannedOperand value; - /// @brief `Between`'s second operand, typed by `kind`; empty otherwise. - PlannedOperand upper; - /// @brief The operand as the request gave it (`Between`: the first). - std::string text; - /// @brief `Between`'s second operand as the request gave it. - std::string upperText; - /// @brief Whether text operators compare the text as given rather than folded. - bool caseSensitive = false; -}; + /// @brief The key columns by column index, null for a column not needed; valid until the next `local`. + /// @return The pointers. + [[nodiscard]] std::span pointers() const noexcept { return _pointers; } -/// @brief The conditions on one column. -struct PlannedColumnFilter { - /// @brief The column's id. - std::string column; - /// @brief How `include` entries combine. - Combine combine = Combine::Any; - /// @brief Conditions a row must meet; empty means none. - std::vector include; - /// @brief Conditions that reject a row when any matches; empty for a group's columns. - std::vector exclude; +private: + void fill(std::uint32_t position); + + void grow(std::size_t capacity); + + RowSnapshot const* _snapshot; + std::span _columns; + Services const* _services; + std::vector _needed; + std::size_t _capacity = 0; + std::vector> _keys; + std::vector _pointers; + std::vector _rows; + std::unordered_map _local; }; -/// @brief A filter over several columns: a row matches when the group's entries match on any of its columns. -struct PlannedGroup { - /// @brief The columns, each with the entries that apply to it; `combine` is the group's. - std::vector columns; +/// @brief A view with its retained rows merged in, and the view rows of those the filter rejects. +struct RetainedView { + /// @brief The merged view. + ComputedView view; + /// @brief View rows of retained rows the filter rejects, ascending. + std::vector unmatched; }; -/// @brief A `TableQuery` validated and normalised for translation into a store's own query. -struct QueryPlan { - /// @brief The sort chain, most significant key first. A store-backed model appends its row key, ascending, to - /// this (or uses it alone when this is empty) so the order is total. - std::vector sort; - /// @brief The column filters, ANDed, in evaluation order. - std::vector filters; - /// @brief The groups, ANDed with `filters`. - std::vector groups; - /// @brief The first view row wanted, within `[0, QueryLimits::maxOffset]`. - std::int64_t offset = 0; - /// @brief The rows wanted, clamped to `QueryLimits::maxLimit`; zero asks for the count only. - std::int64_t limit = 0; - /// @brief `QueryLimits::totalCap`: a count above it may be reported as a lower bound. - std::int64_t totalCap = 0; +/// @brief Merges a validated query's retained rows into the view of its sort and filter, for one request: the +/// view's own value, which a cache may share, is not changed. +/// @param base The view of the sort and filter. +/// @param source The rows the view was computed over: their columns and groups. +/// @param snapshot The snapshot the view was computed over. +/// @param validated The query as `validate` returned it. +/// @param options The services; `validate` applied its limits and `mayRead`. +/// @param sourceRowOf A key's source row; when empty, the snapshot's row ids are scanned once. +/// @return The merged view, or the filter's compile error. +[[nodiscard]] MORPH_API std::expected retainedView( + ComputedView const& base, DataSource const& source, RowSnapshot const& snapshot, TableQuery const& validated, + ApplyOptions const& options, SourceRowOf const& sourceRowOf = {}); + +/// @brief Sets a page's `unmatched`: the indices, into its `rows`, of those whose view row is in @p unmatched. +/// @param page The page; a keyed page's view rows are its `indices`, a page's its offset onwards. +/// @param unmatched View rows of retained rows the filter rejects, ascending. +MORPH_API void markUnmatched(PageRows& page, std::span unmatched); + +/// @brief The page of a view for a validated query: `pageRows` over the view, with the query's retained rows merged +/// in per request when it retains any. +/// @param view The view of the sort and filter, as `computeView` returns it or a cache holds it. +/// @param source The rows the view was computed over. +/// @param snapshot The snapshot the view was computed over. +/// @param validated The query as `validate` returned it. +/// @param options The limits and services. +/// @param viewRowOf As for `pageRows`; read only when the query retains nothing, since a merged view has its own. +/// @param sourceRowOf As for `pageRows`. +/// @return The page, or the filter's compile error. +[[nodiscard]] MORPH_API std::expected viewPage( + ComputedView const& view, DataSource const& source, RowSnapshot const& snapshot, TableQuery const& validated, + ApplyOptions const& options, std::span viewRowOf = {}, SourceRowOf const& sourceRowOf = {}); + +/// @brief What `distinctOver` reads: one snapshot, the key columns at hand, and the filter of the other columns. +struct DistinctInput { + /// @brief The rows. + std::shared_ptr snapshot; + /// @brief The columns of @p snapshot. + std::span columns; + /// @brief Key columns by column index, built over `snapshot`; null where not built, or empty for none. + std::span const> keys; + /// @brief The filter, the listed column's own entry already erased. + FilterSpec filters; + /// @brief The services for this call alone (`Services::forTask`). + Services services; + /// @brief The bounds; `totalCap` caps the `distinct` count. + QueryLimits limits; + /// @brief The table's declared groups, which the filter's and the request's `group` name. + std::span groups; }; -namespace detail { - -/// @brief The operand a compiled entry holds in @p slot, typed by the column's kind. -/// @param kind The column's kind. -/// @param entry The compiled entry. -/// @param slot 0, or 1 for `Between`'s second operand. -/// @return The operand. -[[nodiscard]] inline PlannedOperand plannedOperand(ColumnKind kind, CompiledFilter::Entry const& entry, - std::size_t slot) { - switch (kind) { - case ColumnKind::Integer: - case ColumnKind::Key: - case ColumnKind::Decimal: - case ColumnKind::Quantity: - return entry.exact.at(slot); - case ColumnKind::Number: - return entry.reals.at(slot); - case ColumnKind::Date: - case ColumnKind::DateTime: - case ColumnKind::Bool: - return entry.ints.at(slot); - case ColumnKind::Text: - return slot == 0 ? PlannedOperand{entry.text} : PlannedOperand{}; - case ColumnKind::Custom: - default: - return {}; - } +/// @brief The civil date of a count of days since 1970-01-01. +/// @param days The days. +/// @return The date. +[[nodiscard]] inline std::chrono::year_month_day civilDate(std::int64_t days) { + return std::chrono::year_month_day{std::chrono::sys_days{std::chrono::days{days}}}; } -/// @brief A compiled entry as a planned condition. -/// @param info The column. -/// @param entry The entry. -/// @return The condition. -[[nodiscard]] inline PlannedCondition plannedCondition(ColumnInfo const& info, CompiledFilter::Entry const& entry) { - PlannedCondition out{.column = info.id, - .kind = info.kind, - .op = entry.op, - .value = {}, - .upper = {}, - .text = entry.operands[0], - .upperText = entry.operands[1], - .caseSensitive = entry.caseSensitive}; - if (entry.op != FilterOp::IsEmpty && entry.op != FilterOp::NotEmpty) { - out.value = plannedOperand(info.kind, entry, 0); - if (entry.op == FilterOp::Between) { - out.upper = plannedOperand(info.kind, entry, 1); - } - } - return out; +/// @brief Days since 1970-01-01 of a civil date. +/// @param date The date. +/// @return The days. +[[nodiscard]] inline std::int64_t daysOf(std::chrono::year_month_day const& date) { + return std::chrono::sys_days{date}.time_since_epoch().count(); } -/// @brief A compiled column filter as a planned one. -/// @param columns The table's columns. -/// @param filter The compiled filter. -/// @return The planned filter. -[[nodiscard]] inline PlannedColumnFilter plannedColumnFilter(std::span columns, - CompiledFilter::Column const& filter) { - auto const& info = columns[filter.column]; - PlannedColumnFilter out{.column = info.id, .combine = filter.combine, .include = {}, .exclude = {}}; - for (auto const& entry : filter.include) { - out.include.push_back(plannedCondition(info, entry)); - } - for (auto const& entry : filter.exclude) { - out.exclude.push_back(plannedCondition(info, entry)); - } - return out; -} +/// @brief A date as `YYYY-MM-DD`. +/// @param days Days since 1970-01-01. +/// @return The text. +[[nodiscard]] MORPH_API std::string isoDate(std::int64_t days); + +/// @brief The day a date-time falls on, in UTC. +/// @param seconds Seconds since 1970-01-01T00:00:00Z. +/// @return Days since 1970-01-01. +[[nodiscard]] MORPH_API std::int64_t dayOfSeconds(std::int64_t seconds); + +/// @brief A date-time as `YYYY-MM-DDTHH:MM:SSZ`. +/// @param seconds Seconds since 1970-01-01T00:00:00Z. +/// @return The text. +[[nodiscard]] MORPH_API std::string isoDateTime(std::int64_t seconds); + +/// @brief The first and last day of the bucket a day is in. +/// @param day Days since 1970-01-01. +/// @param bucket `Year`, `Month` or `Day`. +/// @return The bucket's first and last day. +[[nodiscard]] MORPH_API std::pair bucketDays(std::int64_t day, DateBucket bucket); + +/// @brief One value while `distinctOver` groups the rows. +struct DistinctGroup { + /// @brief The value's first candidate row, in source order. + std::uint32_t first = 0; + /// @brief The place, among the listed columns, of the first column of `first` that holds it. + std::size_t column = 0; + /// @brief The rows that hold it. + std::int64_t count = 0; + /// @brief The last row counted, so a row holding the value in several columns counts once. + std::uint32_t last = 0; +}; -/// @brief The first sort or filter column of @p query that @p translatable refuses. -/// @param query The validated query. -/// @param translatable The model's predicate; empty accepts everything. -/// @return The `Unavailable` error, or nothing. -[[nodiscard]] inline std::optional untranslatable( - TableQuery const& query, std::function const& translatable) { - if (!translatable) { - return std::nullopt; - } - auto const refuse = [](std::string const& column, std::string_view use) { - return TableError{.code = TableErrorCode::Unavailable, - .column = column, - .message = "column " + column + " cannot be " + std::string{use} + " by this table"}; - }; - for (auto const& key : query.sort) { - if (!translatable(key.column, PlanUse::Sort)) { - return refuse(key.column, "sorted"); - } - } - for (auto const& [column, filter] : query.filters.columns) { - if (!translatable(column, PlanUse::Filter) && (!filter.include.empty() || !filter.exclude.empty())) { - return refuse(column, "filtered"); - } - } - for (auto const& group : query.filters.groups) { - for (auto const& column : group.columns) { - if (!translatable(column, PlanUse::Filter)) { - return refuse(column, "filtered"); +/// @brief Groups the candidate rows of the listed columns by a key: a row counts once for each value it holds in +/// any of them, once in `blanks` when one of its cells is empty, and once in `invalid` when one is invalid. +/// @tparam Key The grouping key's type. +/// @tparam Hash Its hash. +/// @param rows The candidate rows, source order. +/// @param columns The listed columns' keys, in the order they are listed. +/// @param keyOf The grouping key of a valid cell, from its column's keys and its row. +/// @param groups Receives one entry a value, in order of first appearance. +/// @param out Receives `blanks`, `invalid` and `partial`. +template > +void groupRows(std::span rows, std::span columns, auto const& keyOf, + std::vector& groups, DistinctValues& out) { + std::unordered_map index; + for (auto const row : rows) { + bool blank = false; + bool invalid = false; + for (std::size_t at = 0; at < columns.size(); ++at) { + auto const& keys = *columns[at]; + switch (keys.states[row]) { + case CellState::Empty: + blank = true; + continue; + case CellState::Invalid: + invalid = true; + continue; + case CellState::Unloaded: + out.partial = true; + continue; + case CellState::Valid: + default: + break; + } + auto const [found, added] = index.try_emplace(keyOf(keys, row), groups.size()); + if (added) { + groups.push_back(DistinctGroup{.first = row, .column = at, .count = 1, .last = row}); + continue; + } + auto& group = groups[found->second]; + if (group.last != row) { + ++group.count; + group.last = row; } } + out.blanks += blank ? 1 : 0; + out.invalid += invalid ? 1 : 0; } - return std::nullopt; } +/// @brief Orders two valid cells of one kind, possibly in two columns, as a sort of one column would. +/// @param left One cell's column keys. +/// @param leftRow Its row. +/// @param right The other cell's column keys, of the same kind. +/// @param rightRow Its row. +/// @return Negative, zero or positive as the left cell orders before, with, or after the right one. +[[nodiscard]] MORPH_API int compareValues(KeyColumn const& left, std::uint32_t leftRow, KeyColumn const& right, + std::uint32_t rightRow); + +/// @brief A cell of a `Measure` column as a measure: what its key was read from. +/// @param cell The cell; its key is valid. +/// @param units The registry the key was built with. +/// @return The measure: a plain number in the ratio's unit, text read as an operand; nothing for any other cell. +[[nodiscard]] MORPH_API std::optional measureOf(Cell const& cell, UnitRegistry const* units); + +/// @brief The `text` and `operand` of a value: from its first row. +/// @param snapshot The rows. +/// @param column The column's index. +/// @param info The column. +/// @param keys The column's keys. +/// @param row The value's first row. +/// @param bucket The request's bucket. +/// @param units The registry a `Measure` column's keys were built with. +/// @return The value, its count zero. A measure's `text` is its first row's amount and its unit's symbol (the ratio's +/// unit shows none), its `operand` the amount and the unit's id, as a filter takes it. +[[nodiscard]] MORPH_API DistinctValue describeValue(RowSnapshot const& snapshot, std::size_t column, + ColumnInfo const& info, KeyColumn const& keys, std::uint32_t row, + DateBucket bucket, UnitRegistry const* units = nullptr); + +/// @brief The distinct values of one column, or pooled over a group's columns, over the rows @p input's filter +/// admits: the one core that `distinctValues`, `Engine::distinctValues` and a server's reply share. +/// +/// Builds the key columns @p input lacks (the filter's and the listed columns') on the calling thread, into locals. +/// A row the filter leaves undecided is in no count and sets `partial`; an unloaded cell in a listed column is in no +/// count and sets `partial`, and the row's loaded cells still count. An unloaded cell in a base-level column the +/// list reads is `SourceContract`, as a view job reports it, and so is a listed `Measure` column with no unit +/// registry. Valid cells group by the key the column sorts and filters by (text by its fold; a date bucket by its +/// first day; a measure by its dimension's place and its base amount); a row counts once per value it holds, once in +/// `blanks` when it has an empty cell and once in `invalid` when it has an invalid one. A value's text is that of +/// its first row and, within the row, its first column. Values are searched by their folded text, ordered ascending +/// by their keys (ties by first row), counted up to `totalCap`, and then sliced by `offset` and `limit`. +/// @param input The snapshot, columns, keys, filter, services, bounds and groups. +/// @param validated The request as `detail::checkDistinct` left it. +/// @return The values; `ServiceFailed` from a throwing service; `SourceContract` for an unloaded cell in a base-level +/// column it reads; or the filter's compile error. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] MORPH_API std::expected distinctOver(DistinctInput const& input, + DistinctRequest const& validated); + +/// @brief Removes a values list's own filter: the column's entry, or every group filter naming the group. +/// @param filters The filter. +/// @param request The values list's request. +MORPH_API void withoutOwnFilter(FilterSpec& filters, DistinctRequest const& request); + } // namespace detail -/// @brief Validates @p query and normalises it into a plan a model translates into its own query. +/// @brief The distinct values of one column, or pooled over a declared group's columns, with their counts, over the +/// rows the other filters of @p query leave. /// -/// In order: `validate`, the `translatable` refusal, the guarded compile step `apply` also uses, and a pure -/// projection of the compiled filter. A refusal is therefore the value `apply` returns for the same query, except -/// the `Unavailable` of `translatable`, which only a model gives. `apply` over the same rows is the oracle the -/// model's pages are held to (`conformanceFailures`). -/// @param query The request body's table query. -/// @param columns The row schema's columns. -/// @param limits The bounds of `validate`. -/// @param mayRead Whether the principal may read a column; empty allows every column. -/// @param services The collator and date parser operands are compiled with; null members mean their defaults. -/// @param translatable Whether the model can sort or filter a column; empty accepts all. A column it refuses is -/// `Unavailable`, naming the column. -/// @return The plan, or the typed error the client shows. -[[nodiscard]] inline std::expected planQuery( - TableQuery const& query, std::span columns, QueryLimits const& limits = {}, - std::function const& mayRead = {}, Services const& services = {}, - std::function const& translatable = {}) { - auto checked = validate(query, columns, limits, mayRead); - if (!checked) { - return std::unexpected(std::move(checked.error())); - } - if (auto error = detail::untranslatable(*checked, translatable)) { +/// The source's groups are checked (`detail::checkGroups`), and the query and the request validated together +/// (`validate` with `distinct` set to @p request). The column's own entry in `query.filters.columns`, or every +/// group filter naming the request's group, is removed, so a value the list's own filter left out is still listed. +/// Runs in the calling thread over one snapshot, building the key columns it reads. +/// @param source The rows. +/// @param query The query whose filters narrow the rows; its page, sort and columns are not read. +/// @param request The column, search, bucket and page of values. +/// @param options Limits, services and column access. +/// @return The values, or the typed error the client shows. +[[nodiscard]] MORPH_API std::expected distinctValues(DataSource const& source, + TableQuery const& query, + DistinctRequest const& request, + ApplyOptions const& options = {}); + +inline std::expected Engine::distinctValues(DistinctRequest const& request) const { + auto validated = request; + QueryLimits const limits; + auto const groups = _source->groups(); + if (auto error = detail::checkGroups(_columns, groups)) { return std::unexpected(std::move(*error)); } - auto compiled = compileFilterGuarded(checked->filters, columns, services.forTask()); - if (!compiled) { - return std::unexpected(std::move(compiled.error())); - } - QueryPlan plan; - plan.offset = checked->page.offset; - plan.limit = checked->page.limit; - plan.totalCap = limits.totalCap; - for (auto const& key : checked->sort) { - auto const& info = columns[*detail::findColumn(columns, key.column)]; - plan.sort.push_back( - PlannedSortKey{.column = info.id, .kind = info.kind, .comparator = info.comparator, .dir = key.dir}); - } - for (auto const& filter : compiled->columns()) { - plan.filters.push_back(detail::plannedColumnFilter(columns, filter)); - } - for (auto const& group : compiled->groups()) { - PlannedGroup planned; - for (auto const& filter : group.columns) { - planned.columns.push_back(detail::plannedColumnFilter(columns, filter)); - } - plan.groups.push_back(std::move(planned)); + if (auto error = detail::checkDistinct(validated, _columns, limits, {}, groups)) { + return std::unexpected(std::move(*error)); } - return plan; + auto filters = _filterSpec; + detail::withoutOwnFilter(filters, validated); + detail::DistinctInput const input{.snapshot = _snapshot, + .columns = _columns, + .keys = _keysSnapshot == _snapshot + ? std::span const>{_keys} + : std::span const>{}, + .filters = std::move(filters), + .services = _options.services.forTask(), + .limits = limits, + .groups = groups}; + return detail::distinctOver(input, validated); } +/// @brief Runs @p query over @p source in the calling thread: the reference +/// implementation of `server` mode. +/// +/// `validate`, then `detail::computeView`, then `detail::pageRows`; a keyed +/// query finds its keys by scanning the snapshot's row ids once. A query with +/// `distinct` set is answered by `distinctValues`, with no rows. +/// @param source The server's rows. +/// @param query The request body's table query. +/// @param options Limits, services and column access. +/// @return The page, or the typed error the client shows: `SourceContract` +/// when a sorted or filtered base-level column holds an unloaded cell, +/// or when the source's declared groups break `detail::checkGroups`. +[[nodiscard]] MORPH_API std::expected apply(DataSource const& source, TableQuery const& query, + ApplyOptions const& options = {}); + +// ── Keys on the wire ──────────────────────────────────────────────────────── + +/// @brief Writes row keys as a change event carries them. +/// @param keys The keys. +/// @return Each key as raw JSON: an integer key as a JSON number, a text key as a JSON string. +[[nodiscard]] MORPH_API std::vector changeKeys(std::span keys); + +/// @brief Reads one row key of a change event back. +/// @param key The key as raw JSON. +/// @return The key: a JSON number that is an integer read exactly, a JSON string read as text; nothing for any +/// other JSON, which a reader takes as a change of the whole type. +[[nodiscard]] MORPH_API std::optional rowIdOf(glz::raw_json const& key); + // ── Typed rows ────────────────────────────────────────────────────────────── +/// @brief One entry of a row type's `columnLevels()`: the data level a column's cells need. +/// +/// A row type declares its levels once, as +/// `static constexpr std::array columnLevels() noexcept`. +struct ColumnLevel { + /// @brief The column, by the member's JSON name. + std::string_view column; + /// @brief The level; never empty, which is the base level every column has without an entry. + std::string_view level; +}; + +/// @brief A typed row's amount in a named unit: the member type of a `Measure` column. +/// +/// Its JSON is `{"num", "den", "unit"}`: the amount as a `Rational` is written, with the unit's string id beside it. +/// The id is resolved through the registry the row's source is given, and an id it does not hold is an invalid +/// cell. A row's schema marks such a property `x-measure` and lists no units, which are the application's at run +/// time. +struct MORPH_API MeasureValue { + /// @brief The amount. + math::Rational amount; + /// @brief The unit's id; empty is the ratio's unit. + std::string unit; + + /// @brief The JSON shape. + struct Wire { + /// @brief The amount's numerator. + std::int64_t num = 0; + /// @brief The amount's denominator. + std::int64_t den = 1; + /// @brief The unit's id. + std::string unit; + }; + + /// @brief Reads the JSON shape; the amount's places are k when the denominator is 10^k, else the most a + /// `Rational` holds, as a generic page reads an exact cell. + /// @param wire The shape as read. + void setWire(Wire const& wire); + + /// @brief The JSON shape. + /// @return The amount's canonical numerator and denominator, and the unit's id. + [[nodiscard]] Wire getWire() const { + return Wire{.num = amount.numerator, .den = amount.denominator, .unit = unit}; + } + + /// @brief Member-wise equality, the amount by value. + /// @param other The value to compare with. + /// @return `true` when the amounts are equal and the units are the same id. + [[nodiscard]] bool operator==(MeasureValue const& other) const = default; +}; + +/// @brief Whether @p level is loaded for @p row: how a typed table says which of its cells are unloaded. Empty +/// means every level is loaded. +/// @tparam Row The row type. +template +using LevelLoaded = std::function; + namespace detail { +/// @brief A row type that declares the levels of its columns. +template +concept HasColumnLevels = requires { + { Row::columnLevels() }; +}; + +/// @brief A row type that declares column groups. +template +concept HasColumnGroups = requires { + { Row::columnGroups() }; +}; + +/// @brief The column groups a row type declares, each labelled by its id. +/// @tparam Row The row type. +/// @return The groups; none when the row type declares none. +template +[[nodiscard]] std::vector declaredGroups() { + std::vector out; + if constexpr (HasColumnGroups) { + for (auto const& group : Row::columnGroups()) { + out.push_back(ColumnGroupInfo{.id = std::string{group.id}, + .label = std::string{group.id}, + .columns = {group.columns.begin(), group.columns.end()}}); + } + } + return out; +} + /// @brief `true` for `std::optional`. /// @tparam T A type. template @@ -633,6 +1065,8 @@ template return ColumnKind::Decimal; } else if constexpr (units::isQuantity) { return ColumnKind::Quantity; + } else if constexpr (std::is_same_v) { + return ColumnKind::Measure; } else if constexpr (std::is_same_v || std::is_same_v) { return ColumnKind::DateTime; } else if constexpr (MemberWrapper) { @@ -681,12 +1115,16 @@ template /// @brief A member value as a cell. /// @tparam T The member type. /// @param value The member. -/// @return The cell. +/// @param units The registry a `MeasureValue`'s unit id is resolved through; null resolves none. +/// @return The cell; a `MeasureValue` whose id @p units does not hold is a measure of `kUnknownUnit`, an invalid cell. template -[[nodiscard]] Cell toCell(T const& value) { +[[nodiscard]] Cell toCell(T const& value, UnitRegistry const* units = nullptr) { using V = std::remove_cvref_t; if constexpr (IsOptional::value) { - return value ? toCell(*value) : Cell{}; + return value ? toCell(*value, units) : Cell{}; + } else if constexpr (std::is_same_v) { + auto const unit = units != nullptr ? units->find(value.unit) : std::nullopt; + return Cell{Measure{.amount = value.amount, .unit = unit.value_or(kUnknownUnit)}}; } else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) { return Cell{value}; @@ -701,16 +1139,16 @@ template } else if constexpr (std::is_same_v) { return value.value ? toCell(*value.value) : Cell{}; } else if constexpr (MemberWrapper) { - return toCell(value.*(glz::meta::value)); + return toCell(value.*(glz::meta::value), units); } else { return writtenCell(value); } } -/// @brief Reads one column's cell from a row. +/// @brief Reads one column's cell from a row, a measure's unit through the registry given. /// @tparam Row The row type. template -using CellReader = Cell (*)(Row const&); +using CellReader = Cell (*)(Row const&, UnitRegistry const*); /// @brief One cell reader per key glaze writes, in key order. /// @tparam Row The row type. @@ -719,14 +1157,17 @@ template [[nodiscard]] std::vector> cellReaders() { constexpr auto count = glz::reflect::size; return [&](std::index_sequence) { - return std::vector>{ - +[](Row const& row) -> Cell { return toCell(morph::detail::reflectedMember(row)); }...}; + return std::vector>{+[](Row const& row, UnitRegistry const* units) -> Cell { + return toCell(morph::detail::reflectedMember(row), units); + }...}; }(std::make_index_sequence{}); } -/// @brief One column per key glaze writes, its kind from the value's type. +/// @brief One column per key glaze writes, its kind from the value's type and its level from `Row::columnLevels()` +/// when the row type declares it. /// @tparam Row The row type. /// @return The columns. +/// @throws std::invalid_argument when a `columnLevels()` entry names no column. template [[nodiscard]] std::vector reflectedColumns() { constexpr auto count = glz::reflect::size; @@ -736,9 +1177,19 @@ template ColumnInfo{.id = std::string{glz::reflect::keys[I]}, .kind = kindOf(std::declval()))>(), .comparator = {}, - .format = {}}), + .format = {}, + .level = {}}), ...); }(std::make_index_sequence{}); + if constexpr (HasColumnLevels) { + for (auto const& entry : Row::columnLevels()) { + auto const column = std::ranges::find(out, entry.column, &ColumnInfo::id); + if (column == out.end()) { + throw std::invalid_argument{"columnLevels() names no column: " + std::string{entry.column}}; + } + column->level = std::string{entry.level}; + } + } return out; } @@ -750,6 +1201,8 @@ template using RowKey = std::function; /// @brief A snapshot over a shared, immutable vector of typed rows. +/// +/// A cell of a column whose level @p loaded refuses for its row is `Unloaded`; the member is not read. /// @tparam Row A glaze-reflectable aggregate. template class RowsSnapshot final : public RowSnapshot { @@ -758,14 +1211,31 @@ class RowsSnapshot final : public RowSnapshot { /// @param rows The rows; shared, never modified. /// @param key The key projection. /// @param readers One cell reader per column. + /// @param levels Each column's level, by column index; null when no column has one. + /// @param loaded Whether a level is loaded for a row; empty when every level is. + /// @param units The registry a measure member's unit id is resolved through; null resolves none. RowsSnapshot(std::shared_ptr const> rows, RowKey key, - std::shared_ptr> const> readers) - : _rows{std::move(rows)}, _key{std::move(key)}, _readers{std::move(readers)} {} + std::shared_ptr> const> readers, + std::shared_ptr const> levels = nullptr, LevelLoaded loaded = {}, + std::shared_ptr units = nullptr) + : _rows{std::move(rows)}, + _key{std::move(key)}, + _readers{std::move(readers)}, + _levels{std::move(levels)}, + _loaded{std::move(loaded)}, + _units{std::move(units)} {} /// @brief The number of rows. /// @return Row count. [[nodiscard]] std::size_t rowCount() const override { return _rows->size(); } + /// @brief The rows vector's address without a level predicate, so a source rebuilt over the same vector has + /// the same identity; this snapshot's address with one, whose cells the predicate also decides. + /// @return The identity. + [[nodiscard]] void const* identity() const override { + return _loaded ? static_cast(this) : static_cast(_rows.get()); + } + /// @brief A row's key. /// @param row Row index. /// @return The key. @@ -776,7 +1246,12 @@ class RowsSnapshot final : public RowSnapshot { /// @param column Column index. /// @return The cell. [[nodiscard]] Cell cell(std::size_t row, std::size_t column) const override { - return (*_readers)[column]((*_rows)[row]); + auto const& value = (*_rows)[row]; + auto const level = levelOf(column); + if (!level.empty() && !_loaded(value, level)) { + return Cell{Unloaded{}}; + } + return (*_readers)[column](value, _units.get()); } /// @brief Hands rows `[first, last)` of @p column to @p sink in runs. @@ -789,11 +1264,14 @@ class RowsSnapshot final : public RowSnapshot { std::vector run; run.reserve(kRun); auto const reader = (*_readers)[column]; + auto const level = levelOf(column); while (first < last) { auto const end = std::min(first + kRun, last); run.clear(); for (auto row = first; row < end; ++row) { - run.push_back(reader((*_rows)[row])); + auto const& value = (*_rows)[row]; + run.push_back(!level.empty() && !_loaded(value, level) ? Cell{Unloaded{}} + : reader(value, _units.get())); } sink.cells(first, run); first = end; @@ -801,9 +1279,17 @@ class RowsSnapshot final : public RowSnapshot { } private: + // The level a column's cells are checked against: empty when the column has none or no predicate is set. + [[nodiscard]] std::string_view levelOf(std::size_t column) const { + return _loaded && _levels != nullptr ? std::string_view{(*_levels)[column]} : std::string_view{}; + } + std::shared_ptr const> _rows; RowKey _key; std::shared_ptr> const> _readers; + std::shared_ptr const> _levels; + LevelLoaded _loaded; + std::shared_ptr _units; }; /// @brief A `DataSource` over typed rows: one column per key glaze writes, @@ -811,12 +1297,17 @@ class RowsSnapshot final : public RowSnapshot { /// /// `bool` is `Bool`; other integers `Integer` (an unsigned value above /// `INT64_MAX` is an invalid cell); floating point `Number`; `Rational` -/// `Decimal`; a `Quantity` `Quantity`; `DateTime` and `Timestamp` +/// `Decimal`; a `Quantity` `Quantity`; a `MeasureValue` `Measure`, its unit id +/// resolved through the source's registry; `DateTime` and `Timestamp` /// `DateTime`; a type glaze writes as one of its members (`Ranged`, /// `Choice`, `Tagged`) that member's kind; everything else `Text` (an enum by /// its glaze name). A `std::optional` member's empty state, or anything glaze /// writes as `null`, is an empty cell. A row with a `glz::meta` has the -/// columns its meta names. `setRows` replaces the rows and notifies `Reset`. +/// columns its meta names. A row type's `columnLevels()` gives its columns +/// their levels, and a cell of a column whose level the `LevelLoaded` +/// predicate refuses for its row is `Unloaded`. A row type's `columnGroups()` +/// are the source's `groups()`, each labelled by its id. `setRows` replaces +/// the rows and notifies `Reset`. /// @tparam Row A glaze-reflectable aggregate. template class RowsSource final : public DataSource { @@ -828,13 +1319,22 @@ class RowsSource final : public DataSource { /// id (for example `Date` for an `int64` of epoch days). /// @param comparators Comparator names by column id, from /// `Services::comparators`; a column named here is `Custom`. + /// @param loaded Whether a level is loaded for a row; empty means every level is. + /// @param units The registry a `MeasureValue` member's unit id is resolved through: the one the source's + /// keys are built with (`Services::units`). Null resolves none, so every measure is invalid. + /// @throws std::invalid_argument when `Row::columnLevels()` names no column. RowsSource(std::shared_ptr const> rows, RowKey key, std::map> const& kinds = {}, - std::map> const& comparators = {}) + std::map> const& comparators = {}, LevelLoaded loaded = {}, + std::shared_ptr units = nullptr) : _columns{detail::reflectedColumns()}, + _groups{detail::declaredGroups()}, _readers{std::make_shared> const>(detail::cellReaders())}, _key{std::move(key)}, - _snapshot{std::make_shared>(std::move(rows), _key, _readers)} { + _loaded{std::move(loaded)}, + _units{std::move(units)} { + auto levels = std::make_shared>(); + levels->reserve(_columns.size()); for (auto& column : _columns) { if (auto const found = kinds.find(column.id); found != kinds.end()) { column.kind = found->second; @@ -843,13 +1343,21 @@ class RowsSource final : public DataSource { column.kind = ColumnKind::Custom; column.comparator = found->second; } + levels->push_back(column.level); } + _levels = std::move(levels); + // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer): _levels is built in the body before the snapshot can name it. + _snapshot = std::make_shared>(std::move(rows), _key, _readers, _levels, _loaded, _units); } /// @brief The columns. /// @return One per reflected member. [[nodiscard]] std::span columns() const override { return _columns; } + /// @brief The row type's declared groups. + /// @return One per `Row::columnGroups()` entry, labelled by its id; none when the row type declares none. + [[nodiscard]] std::span groups() const override { return _groups; } + /// @brief The current rows; a pointer copy. /// @return The snapshot. [[nodiscard]] std::shared_ptr snapshot() const override { return _snapshot; } @@ -865,156 +1373,410 @@ class RowsSource final : public DataSource { /// @brief Replaces the rows and notifies `Reset`. /// @param rows The new rows. void setRows(std::shared_ptr const> rows) { - _snapshot = std::make_shared>(std::move(rows), _key, _readers); + _snapshot = std::make_shared>(std::move(rows), _key, _readers, _levels, _loaded, _units); _listeners.notify(RowChange{.kind = ChangeKind::Reset, .rows = {}}); } private: std::vector _columns; + std::vector _groups; std::shared_ptr> const> _readers; RowKey _key; + LevelLoaded _loaded; + std::shared_ptr _units; + std::shared_ptr const> _levels; std::shared_ptr const> _snapshot; detail::Listeners _listeners; }; +namespace detail { + +/// @brief The levels of @p levels that @p loaded refuses for @p row, in the order of @p levels. +/// @tparam Row The row type. +/// @param row The row. +/// @param levels Levels, sorted. +/// @param loaded The predicate; not empty. +/// @return The refused levels. +template +[[nodiscard]] std::vector refusedLevels(Row const& row, std::span levels, + LevelLoaded const& loaded) { + std::vector out; + for (auto const& level : levels) { + if (!loaded(row, level)) { + out.push_back(level); + } + } + return out; +} + +/// @brief The order levels @p loaded refuses for at least one row of the view or of the undecided set. +/// @tparam Row The row type. +/// @param rows The rows the view was computed over. +/// @param view The view. +/// @param order The query's order levels, sorted. +/// @param loaded The predicate; not empty. +/// @return The levels, sorted. +template +[[nodiscard]] std::vector awaitedLevels(std::vector const& rows, ComputedView const& view, + std::span order, + LevelLoaded const& loaded) { + std::vector out; + for (auto const& level : order) { + auto const refused = [&](std::uint32_t row) { return !loaded(rows[row], level); }; + if (std::ranges::any_of(view.rows, refused) || std::ranges::any_of(view.undecided, refused)) { + out.push_back(level); + } + } + return out; +} + +} // namespace detail + /// @brief Runs @p query over typed rows and returns the page of rows: what a /// server's list action returns. +/// +/// With @p loaded set, `unloadedRows` names each row of the page with the levels the query needs (`levelsNeeded`: +/// `order` and `display`) that @p loaded refuses for it, and `awaiting` the `order` levels it refuses for at least +/// one row of the view or of the undecided rows. A predicate cannot say that a load failed, so `failed` stays +/// empty. Without @p loaded every level is loaded, and all three stay empty. /// @tparam Row A glaze-reflectable aggregate. /// @param rows The server's rows; read during the call only. /// @param key The key projection. /// @param query The request body's table query. -/// @param options Limits, services and column access. +/// @param options Limits, services and column access; `services.units` also resolves `MeasureValue` members. /// @param kinds Column kinds that replace the inferred ones. /// @param comparators Comparator names by column id; a column named here is `Custom`. +/// @param loaded Whether a level is loaded for a row; empty means every level is. /// @return The page, or the typed error the client shows. template [[nodiscard]] std::expected, TableError> apply( std::vector const& rows, RowKey key, TableQuery const& query, ApplyOptions const& options = {}, std::map> const& kinds = {}, - std::map> const& comparators = {}) { + std::map> const& comparators = {}, LevelLoaded loaded = {}) { // Borrowed for the call: an aliasing pointer that owns nothing. std::shared_ptr const> const borrowed{std::shared_ptr{}, &rows}; - RowsSource const source{borrowed, std::move(key), kinds, comparators}; - auto page = apply(source, query, options); - if (!page) { - return std::unexpected(std::move(page.error())); + RowsSource const source{borrowed, std::move(key), kinds, comparators, loaded, options.services.units}; + if (auto error = detail::checkGroups(source.columns(), source.groups())) { + return std::unexpected(std::move(*error)); } + auto const checked = validate(query, source.columns(), options.limits, options.mayRead, source.groups()); + if (!checked) { + return std::unexpected(checked.error()); + } + if (checked->distinct) { + auto values = distinctValues(source, *checked, *checked->distinct, options); + if (!values) { + return std::unexpected(std::move(values.error())); + } + Page out; + out.distinct = std::move(*values); + return out; + } + auto const view = detail::computeView(source, *checked, options); + if (!view) { + return std::unexpected(view.error()); + } + auto viewed = detail::viewPage(*view, source, *source.snapshot(), *checked, options); + if (!viewed) { + return std::unexpected(std::move(viewed.error())); + } + auto page = std::move(*viewed); Page out; - out.total = page->total; - out.offset = page->offset; - out.rows.reserve(page->rows.size()); - for (auto const row : page->rows) { + out.total = page.total; + out.offset = page.offset; + out.totalKind = page.totalKind; + out.undecided = page.undecided; + out.awaiting = std::move(page.awaiting); + out.failed = std::move(page.failed); + out.indices = std::move(page.indices); + out.viewRevision = std::move(page.viewRevision); + out.unmatched = std::move(page.unmatched); + out.rows.reserve(page.rows.size()); + for (auto const row : page.rows) { out.rows.push_back(rows[row]); } + if (!loaded) { + return out; + } + auto const needed = + levelsNeeded(*checked, source.columns(), options.mayRead, options.services.forTask(), source.groups()); + std::vector wanted = needed.order; + wanted.insert(wanted.end(), needed.display.begin(), needed.display.end()); + std::ranges::sort(wanted); + auto const [first, last] = std::ranges::unique(wanted); + wanted.erase(first, last); + for (std::size_t index = 0; index < page.rows.size(); ++index) { + auto levels = detail::refusedLevels(rows[page.rows[index]], wanted, loaded); + if (!levels.empty()) { + out.unloadedRows.push_back( + UnloadedRow{.index = static_cast(index), .levels = std::move(levels), .failed = {}}); + } + } + auto awaited = detail::awaitedLevels(rows, *view, needed.order, loaded); + out.awaiting.insert(out.awaiting.end(), awaited.begin(), awaited.end()); + std::ranges::sort(out.awaiting); + auto const [awaitFirst, awaitLast] = std::ranges::unique(out.awaiting); + out.awaiting.erase(awaitFirst, awaitLast); return out; } // ── Server mode on the client ─────────────────────────────────────────────── -/// @brief A request a `PageWindow` asks the client to send, tagged with the -/// query it belongs to. +/// @brief A page request a `PageWindow` asks the client to send, tagged with the +/// query and the revision it belongs to. struct PageFetch { /// @brief The rows to request. PageRequest request; + /// @brief The columns to ask for (`TableQuery::columns`). A held page asks only for the columns it lacks; empty + /// asks for every column. + std::vector columns; /// @brief The window's query when the fetch was made (`PageWindow::query`). std::uint64_t query = 0; + /// @brief The window's revision when the fetch was made (`PageWindow::revision`). + std::uint64_t revision = 0; /// @brief Member-wise equality. /// @param other The fetch to compare with. - /// @return `true` when request and query match. + /// @return `true` when request, columns, query and revision match. [[nodiscard]] bool operator==(PageFetch const& other) const = default; }; -/// @brief The pages a `server`-mode table holds: those around the visible -/// rows, up to a bound, plus the request state and the last error. -/// -/// The client calls `visible` as the view scrolls and sends the request of -/// each fetch it returns, then hands the fetch back with its reply to -/// `accept` (or with its error to `fail`). A change of sort or filter is a -/// new query: call `reset`. A reply to a fetch made before the last `reset` -/// is ignored, so a late page of the old query never shows under the new one. -/// -/// A server may return fewer rows than a fetch asked for (`validate` clamps -/// the limit to its `maxLimit`): the window then fetches the rest of the page -/// from where the reply ended. A page is complete when it is full, reaches the -/// known total, or a reply to it is empty. +/// @brief A keyed request a `PageWindow` asks the client to send (`TableQuery::keys`). +struct RowsFetch { + /// @brief The keys to ask for: the event's keys and one probe per run of held rows. + std::vector keys; + /// @brief The columns to ask for: those of the latest `visible` call. + std::vector columns; + /// @brief The window's query when the fetch was made. + std::uint64_t query = 0; + /// @brief The fetch's place among the window's keyed fetches; a later fetch has a larger one. + std::uint64_t sequence = 0; + + /// @brief Member-wise equality. + /// @param other The fetch to compare with. + /// @return `true` when keys, columns, query and sequence match. + [[nodiscard]] bool operator==(RowsFetch const& other) const = default; +}; + +/// @brief What a window asks for after a change of its table's record. +enum class Refresh : std::uint8_t { + Nothing, ///< Nothing: the window holds no row. + Rows, ///< The keyed fetch in `RefreshPlan::rows`. + Pages, ///< The window invalidated itself; the next `visible` fetches its pages again. +}; + +/// @brief What `PageWindow::refresh` and `PageWindow::owed` return. +struct RefreshPlan { + /// @brief What to fetch. + Refresh kind = Refresh::Nothing; + /// @brief The keyed fetch to send when `kind` is `Rows`. + RowsFetch rows; +}; + +template +class PageWindow; + +/// @brief The window of generic rows; defined in `table/description.hpp`, so a translation unit that does not +/// include it cannot use the typed window for generic rows by mistake. +template <> +class PageWindow>; + +namespace detail { + +/// @brief How a fetch in flight relates to the page it is for. +enum class WindowFetchKind : std::uint8_t { + Whole, ///< The whole page: its reply replaces the page. + Rest, ///< The rows after those held: its reply is appended. + Columns, ///< The same rows with more columns: its reply's cells are added by key. +}; + +/// @brief What a window reads of a reply besides its rows' content. +struct WindowReply { + /// @brief One key per row; empty when the window has no key function. + std::span keys; + /// @brief Rows in the reply. + std::size_t rows = 0; + /// @brief The reply's `unloadedRows`. + std::span unloadedRows; + /// @brief The reply's `total`. + std::optional total; + /// @brief The reply's `totalKind`. + TotalKind totalKind = TotalKind::Exact; + /// @brief The reply's `undecided`. + std::int64_t undecided = 0; + /// @brief The reply's `awaiting`. + std::span awaiting; + /// @brief The reply's `failed`. + std::span failed; + /// @brief The reply's `indices`. + std::span indices; +}; + +/// @brief The rows of one page of a typed window. /// @tparam Row The row type. template -class PageWindow { -public: - /// @brief An empty window. - /// @param pageSize Rows per page (default 200). - /// @param maxPages Pages held at most; the farthest from the visible rows go first. - // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) - page size then page count, both documented above - explicit PageWindow(std::int64_t pageSize = 200, std::size_t maxPages = 8) - : _pageSize{std::max(pageSize, 1)}, _maxPages{std::max(maxPages, 1)} {} +struct TypedWindowRows { + /// @brief The rows, in view order. + std::vector rows; - /// @brief Declares the visible rows; returns the fetches to send. + /// @brief A typed row is whole: every column is held. + /// @param column Unused. + /// @return `true`. + [[nodiscard]] static bool holds(std::string_view column) noexcept { + static_cast(column); + return true; + } + /// @brief The columns a rest-of-page fetch names: none, since a typed row is whole. + /// @return Empty. + [[nodiscard]] static std::vector columns() { return {}; } + /// @brief Keeps the first @p count rows. + /// @param count Rows kept. + void truncate(std::size_t count) { + rows.erase(rows.begin() + static_cast(std::min(count, rows.size())), rows.end()); + } +}; + +/// @brief The bookkeeping both windows share: pages, keys, unloaded levels, staleness, revisions, fetches in +/// flight, totals and keyed sequences. Everything except a row's content, which @p Content holds. +/// +/// See `PageWindow` for the rules; each member below states its own. +/// @tparam Content A page's content: `holds(column)`, `columns()` and `truncate(count)`. +template +class WindowCore { +public: + /// @brief Declares the visible rows and the columns shown; returns the fetches to send. + /// + /// Covers the visible rows and one page either side, skipping pages past an exact total and pages with a + /// fetch in flight. A page not held, or held stale, is fetched whole with @p columns. A page held, current and + /// cut short is fetched from where it ends. A page held, current and complete that lacks some of @p columns + /// is fetched again for the same rows, naming only those columns. Each returned fetch is in flight. /// - /// Covers the visible rows and one page either side, skipping complete - /// pages, pages in flight, and pages past a known total. A page held in - /// part is fetched from where it ends. The returned pages are marked in - /// flight. - /// @param first First visible view row. - /// @param count Visible rows. + /// Only the first `maxColumns` of @p columns are taken: a page holds at most that many, and never drops one + /// the latest call named, so a wider set would be dropped and fetched again without end. + /// @param first First visible view row. + /// @param count Visible rows. + /// @param columns The columns shown, in order; empty asks for every column. /// @return The fetches to send. - [[nodiscard]] std::vector visible(std::int64_t first, std::int64_t count) { + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + [[nodiscard]] std::vector visibleColumns(std::int64_t first, std::int64_t count, + std::span columns) { + columns = columns.first(std::min(columns.size(), _maxColumns)); _visibleFirst = std::max(first, 0); _visibleCount = std::max(count, 0); + _columns.assign(columns.begin(), columns.end()); + ++_stamp; + for (auto const& column : columns) { + _named.insert_or_assign(column, _stamp); + } auto const firstPage = std::max((_visibleFirst / _pageSize) - 1, 0); auto const lastPage = ((_visibleFirst + std::max(_visibleCount, 1) - 1) / _pageSize) + 1; + _coveredFirst = firstPage; + _coveredLast = lastPage; std::vector out; for (auto page = firstPage; page <= lastPage; ++page) { if (exactTotal() && page * _pageSize >= *_total) { break; } - if (_complete.contains(page) || std::ranges::find(_inFlight, page) != _inFlight.end()) { + if (_inFlight.contains(page)) { continue; } + PageFetch fetch{.request = {}, .columns = {}, .query = _query, .revision = _revision}; + WindowFetchKind kind = WindowFetchKind::Whole; auto const held = _pages.find(page); - auto const have = held == _pages.end() ? std::int64_t{0} : static_cast(held->second.size()); - _inFlight.push_back(page); - out.push_back( - PageFetch{.request = PageRequest{.offset = (page * _pageSize) + have, .limit = _pageSize - have}, - .query = _query}); + if (held == _pages.end() || held->second.stale) { + fetch.request = PageRequest{.offset = page * _pageSize, .limit = _pageSize}; + fetch.columns.assign(columns.begin(), columns.end()); + } else if (!held->second.complete) { + auto const have = held->second.rows; + fetch.request = PageRequest{.offset = (page * _pageSize) + have, .limit = _pageSize - have}; + fetch.columns = held->second.content.columns(); + kind = WindowFetchKind::Rest; + } else { + if (held->second.rows == 0) { + continue; + } + for (auto const& column : columns) { + if (!held->second.content.holds(column) && + std::ranges::find(fetch.columns, column) == fetch.columns.end()) { + fetch.columns.push_back(column); + } + } + if (fetch.columns.empty()) { + continue; + } + fetch.request = PageRequest{.offset = page * _pageSize, .limit = held->second.rows}; + kind = WindowFetchKind::Columns; + } + _inFlight.insert_or_assign(page, Flight{.fetch = fetch, .kind = kind}); + out.push_back(std::move(fetch)); } return out; } - /// @brief Stores a reply. - /// @param fetch The fetch the reply answers, as `visible` returned it. - /// @param page The page the server returned. - /// @return `false` when the reply was ignored: its fetch belongs to an - /// earlier query, or is not awaited. - bool accept(PageFetch const& fetch, Page page) { - if (fetch.query != _query) { - return false; + /// @brief The fetches in flight for pages outside the range the latest `visible` call covered. + /// + /// The client cancels them through their stop tokens and tells the window with `cancelled`. + /// @return The fetches, by page. + [[nodiscard]] std::vector superseded() const { + std::vector out; + for (auto const& [page, flight] : _inFlight) { + if (page < _coveredFirst || page > _coveredLast) { + out.push_back(flight.fetch); + } } - auto const index = fetch.request.offset / _pageSize; - auto const flight = std::ranges::find(_inFlight, index); - if (flight == _inFlight.end()) { - return false; + return out; + } + + /// @brief Forgets a fetch the client cancelled; its reply, should one arrive, is ignored. + /// @param fetch The fetch, as `visible` returned it. + void cancelled(PageFetch const& fetch) { + auto const found = _inFlight.find(pageOf(fetch)); + if (found != _inFlight.end() && found->second.fetch == fetch) { + _inFlight.erase(found); } - _inFlight.erase(flight); - if (page.total) { - _total = page.total; - _totalKind = page.totalKind; + } + + /// @brief Plans the answer to a keyed change of the table's record. + /// + /// While any page fetch is in flight the keys are also recorded for `owed`. `Nothing` when no row is held; + /// `Pages` (the window invalidates) without a key function, while `awaiting()` is not empty, or when the keys + /// to ask for exceed `maxKeys`; otherwise `Rows`, asking for every key of the event, held or not, and for the + /// first key of each run of consecutive held rows (a probe), which tells the window whether rows shifted. + /// @param keys The event's keys. + /// @return The plan. + [[nodiscard]] RefreshPlan refresh(std::span keys) { + if (!_inFlight.empty()) { + _owed.insert(_owed.end(), keys.begin(), keys.end()); } - _error.reset(); - auto& rows = _pages[index]; - bool const replyEmpty = page.rows.empty(); - if (fetch.request.offset == (index * _pageSize) + static_cast(rows.size())) { - auto const room = static_cast(_pageSize) - rows.size(); - auto const take = std::min(room, page.rows.size()); - rows.insert(rows.end(), std::make_move_iterator(page.rows.begin()), - std::make_move_iterator(page.rows.begin() + static_cast(take))); + return plan(keys); + } + + /// @brief Plans the keyed fetch for the events that arrived while a page fetch was in flight. + /// + /// The client calls it after each `accept`: an event can precede the reply whose rows it concerns. The + /// recorded keys are dropped when no page fetch is in flight, and whenever the plan is `Pages`: the + /// invalidation leaves every reply still in flight older than the window, so the refetch that follows covers + /// every recorded key. + /// @return The plan, by the rules of `refresh`; `Nothing` when no key is recorded. + [[nodiscard]] RefreshPlan owed() { + if (_owed.empty()) { + return {}; } - auto const end = (index * _pageSize) + static_cast(rows.size()); - if (std::cmp_greater_equal(rows.size(), _pageSize) || (exactTotal() && end >= *_total) || replyEmpty) { - _complete.insert(index); + auto keys = std::move(_owed); + _owed.clear(); + auto result = plan(keys); + if (!_inFlight.empty() && result.kind != Refresh::Pages) { + _owed = std::move(keys); + } + return result; + } + + /// @brief Takes a new revision and marks every held page stale. Rows stay shown and fetches stay in flight. + void invalidate() { + ++_revision; + for (auto& [page, held] : _pages) { + held.stale = true; } - evict(); - return true; } /// @brief Records a failed request; the error is shown until a reply arrives. @@ -1025,20 +1787,25 @@ class PageWindow { if (fetch.query != _query) { return false; } - std::erase(_inFlight, fetch.request.offset / _pageSize); + cancelled(fetch); _error = std::move(error); return true; } - /// @brief Drops every page, request and error and starts a new query: the - /// sort or filter changed. + /// @brief Drops every page, request, recorded key and error and starts a new query: the sort or filter + /// changed. void reset() { ++_query; _pages.clear(); - _complete.clear(); _inFlight.clear(); _total.reset(); _totalKind = TotalKind::Exact; + _undecided = 0; + _awaiting.clear(); + _failed.clear(); + _totalsRevision = 0; + _owed.clear(); + _latestAsked.clear(); _error.reset(); } @@ -1046,30 +1813,43 @@ class PageWindow { /// @return The query's number. [[nodiscard]] std::uint64_t query() const noexcept { return _query; } - /// @brief The row at a view row, when it is held. + /// @brief The current revision, which `invalidate` advances. + /// @return The revision's number. + [[nodiscard]] std::uint64_t revision() const noexcept { return _revision; } + + /// @brief The unloaded levels of the held row at a view row. /// @param index View row. - /// @return The row, or null. - [[nodiscard]] Row const* row(std::int64_t index) const { - if (index < 0) { - return nullptr; - } - auto const found = _pages.find(index / _pageSize); - if (found == _pages.end()) { - return nullptr; + /// @return Views into the window, valid until it next changes; empty when the row is not held. + [[nodiscard]] UnloadedLevels unloadedLevels(std::int64_t index) const { + auto const* const page = heldAt(index); + if (page == nullptr) { + return {}; } - auto const offset = static_cast(index % _pageSize); - return offset < found->second.size() ? &found->second[offset] : nullptr; + auto const position = static_cast(index % _pageSize); + return UnloadedLevels{.levels = page->levels[position], .failed = page->failedLevels[position]}; } - /// @brief The view's total rows, when a reply of this query reported it. + /// @brief The view's total rows, when a page reply of this query reported it. /// @return The total. [[nodiscard]] std::optional total() const noexcept { return _total; } - /// @brief Whether `total()` is the count of the view or a lower bound, as the latest reply that carried a total - /// said. + /// @brief Whether `total()` is the count of the view or a lower bound, as the latest page reply that carried + /// a total said. /// @return The kind; `Exact` while no total is known. [[nodiscard]] TotalKind totalKind() const noexcept { return _totalKind; } + /// @brief Rows the filter can neither admit nor reject yet, as the latest page reply said. + /// @return The count. + [[nodiscard]] std::int64_t undecided() const noexcept { return _undecided; } + + /// @brief The order levels with a load wanted or in flight, as the latest page reply said. + /// @return The levels. + [[nodiscard]] std::span awaiting() const noexcept { return _awaiting; } + + /// @brief The order levels whose load failed, as the latest page reply said. + /// @return The levels. + [[nodiscard]] std::span failed() const noexcept { return _failed; } + /// @brief The last error, until a reply clears it. /// @return The error, or nothing. [[nodiscard]] std::optional const& error() const noexcept { return _error; } @@ -1078,11 +1858,376 @@ class PageWindow { /// @return Page count. [[nodiscard]] std::size_t pagesHeld() const noexcept { return _pages.size(); } - /// @brief Whether any request is in flight. + /// @brief Whether any page fetch is in flight. /// @return `true` while a page is awaited. [[nodiscard]] bool pending() const noexcept { return !_inFlight.empty(); } + /// @brief How many held keys the window remembers a keyed fetch for; never more than the rows it holds once a + /// reply has been accepted, whatever the number of events. + /// @return The count. + [[nodiscard]] std::size_t keysRemembered() const noexcept { return _latestAsked.size(); } + +protected: + /// @brief One held page. + struct Held { + /// @brief The rows' content. + Content content; + /// @brief Each row's key; empty without a key function. + std::vector keys; + /// @brief Each row's unloaded levels. + std::vector> levels; + /// @brief Each row's failed levels. + std::vector> failedLevels; + /// @brief Rows held. + std::int64_t rows = 0; + /// @brief Whether an invalidation or another page's totals made the page out of date. + bool stale = false; + /// @brief Whether the page holds every row it will: full, at the total, or ended by an empty reply. + bool complete = false; + }; + + /// @brief A fetch in flight. + struct Flight { + /// @brief The fetch as `visible` returned it. + PageFetch fetch; + /// @brief How its reply is stored. + WindowFetchKind kind = WindowFetchKind::Whole; + }; + + /// @brief An empty window. + /// @param pageSize Rows per page. + /// @param maxPages Pages held at most. + /// @param keyed Whether rows have keys, so that a change can be answered with a keyed fetch. + /// @param maxKeys Keys one keyed fetch asks for at most. + /// @param maxColumns Columns a page holds at most. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) - sizes and bounds, each documented above + WindowCore(std::int64_t pageSize, std::size_t maxPages, bool keyed, std::size_t maxKeys, std::size_t maxColumns) + : _pageSize{std::max(pageSize, 1)}, + _maxPages{std::max(maxPages, 1)}, + _maxKeys{maxKeys}, + _maxColumns{std::max(maxColumns, 1)}, + _keyed{keyed} {} + + /// @brief Stores a page reply. + /// + /// Ignored when the fetch belongs to another query or is not the one in flight for its page. A whole-page + /// reply replaces the page, which stays stale when its fetch is older than the window's revision; a + /// rest-of-page reply is appended; a column reply is merged when its keys are the page's, row for row, and + /// invalidates the window otherwise. A reply not older than the totals held sets them; one whose total or + /// undecided count differs marks every other held page stale. An exact total drops every held row past it. + /// @tparam Fill `void(Content&, WindowFetchKind, std::size_t take)`: stores the first `take` rows of the reply. + /// @param fetch The fetch the reply answers. + /// @param reply What the window reads of the reply. + /// @param fill Stores the reply's content. + /// @return `false` when the reply was ignored. + template + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward): called more than once, so it is never forwarded. + bool acceptReply(PageFetch const& fetch, WindowReply const& reply, Fill&& fill) { + if (fetch.query != _query) { + return false; + } + auto const index = pageOf(fetch); + auto const flight = _inFlight.find(index); + if (flight == _inFlight.end() || flight->second.fetch != fetch) { + return false; + } + auto const kind = flight->second.kind; + _inFlight.erase(flight); + _error.reset(); + if (_keyed && reply.keys.size() != reply.rows) { + invalidate(); + _error = TableError{.code = TableErrorCode::InvalidValue, + .column = {}, + .message = "a page reply of " + std::to_string(reply.keys.size()) + " keys and " + + std::to_string(reply.rows) + " rows"}; + return true; + } + bool const replyEmpty = reply.rows == 0; + bool stored = false; + if (kind == WindowFetchKind::Columns) { + auto const held = _pages.find(index); + if (held != _pages.end()) { + if (sameKeys(held->second, reply)) { + fill(held->second.content, kind, reply.rows); + mergeLevels(held->second, reply); + } else { + invalidate(); + } + } + } else if (kind == WindowFetchKind::Whole) { + auto& held = _pages[index]; + auto const take = std::min(reply.rows, static_cast(_pageSize)); + held = Held{}; + fill(held.content, kind, take); + appendRows(held, reply, take); + held.stale = fetch.revision != _revision; + stored = true; + } else { + auto const held = _pages.find(index); + if (held != _pages.end() && fetch.request.offset == (index * _pageSize) + held->second.rows) { + auto const room = static_cast(_pageSize - held->second.rows); + auto const take = std::min(room, reply.rows); + fill(held->second.content, kind, take); + appendRows(held->second, reply, take); + stored = true; + } + } + if (fetch.revision >= _totalsRevision) { + adoptTotals(index, fetch.revision, reply); + } + // After the totals: the reply's own total decides whether a page it cut short is complete, so the first page + // of a short view is complete at once, with no fetch for a rest that does not exist. + if (stored) { + if (auto const held = _pages.find(index); held != _pages.end()) { + completeIf(index, held->second, replyEmpty); + } + } + dropPastTotal(); + evict(); + forgetUnheldKeys(); + return true; + } + + /// @brief Patches held rows from a keyed reply. + /// + /// Ignored (empty) for another query or without a key function. A reply row whose key a later fetch asked for + /// is ignored. The window invalidates instead of patching when a requested key it holds has no row, a held + /// key is at another view row, an unheld key lies inside a held page, or, on the reply to the latest keyed + /// fetch, the totals differ from the window's. + /// @tparam Replace `void(Held&, std::size_t at, std::size_t from)`: replaces held row `at` with reply row + /// `from`. + /// @param fetch The fetch the reply answers. + /// @param reply What the window reads of the reply. + /// @param replace Stores one row's content. + /// @return The view rows replaced, ascending. + template + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward,readability-function-cognitive-complexity): called more than once, so it is never forwarded. one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + std::vector patchRows(RowsFetch const& fetch, WindowReply const& reply, Replace&& replace) { + if (fetch.query != _query || !_keyed) { + return {}; + } + if (reply.keys.size() != reply.rows || reply.indices.size() != reply.rows) { + invalidate(); + return {}; + } + std::unordered_map held; + for (auto const& [page, content] : _pages) { + for (std::size_t at = 0; at < content.keys.size(); ++at) { + held.emplace(content.keys[at], (page * _pageSize) + static_cast(at)); + } + } + auto const latest = [this](RowId const& key) { + auto const found = _latestAsked.find(key); + return found == _latestAsked.end() ? std::uint64_t{0} : found->second; + }; + bool shifted = false; + std::unordered_set answered; + std::vector current; + for (std::size_t from = 0; from < reply.rows; ++from) { + auto const& key = reply.keys[from]; + if (latest(key) > fetch.sequence) { + continue; + } + answered.insert(key); + current.push_back(from); + auto const index = reply.indices[from]; + auto const found = held.find(key); + if (found != held.end()) { + shifted = shifted || found->second != index; + } else if (index >= 0 && _pages.contains(index / _pageSize)) { + shifted = true; + } + } + for (auto const& key : fetch.keys) { + if (latest(key) == fetch.sequence && held.contains(key) && !answered.contains(key)) { + shifted = true; + } + } + if (fetch.sequence == _latestKeyed && + ((reply.total && (reply.total != _total || reply.totalKind != _totalKind)) || + reply.undecided != _undecided)) { + shifted = true; + } + if (shifted) { + invalidate(); + return {}; + } + std::vector out; + for (auto const from : current) { + auto const index = reply.indices[from]; + if (!held.contains(reply.keys[from])) { + continue; + } + auto& page = _pages.at(index / _pageSize); + auto const position = static_cast(index % _pageSize); + replace(page, position, from); + page.levels[position].clear(); + page.failedLevels[position].clear(); + if (auto const* const unloaded = unloadedOf(reply, from)) { + page.levels[position] = unloaded->levels; + page.failedLevels[position] = unloaded->failed; + } + out.push_back(index); + } + std::ranges::sort(out); + return out; + } + + /// @brief The page holding a view row, when the row is held. + /// @param index View row. + /// @return The page, or null. + [[nodiscard]] Held const* heldAt(std::int64_t index) const { + if (index < 0) { + return nullptr; + } + auto const found = _pages.find(index / _pageSize); + if (found == _pages.end() || index % _pageSize >= found->second.rows) { + return nullptr; + } + return &found->second; + } + + /// @brief Whether the latest `visible` call named a column, so a page must keep it. + /// @param column The column. + /// @return `true` when it is among the columns shown now. + [[nodiscard]] bool shownNow(std::string_view column) const { + return std::ranges::find(_columns, column) != _columns.end(); + } + + /// @brief The latest `visible` call that named a column. + /// @param column The column. + /// @return The call's stamp; 0 when no call named it. + [[nodiscard]] std::uint64_t namedAt(std::string_view column) const { + auto const found = _named.find(column); + return found == _named.end() ? std::uint64_t{0} : found->second; + } + + /// @brief Rows per page. + /// @return The page size. + [[nodiscard]] std::int64_t pageSize() const noexcept { return _pageSize; } + + /// @brief Columns a page holds at most. + /// @return The bound. + [[nodiscard]] std::size_t maxColumns() const noexcept { return _maxColumns; } + private: + [[nodiscard]] std::int64_t pageOf(PageFetch const& fetch) const noexcept { + return fetch.request.offset / _pageSize; + } + + // Whether a known total bounds the view; a lower bound does not. + [[nodiscard]] bool exactTotal() const noexcept { return _total && _totalKind == TotalKind::Exact; } + + [[nodiscard]] static UnloadedRow const* unloadedOf(WindowReply const& reply, std::size_t row) { + auto const found = + std::ranges::lower_bound(reply.unloadedRows, static_cast(row), {}, &UnloadedRow::index); + return found != reply.unloadedRows.end() && std::cmp_equal(found->index, row) ? &*found : nullptr; + } + + [[nodiscard]] bool sameKeys(Held const& held, WindowReply const& reply) const { + if (std::cmp_not_equal(reply.rows, held.rows)) { + return false; + } + return !_keyed || std::ranges::equal(held.keys, reply.keys); + } + + void appendRows(Held& held, WindowReply const& reply, std::size_t take) { + for (std::size_t row = 0; row < take; ++row) { + if (_keyed) { + held.keys.push_back(reply.keys[row]); + } + auto const* const unloaded = unloadedOf(reply, row); + held.levels.push_back(unloaded != nullptr ? unloaded->levels : std::vector{}); + held.failedLevels.push_back(unloaded != nullptr ? unloaded->failed : std::vector{}); + } + held.rows += static_cast(take); + } + + static void unite(std::vector& into, std::vector const& more) { + into.insert(into.end(), more.begin(), more.end()); + std::ranges::sort(into); + auto const [first, last] = std::ranges::unique(into); + into.erase(first, last); + } + + void mergeLevels(Held& held, WindowReply const& reply) { + for (auto const& unloaded : reply.unloadedRows) { + if (unloaded.index < 0 || unloaded.index >= held.rows) { + continue; + } + auto const position = static_cast(unloaded.index); + unite(held.levels[position], unloaded.levels); + unite(held.failedLevels[position], unloaded.failed); + } + } + + void completeIf(std::int64_t index, Held& held, bool replyEmpty) { + auto const end = (index * _pageSize) + held.rows; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): exactTotal() holds, so the total is known. + if (held.rows >= _pageSize || (exactTotal() && end >= *_total) || replyEmpty) { + held.complete = true; + } + } + + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): page index, then revision, as the window's callers hold them. + void adoptTotals(std::int64_t index, std::uint64_t revision, WindowReply const& reply) { + bool const differs = + (reply.total && (reply.total != _total || reply.totalKind != _totalKind)) || reply.undecided != _undecided; + _totalsRevision = revision; + _undecided = reply.undecided; + _awaiting.assign(reply.awaiting.begin(), reply.awaiting.end()); + _failed.assign(reply.failed.begin(), reply.failed.end()); + if (reply.total) { + _total = reply.total; + _totalKind = reply.totalKind; + } + if (differs) { + for (auto& [page, held] : _pages) { + if (page != index) { + held.stale = true; + } + } + } + } + + // A key that left the held pages needs no memory of the fetch that last asked for it. + void forgetUnheldKeys() { + if (_latestAsked.empty()) { + return; + } + std::unordered_set heldKeys; + for (auto const& [page, held] : _pages) { + heldKeys.insert(held.keys.begin(), held.keys.end()); + } + std::erase_if(_latestAsked, [&](auto const& entry) { return !heldKeys.contains(entry.first); }); + } + + // A view that shrank holds nothing past its end, and awaits no fetch there: a page past an exact total is + // never fetched again, so a row held there would stay shown, and its key would be a probe no reply answers. + void dropPastTotal() { + if (!exactTotal()) { + return; + } + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): exactTotal() holds, so the total is known. + auto const total = *_total; + std::erase_if(_pages, [&](auto const& entry) { return entry.first * _pageSize >= total; }); + std::erase_if(_inFlight, [&](auto const& entry) { return entry.first * _pageSize >= total; }); + for (auto& [page, held] : _pages) { + auto const keep = total - (page * _pageSize); + if (held.rows > keep) { + auto const count = static_cast(keep); + held.content.truncate(count); + if (_keyed) { + held.keys.resize(count); + } + held.levels.resize(count); + held.failedLevels.resize(count); + held.rows = keep; + held.complete = true; + } + } + } + void evict() { auto const center = (_visibleFirst + (_visibleCount / 2)) / _pageSize; while (_pages.size() > _maxPages) { @@ -1092,31 +2237,299 @@ class PageWindow { farthest = at; } } - _complete.erase(farthest->first); _pages.erase(farthest); } } - // Whether a known total bounds the view; a lower bound does not. - [[nodiscard]] bool exactTotal() const noexcept { return _total && _totalKind == TotalKind::Exact; } + [[nodiscard]] RefreshPlan plan(std::span keys) { + if (std::ranges::none_of(_pages, [](auto const& entry) { return entry.second.rows > 0; })) { + return {}; + } + if (!_keyed || !_awaiting.empty()) { + invalidate(); + return RefreshPlan{.kind = Refresh::Pages, .rows = {}}; + } + std::vector asked; + asked.reserve(keys.size() + _pages.size()); + std::unordered_set seen; + seen.reserve(keys.size() + _pages.size()); + for (auto const& key : keys) { + if (seen.insert(key).second) { + asked.push_back(key); + } + } + std::int64_t runEnd = -1; + for (auto const& [page, held] : _pages) { + if (held.rows == 0) { + continue; + } + auto const start = page * _pageSize; + if (start != runEnd && seen.insert(held.keys.front()).second) { + asked.push_back(held.keys.front()); + } + runEnd = start + held.rows; + } + if (asked.size() > _maxKeys) { + invalidate(); + return RefreshPlan{.kind = Refresh::Pages, .rows = {}}; + } + // Only a held key is remembered: an older reply's row for it must not overwrite the newer one, and its + // absence from the latest reply means it left the view. A key the window does not hold needs no memory, since + // a row for it is either outside the held pages (ignored) or inside them (the window refetches). + auto const sequence = ++_sequence; + std::unordered_set heldKeys; + for (auto const& [page, held] : _pages) { + heldKeys.insert(held.keys.begin(), held.keys.end()); + } + for (auto const& key : asked) { + if (heldKeys.contains(key)) { + _latestAsked.insert_or_assign(key, sequence); + } + } + _latestKeyed = sequence; + return RefreshPlan{ + .kind = Refresh::Rows, + .rows = RowsFetch{.keys = std::move(asked), .columns = _columns, .query = _query, .sequence = sequence}}; + } std::int64_t _pageSize; std::size_t _maxPages; + std::size_t _maxKeys; + std::size_t _maxColumns; + bool _keyed; std::uint64_t _query = 0; - std::map> _pages; - std::set _complete; - std::vector _inFlight; + std::uint64_t _revision = 0; + std::map _pages; + std::map _inFlight; std::optional _total; TotalKind _totalKind = TotalKind::Exact; + std::int64_t _undecided = 0; + std::vector _awaiting; + std::vector _failed; + std::uint64_t _totalsRevision = 0; + std::uint64_t _sequence = 0; + std::unordered_map _latestAsked; + std::uint64_t _latestKeyed = 0; + std::vector _owed; + std::vector _columns; + std::map> _named; + std::uint64_t _stamp = 0; std::optional _error; std::int64_t _visibleFirst = 0; std::int64_t _visibleCount = 0; + std::int64_t _coveredFirst = 0; + std::int64_t _coveredLast = -1; +}; + +} // namespace detail + +/// @brief The pages a `server`-mode table holds around the visible rows, kept current under changes. +/// +/// The client calls `visible` as the view scrolls and sends the request of each fetch it returns, then hands the +/// fetch back with its reply to `accept` (or with its error to `fail`). A change of sort or filter is a new +/// query: call `reset`. A reply to a fetch made before the last `reset`, or to a fetch that is no longer the one +/// in flight for its page, is ignored, so a late page never shows over a newer one. +/// +/// A change of the table's record goes to `refresh` (its keys) or `invalidate` (the whole type, a resync); the +/// client sends the keyed fetch a `Rows` plan carries and hands the reply to `patch`, and calls `owed` after each +/// `accept`. The window has no clock and sends nothing: it returns what to fetch. +/// +/// A server may return fewer rows than a fetch asked for (`validate` clamps the limit to its `maxLimit`): the +/// window then fetches the rest of the page from where the reply ended. A page is complete when it is full, +/// reaches the known total, or a reply to it is empty. +/// @tparam Row The row type. +template +class PageWindow : public detail::WindowCore> { + using Core = detail::WindowCore>; + +public: + /// @brief An empty window. + /// @param pageSize Rows per page (default 200). + /// @param maxPages Pages held at most; the farthest from the visible rows go first. + /// @param key The key of a row; without one, every change refetches the visible pages. + /// @param maxKeys Keys one keyed fetch asks for at most; more refetch the pages instead. + /// @param maxColumns Unused by a typed window, whose rows are whole; kept so both windows construct alike. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) - sizes and bounds, each documented above + explicit PageWindow(std::int64_t pageSize = 200, std::size_t maxPages = 8, RowKey key = {}, + std::size_t maxKeys = 1000, std::size_t maxColumns = 96) + : Core{pageSize, maxPages, static_cast(key), maxKeys, maxColumns}, _key{std::move(key)} {} + + /// @brief Declares the visible rows; returns the fetches to send. + /// + /// Covers the visible rows and one page either side, skipping complete pages, pages in flight, and pages past + /// an exact total. A page not held or held stale is fetched whole; a page held in part is fetched from where + /// it ends. The returned pages are marked in flight. + /// @param first First visible view row. + /// @param count Visible rows. + /// @param columns Ignored: a typed row is whole, and every fetch names no column. + /// @return The fetches to send. + [[nodiscard]] std::vector visible(std::int64_t first, std::int64_t count, + std::span columns = {}) { + static_cast(columns); + return this->visibleColumns(first, count, {}); + } + + /// @brief Stores a page reply. + /// @param fetch The fetch the reply answers, as `visible` returned it. + /// @param page The page the server returned. + /// @return `false` when the reply was ignored: its fetch belongs to an earlier query, or is not the one in + /// flight for its page. + bool accept(PageFetch const& fetch, Page page) { + auto const keys = keysOf(page); + return this->acceptReply( + fetch, replyOf(page, keys), + [&page](detail::TypedWindowRows& content, detail::WindowFetchKind kind, std::size_t take) { + auto const end = page.rows.begin() + static_cast(take); + if (kind == detail::WindowFetchKind::Whole) { + content.rows.assign(std::make_move_iterator(page.rows.begin()), std::make_move_iterator(end)); + } else if (kind == detail::WindowFetchKind::Rest) { + content.rows.insert(content.rows.end(), std::make_move_iterator(page.rows.begin()), + std::make_move_iterator(end)); + } + }); + } + + /// @brief Patches held rows from the reply to a `RowsFetch`. + /// @param fetch The keyed fetch the reply answers, as `refresh` or `owed` returned it. + /// @param reply The keyed reply. + /// @return The view rows replaced, ascending; empty when the reply was ignored or the window invalidated. + std::vector patch(RowsFetch const& fetch, Page reply) { + if (!_key) { + return {}; + } + auto const keys = keysOf(reply); + return this->patchRows(fetch, replyOf(reply, keys), + [&reply](Core::Held& page, std::size_t position, std::size_t from) { + page.content.rows[position] = std::move(reply.rows[from]); + }); + } + + /// @brief The row at a view row, when it is held. + /// @param index View row. + /// @return The row, or null. + [[nodiscard]] Row const* row(std::int64_t index) const { + auto const* const page = this->heldAt(index); + return page == nullptr ? nullptr : &page->content.rows[static_cast(index % this->pageSize())]; + } + +private: + [[nodiscard]] std::vector keysOf(Page const& page) const { + std::vector keys; + if (_key) { + keys.reserve(page.rows.size()); + for (auto const& row : page.rows) { + keys.push_back(_key(row)); + } + } + return keys; + } + + [[nodiscard]] static detail::WindowReply replyOf(Page const& page, std::vector const& keys) { + return detail::WindowReply{.keys = keys, + .rows = page.rows.size(), + .unloadedRows = page.unloadedRows, + .total = page.total, + .totalKind = page.totalKind, + .undecided = page.undecided, + .awaiting = page.awaiting, + .failed = page.failed, + .indices = page.indices}; + } + + RowKey _key; }; // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) } // namespace morph::table +namespace morph::table::detail { + +/// @brief Whether a page member is left out of its JSON: `failed`, `indices`, `viewRevision` and `unmatched` when +/// empty. +/// +/// The typed page, the generic page and `UnloadedRow` share this rule. An optional member that is unset is left +/// out by glaze's own rule for null members. A reader takes every member as present or absent. +/// @tparam T The member's type. +/// @param value The member. +/// @param key Its JSON name. +/// @return `true` when it is left out. +template +[[nodiscard]] constexpr bool omittedPageMember(T const& value, std::string_view key) { + if constexpr (requires { value.empty(); }) { + return (key == "failed" || key == "indices" || key == "viewRevision" || key == "unmatched") && value.empty(); + } else { + return false; + } +} + +} // namespace morph::table::detail + +/// @brief The JSON of `morph::table::Page`: every member by reflection, an empty `failed` or `indices` left out. +/// @tparam Row The row type. +template +struct glz::meta> { + /// @brief Whether a member is left out of the JSON written. + /// @tparam T The member's type. + /// @param member The member. + /// @param key Its JSON name. + /// @param context Unused. + /// @return `true` for an empty `failed` or `indices`. + template + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks this hook up by name. + static constexpr bool skip_if(T const& member, std::string_view key, glz::meta_context const& context) { + static_cast(context); + return morph::table::detail::omittedPageMember(member, key); + } +}; + +/// @brief The JSON of `morph::table::TableQuery`: every member by reflection, an empty `retain` left out, so a query +/// that retains nothing carries no `retain` member. +template <> +struct glz::meta { + /// @brief Whether a member is left out of the JSON written. + /// @tparam T The member's type. + /// @param member The member. + /// @param key Its JSON name. + /// @param context Unused. + /// @return `true` for an empty `retain`. + template + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks this hook up by name. + static constexpr bool skip_if(T const& member, std::string_view key, glz::meta_context const& context) { + static_cast(context); + if constexpr (requires { member.empty(); }) { + return key == "retain" && member.empty(); + } else { + return false; + } + } +}; + +/// @brief The JSON of `morph::table::UnloadedRow`: every member by reflection, an empty `failed` left out. +template <> +struct glz::meta { + /// @brief Whether a member is left out of the JSON written. + /// @tparam T The member's type. + /// @param member The member. + /// @param key Its JSON name. + /// @param context Unused. + /// @return `true` for an empty `failed`. + template + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks this hook up by name. + static constexpr bool skip_if(T const& member, std::string_view key, glz::meta_context const& context) { + static_cast(context); + return morph::table::detail::omittedPageMember(member, key); + } +}; + +/// @brief JSON names of `morph::table::DateBucket`: `value`, `year`, `month` and `day`. +template <> +struct glz::meta { + using enum morph::table::DateBucket; + /// @brief Each enumerator after its JSON name. + static constexpr auto value = glz::enumerate("value", Value, "year", Year, "month", Month, "day", Day); +}; + /// @brief JSON names of `morph::table::TotalKind`: `exact` and `atLeast`. template <> struct glz::meta { @@ -1124,3 +2537,30 @@ struct glz::meta { /// @brief Each enumerator after its JSON name. static constexpr auto value = glz::enumerate("exact", Exact, "atLeast", AtLeast); }; + +/// @brief The JSON of `morph::table::MeasureValue`: `{"num", "den", "unit"}`. +template <> +struct glz::meta { + /// @brief Read and written through its wire shape. + static constexpr auto value = + glz::custom<&morph::table::MeasureValue::setWire, &morph::table::MeasureValue::getWire>; + /// @brief The schema's name. + static constexpr std::string_view name = "MeasureValue"; +}; + +namespace glz::detail { + +/// @brief The schema of `MeasureValue`: its wire object, so its properties are `num`, `den` and `unit`. +template <> +struct to_json_schema { + /// @brief Writes the wire shape's schema. + /// @tparam Opts The write options. + /// @param outSchema The schema written. + /// @param defs The definitions. + template + static void op(auto& outSchema, auto& defs) { + to_json_schema::template op(outSchema, defs); + } +}; + +} // namespace glz::detail diff --git a/include/morph/table/record_name.hpp b/include/morph/table/record_name.hpp new file mode 100644 index 000000000..36d33e6fe --- /dev/null +++ b/include/morph/table/record_name.hpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file table/record_name.hpp +/// @brief A record's registered name, looked up by type. +/// +/// Its own header so the table headers that write a record's name into a schema can each include it, whichever of +/// them a translation unit reaches first. + +#include +#include +#include +#include + +namespace morph::table::detail { + +/// @brief A record's registered name, by the record's type. +/// @param type The record type. +/// @return Its name in `record::detail::recordRegistry()`, or empty when none is registered. +[[nodiscard]] inline std::string recordNameOf(std::type_index type) { + auto const& records = record::detail::recordRegistry(); + auto const found = std::ranges::find(records, type, &record::RecordInfo::type); + return found != records.end() ? found->name : std::string{}; +} + +} // namespace morph::table::detail diff --git a/include/morph/table/row_selection.hpp b/include/morph/table/row_selection.hpp new file mode 100644 index 000000000..4e2e92dbd --- /dev/null +++ b/include/morph/table/row_selection.hpp @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file table/row_selection.hpp +/// @brief What a user selected in a model's table, as an action receives it, and how the server turns it into +/// keys. +/// +/// On a model-backed table the client holds a window, not the view, so "every row I see" is a description of the +/// view: its filter, its retained rows and its revision, less the keys the user took out. `resolve` turns it into +/// keys on the server, in the table's source order, for the caller: the table's function is called for the caller, +/// so its row scope and `mayRead` apply. +/// +/// See `docs/spec/table/table.md`, "A selection of the view". + +#include +#include +#include +#include +#include +#include +#include +// NOLINTNEXTLINE(misc-header-include-cycle): description.hpp includes this header at its end, after the declarations this one needs. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table { + +namespace detail { + +/// @brief A filter's JSON with every member at its default left out: a `combine` of `any`, and empty lists, texts +/// and nulls. It reads back as the same filter, and is the shape a client writes. +/// @param filters The filter. +/// @return The JSON text. +[[nodiscard]] MORPH_API std::string compactFilterJson(FilterSpec const& filters); + +/// @brief The JSON of a selection: `{"keys": […]}` without a view, `{"view": {…}, "except": […]}` with one. +/// @param keys The keys of a key selection. +/// @param filters The view's filter; null for a key selection. +/// @param retained The view's retained rows. +/// @param revision The view's revision. +/// @param except The keys the view selection leaves out. +/// @return The JSON text. +[[nodiscard]] MORPH_API std::string selectionJson(std::span keys, FilterSpec const* filters, + std::span retained, std::string_view revision, + std::span except); + +} // namespace detail + +/// @brief What a user selected in one table: exactly some keys, or every row of a view less some keys. +/// +/// Its JSON is `{"keys": […]}`, or `{"view": {"filters", "retained", "revision"}, "except": […]}`; a filter is +/// written with its default members left out. Its schema property carries `x-selectionOf` with the table's record, +/// so a client knows which table an action works on. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` names it. +template +struct RowSelection { + /// @brief The view a selection of the view is of. + struct View { + /// @brief The view's filter, as the table queried it. + FilterSpec filters; + /// @brief The rows the view kept although they no longer match. + std::vector retained; + /// @brief The view's `viewRevision` when the user selected it. + std::string revision; + }; + + /// @brief Without `view`: exactly these rows. + std::vector keys; + /// @brief With it: every row of that view, less `except`. + std::optional view; + /// @brief The keys a selection of the view leaves out. + std::vector except; + + /// @brief The schema keyword and its value that name the selection's table. + /// @return `{"x-selectionOf", "."}`, the record's registered name; the name is empty when no such + /// record is registered. + [[nodiscard]] static std::pair schemaValue() { + return {"x-selectionOf", detail::recordNameOf(std::type_index{typeid(TableOf)})}; + } +}; + +/// @brief How `resolve` treats a view whose rows changed since the user selected it. +enum class SelectionPolicy : std::uint8_t { + Exact, ///< Refuse with `ViewChanged` when the view's membership differs from the selection's revision. + Current, ///< Act on the view as it is when the action runs. +}; + +/// @brief What `resolve` returns. +struct SelectedRows { + /// @brief The keys, in the table's source order. + std::vector keys; + /// @brief Keys of a key selection the caller may no longer see, left out. + std::int64_t dropped = 0; +}; + +/// @brief The body of `Table..resolve`, for an action of another model or a task off the model's strand. +/// @tparam Function The table's function. +template +struct ResolveRequest { + /// @brief The selection. + RowSelection selection; + /// @brief How a changed view is treated. + SelectionPolicy policy = SelectionPolicy::Exact; +}; + +/// @brief One row of a table, as an action's input names it. Its JSON is the key itself; its schema property +/// carries `x-rowOf` with the table's record. +/// @tparam Function The table's function. +template +struct RowRef { + /// @brief The row's key. + RowId key; + + /// @brief The schema keyword and its value that name the row's table. + /// @return `{"x-rowOf", "."}`; the name is empty when no such record is registered. + [[nodiscard]] static std::pair schemaValue() { + return {"x-rowOf", detail::recordNameOf(std::type_index{typeid(TableOf)})}; + } +}; + +namespace detail { + +/// @brief A selection of any table: what the work off the strand reads. +struct PlainSelection { + /// @brief `RowSelection::keys`. + std::vector keys; + /// @brief Whether the selection is of a view. + bool isView = false; + /// @brief `RowSelection::View::filters`. + FilterSpec filters; + /// @brief `RowSelection::View::retained`. + std::vector retained; + /// @brief `RowSelection::View::revision`. + std::string revision; + /// @brief `RowSelection::except`. + std::vector except; +}; + +/// @brief A view's membership: its rows and the digest of their keys. +struct Membership { + /// @brief The view's source rows, in source order. + std::vector rows; + /// @brief The keys of `rows`, as a set. + MembershipDigest digest; +}; + +/// @brief The membership of the view of @p filters over @p served, with the retained rows merged in. +/// +/// The view is the filter's rows under an empty sort, whose order is the source's. It is taken from @p views when +/// one is given and @p record is not empty, under the key a page query of the same filter and no sort uses, unless +/// the filter reads a level; otherwise it is computed for the call. Each key of @p retained that the source has +/// and the view lacks is merged in at its source row and added to the digest. +/// @param served The table, its source pinned. +/// @param filters The view's filter. +/// @param retained The rows the view kept although they no longer match. +/// @param views The server's view cache; null computes the view. +/// @param record The table's record name, the first member of a view's key; empty caches nothing. +/// @return The membership, or the error the filter or the bound gives: `LimitExceeded` for a view of more than +/// `served.limits.maxSelectedRows` rows. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] MORPH_API std::expected membership(ServedTable const& served, + FilterSpec const& filters, + std::span retained, + ViewCache* views, + std::string_view record = {}); + +/// @brief Resolves @p selection over @p served in the calling thread: `resolve`'s work. +/// @param served The table, its source pinned. +/// @param selection The selection. +/// @param policy How a changed view is treated. +/// @param views The server's view cache; null computes the view. +/// @param record The table's record name; empty caches nothing. +/// @param rowScoped The registration's `rowScoped`: the table then needs a `ServedTable::scope`. +/// @return The keys in source order, or the error: `SourceContract` for a row-scoped table with no scope. +[[nodiscard]] MORPH_API std::expected resolveSelection( + ServedTable const& served, PlainSelection const& selection, SelectionPolicy policy, ViewCache* views, + std::string_view record, bool rowScoped = false); + +/// @brief The owner of a `resolve` that runs where it is called: runs each task at once, inside a scope that names +/// it, so the completion's checks find the task on its owner. +/// +/// One object serves every thread. It is serial for each completion only: every post it gets for one completion +/// comes from the thread that called `resolve` (the settle within the call, then a `then` or `co_await` attach on +/// that thread), and the scope it states is the calling thread's own. Two threads resolving at once run their tasks +/// side by side, each touching only its own completion. +class MORPH_API ResolveInline final : public exec::IExecutor { +public: + /// @brief Runs @p task now, on the calling thread. + /// @param task The task. + void post(std::function task) override; +}; + +/// @brief The selection as the work off the strand reads it. +/// @tparam Function The table's function. +/// @param selection The selection. +/// @return Its plain copy. +template +[[nodiscard]] PlainSelection plainOf(RowSelection const& selection) { + PlainSelection out; + out.keys = selection.keys; + out.except = selection.except; + if (selection.view) { + out.isView = true; + out.filters = selection.view->filters; + out.retained = selection.view->retained; + out.revision = selection.view->revision; + } + return out; +} + +} // namespace detail + +/// @brief Turns a selection into keys, for the caller. +/// +/// Calls the table's function on @p model on the calling thread, the model's strand, for @p context, so the +/// caller's row scope and `mayRead` apply and a `typed` table works as a plain one. A key selection resolves +/// to the keys the caller can still see, in source order, counting the others in `dropped`. A selection of the view +/// resolves to the view's membership (the filter's rows under an empty sort, the retained rows merged in) less +/// `except`, in source order; under `Exact` a membership whose digest differs from the selection's revision is +/// `ViewChanged`. A view of more than `QueryLimits::maxSelectedRows` rows is `LimitExceeded`. +/// +/// Inside a server's dispatch the work runs on the runtime's `work` with its view cache, and the completion +/// belongs to the runtime's `settle`. With no runtime, or one missing either of the two, it runs here with no cache +/// (a runtime with `work` and no `settle` included), and the completion is settled before this returns: a `then` +/// attached afterwards on this thread runs at once, and `co_await` works from any coroutine. A `then` attached from +/// a task of another executor is off the completion's owner, which a debug build asserts. A row-scoped table whose +/// function returns no `scope` is `SourceContract`, as a page query of it is. +/// @tparam Function The table's function. +/// @tparam Model The model type. +/// @param model The model instance; not const, as a table function is not. +/// @param selection The selection. +/// @param context Who asks. +/// @param policy How a changed view is treated. +/// @return The keys, or the error. +template +[[nodiscard]] async::Completion> resolve( + Model& model, RowSelection const& selection, TableContext const& context, SelectionPolicy policy) { + using Result = std::expected; + auto served = detail::pinned(detail::serve(model, context)); + auto plain = detail::plainOf(selection); + auto record = detail::recordNameOf(std::type_index{typeid(TableOf)}); + bool const rowScoped = detail::tableRecordOf().second; + auto const* const runtime = currentTableRuntime(); + if (runtime == nullptr || runtime->work == nullptr || runtime->settle == nullptr) { + static detail::ResolveInline owner; + auto [completion, promise] = async::Completion::makeSettleable(&owner); + try { + promise.resolve(detail::resolveSelection(served, plain, policy, nullptr, record, rowScoped)); + } catch (...) { + promise.reject(std::current_exception()); + } + return std::move(completion); + } + auto [completion, promise] = async::Completion::makeSettleable(runtime->settle); + // A posted task is a `std::function`, which copies: the promise is shared. + auto const shared = std::make_shared::Promise>(std::move(promise)); + runtime->work->post([shared, served = std::move(served), plain = std::move(plain), policy, rowScoped, + views = runtime->views, record = std::move(record), keep = runtime->settleKeep] { + static_cast(keep); + try { + shared->resolve(detail::resolveSelection(served, plain, policy, views, record, rowScoped)); + } catch (...) { + shared->reject(std::current_exception()); + } + }); + return std::move(completion); +} + +/// @brief Throws the refusal a Task handler gives for a table's error. +/// @param error The error `resolve` returned. +/// @throws model::ActionRefusal `"morph.table.viewChanged"` for `ViewChanged`, `"morph.table." + ` for every other code, with the error's message. +[[noreturn]] inline void refuse(TableError const& error) { + throw model::ActionRefusal{"morph.table." + detail::errorCodeName(error.code), {}, error.message}; +} + +/// @brief The action `Table..resolve`: a selection resolved for the caller, as `resolve` does on the model. +/// +/// Its JSON is the `ResolveRequest`'s. It runs as `Table.` does: the table's function for the caller's session +/// on the model's strand, then the work on the server's table executor. +/// @tparam Function The table's function, as `BRIDGE_REGISTER_TABLE` keys it. +template +struct ResolveTable { + /// @brief The selection and the policy. + ResolveRequest request; + + /// @brief Resolves the selection. + /// @tparam Model The model type. + /// @param model The model instance. + /// @param action The action. + /// @return The keys. + /// @throws morph::model::ActionRefusal `table.` with the argument `column`, as `Table.` refuses. + template + // NOLINTNEXTLINE(cppcoreguidelines-avoid-reference-coroutine-parameters): the dispatcher keeps the model and the action alive until the task completes. + static ::core::async::Task invoke(Model& model, ResolveTable& action) { + auto const context = detail::callerContext(); + // Its own statement: MSVC cannot tail-call a call that shares a full-expression with a `co_await`. + auto completion = resolve(model, action.request.selection, context, action.request.policy); + auto resolved = co_await std::move(completion); + if (!resolved) { + throw detail::refusalOf(resolved.error()); + } + co_return std::move(*resolved); + } +}; + +} // namespace morph::table + +/// @brief JSON names of `morph::table::SelectionPolicy`: `exact` and `current`. +template <> +struct glz::meta { + using enum morph::table::SelectionPolicy; + /// @brief Each enumerator after its JSON name. + static constexpr auto value = glz::enumerate("exact", Exact, "current", Current); +}; + +namespace morph::table::detail { + +/// @brief What a `RowSelection` is read from: every member optional. +struct SelectionWire { + /// @brief The view, when the selection is of one. + struct View { + /// @brief Its filter. + FilterSpec filters; + /// @brief Its retained rows. + std::vector retained; + /// @brief Its revision. + std::string revision; + }; + /// @brief The keys of a key selection. + std::vector keys; + /// @brief The view. + std::optional view; + /// @brief The keys a selection of the view leaves out. + std::vector except; +}; + +} // namespace morph::table::detail + +/// @brief The JSON of `morph::table::RowSelection`: `{"keys"}` or `{"view", "except"}`. +/// @tparam Function The table's function. +template +struct glz::meta> { + /// @brief The selection type. + using T = morph::table::RowSelection; + /// @brief Read from the wire shape, written by `detail::selectionJson`. + static constexpr auto value = + glz::custom<[](T& selection, morph::table::detail::SelectionWire const& wire) { + selection.keys = wire.keys; + selection.except = wire.except; + selection.view.reset(); + if (wire.view) { + selection.view = typename T::View{ + .filters = wire.view->filters, .retained = wire.view->retained, .revision = wire.view->revision}; + } + }, + [](T const& selection) { + return glz::raw_json{morph::table::detail::selectionJson( + selection.keys, selection.view ? &selection.view->filters : nullptr, + selection.view ? std::span{selection.view->retained} + : std::span{}, + selection.view ? std::string_view{selection.view->revision} : std::string_view{}, + selection.except)}; + }>; +}; + +/// @brief The JSON of `morph::table::RowRef`: its key. +/// @tparam Function The table's function. +template +struct glz::meta> { + /// @brief The reference type. + using T = morph::table::RowRef; + /// @brief Written as its key. + static constexpr auto value = &T::key; +}; + +/// @brief The JSON of `morph::table::ResolveTable`: its `ResolveRequest`'s. +/// @tparam Function The table's function. +template +struct glz::meta> { + /// @brief The action type. + using T = morph::table::ResolveTable; + /// @brief The action is written as its request. + static constexpr auto value = &T::request; +}; + +namespace glz::detail { + +/// @brief The schema of a `RowSelection`: its wire object. +/// @tparam Function The table's function. +template +struct to_json_schema> { + /// @brief Writes the wire shape's schema. + /// @tparam Opts The write options. + /// @param outSchema The schema written. + /// @param defs The definitions. + template + static void op(auto& outSchema, auto& defs) { + to_json_schema::template op(outSchema, defs); + } +}; + +} // namespace glz::detail diff --git a/include/morph/table/runtime.hpp b/include/morph/table/runtime.hpp new file mode 100644 index 000000000..9f945a3a4 --- /dev/null +++ b/include/morph/table/runtime.hpp @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file table/runtime.hpp +/// @brief Where a table's work runs: what a server installs around a dispatch, +/// for a table's action to read before its first suspension. +/// +/// A table's function runs on the model's strand; the rest of a reply (the +/// sort, the filter, the page) runs on the server's table executor, so a sort +/// of many rows does not hold the strand. `RemoteServer` installs a +/// `TableRuntime` naming that executor for the length of each dispatch; +/// outside one there is none, and the reply is built where the action runs. +/// +/// It also declares the server's view cache by name only (`ViewCache`, made by +/// `makeViewCache`), so a server holds one without its definition. +/// +/// This header includes only the executor, so `core/remote.hpp` reaches it +/// without the table headers. + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table { + +/// @brief How a server's view cache is bounded. +struct ViewCacheOptions { + /// @brief The most bytes the cached views hold, across the server's tables, before the least recently used + /// go. It counts the views, their order keys and their lookups, not the snapshots the views keep alive. + std::size_t maxBytes = 64U << 20U; + /// @brief Called on the computing thread at the start of each computation; empty calls nothing. + std::function onCompute; +}; + +/// @brief What a view cache has done since it was made; `bytes` is what it holds now. +struct ViewCacheStats { + /// @brief Finds that used a valid entry. + std::size_t hits = 0; + /// @brief Finds that found no valid entry. + std::size_t misses = 0; + /// @brief Views computed. + std::size_t computations = 0; + /// @brief Finds that waited for another request's computation. + std::size_t waits = 0; + /// @brief Entries evicted at the bound. + std::size_t evictions = 0; + /// @brief Entries dropped because the rows or an order level changed. + std::size_t invalidations = 0; + /// @brief The bytes the entries hold. + std::size_t bytes = 0; +}; + +class ViewCache; + +/// @brief A view cache, for a holder that does not see its definition. +/// @param options Its bound and computation hook. +/// @return The cache. +[[nodiscard]] MORPH_API std::shared_ptr makeViewCache(ViewCacheOptions options); + +/// @brief A view cache's counters, for a holder that does not see its definition. +/// @param cache The cache. +/// @return Its counters. +[[nodiscard]] MORPH_API ViewCacheStats viewCacheStats(ViewCache const& cache); + +/// @brief What a server gives a table's actions for one dispatch. +struct TableRuntime { + /// @brief Where a reply is built, off the model's strand; null builds it on the strand. + exec::IExecutor* work = nullptr; + /// @brief The server's view cache; null computes every view for its request. + ViewCache* views = nullptr; + /// @brief A serial executor a `resolve`'s completion belongs to: where it settles and its handlers run, so a + /// Task handler awaiting it from any strand finds one owner. Null runs `resolve` where it is called. + exec::IExecutor* settle = nullptr; + /// @brief Keeps `settle` alive while a `resolve`'s work is queued on `work`, which may outlive the server; the + /// server closes `settle` when it goes, so a delivery that comes later is dropped. Null when nothing does. + std::shared_ptr settleKeep; + /// @brief An action's input schema by its id, as the server serves it: what a table's description checks its + /// columns' edit actions against. Empty when the server offers none; an action it does not know answers + /// an empty text. + std::function schemaOf; +}; + +namespace detail { + +/// @brief The calling thread's slot for the installed runtime. +/// @return The slot; null when no runtime is installed. +[[nodiscard]] MORPH_API TableRuntime const*& tableRuntimeSlot() noexcept; + +} // namespace detail + +/// @brief The runtime installed on the calling thread. +/// @return The runtime, or null outside a `RemoteServer` dispatch. +[[nodiscard]] MORPH_API TableRuntime const* currentTableRuntime() noexcept; + +/// @brief Installs a runtime on the calling thread for the scope, and restores the previous one. +class TableRuntimeScope { +public: + /// @brief Installs @p runtime. + /// @param runtime The runtime; must outlive the scope. + explicit TableRuntimeScope(TableRuntime const& runtime MORPH_LIFETIMEBOUND) noexcept + : _previous{detail::tableRuntimeSlot()} { + detail::tableRuntimeSlot() = &runtime; + } + + /// @brief Restores the runtime installed before this scope. + ~TableRuntimeScope() { detail::tableRuntimeSlot() = _previous; } + + TableRuntimeScope(TableRuntimeScope const&) = delete; + TableRuntimeScope& operator=(TableRuntimeScope const&) = delete; + TableRuntimeScope(TableRuntimeScope&&) = delete; + TableRuntimeScope& operator=(TableRuntimeScope&&) = delete; + +private: + TableRuntime const* _previous; +}; + +} // namespace morph::table diff --git a/include/morph/table/sort.hpp b/include/morph/table/sort.hpp index cd394168a..fed426595 100644 --- a/include/morph/table/sort.hpp +++ b/include/morph/table/sort.hpp @@ -13,7 +13,8 @@ /// only a `Number` column holds a double. /// /// Ordering rules, normative for every client and server (spec 7 §5): -/// - an empty or invalid cell sorts after every valid one, in either direction; +/// - an empty or invalid cell sorts after every valid one, and an unloaded cell +/// after every empty or invalid one, in either direction; /// - each key of a chain has its own direction; /// - ties break by source row, so the sort is stable. /// @@ -30,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -51,7 +53,7 @@ namespace morph::table { /// @brief A sort key's direction. enum class SortDirection : std::uint8_t { Ascending, ///< Smallest first. - Descending, ///< Largest first. Invalid cells still come last. + Descending, ///< Largest first. Empty, invalid and unloaded cells still come last. }; /// @brief One key of a sort chain. @@ -72,9 +74,10 @@ using SortChain = std::vector; /// @brief Whether a cell has a key. enum class CellState : std::uint8_t { - Valid, ///< The cell has a key. - Empty, ///< The cell is empty; it sorts with invalid cells. - Invalid, ///< The cell could not be read for its column's kind. + Valid, ///< The cell has a key. + Empty, ///< The cell is empty; it sorts with invalid cells. + Invalid, ///< The cell could not be read for its column's kind. + Unloaded, ///< The cell's value is not loaded yet; it has no key and sorts after every other state. }; /// @brief A deadline for one step of work; `kNoDeadline` runs to completion. @@ -130,13 +133,26 @@ inline constexpr std::size_t kCheckEvery = 2048; /// `parseReal` for a standard library without floating-point `from_chars`. /// /// The classic locale, not the global one: a filter value is the wire's text, so its decimal point is `.` whatever -/// locale the process runs in. +/// locale the process runs in. Infinity is read as `from_chars` reads it, `inf` or `infinity` in any case with an +/// optional `-`, which a stream does not do itself; so a filter means the same with either reader. /// @param text The text. /// @return The value, or nothing when @p text is not exactly a number or is NaN. [[nodiscard]] inline std::optional parseRealClassic(std::string_view text) { if (text.empty() || text.front() == '+' || std::isspace(static_cast(text.front())) != 0) { return std::nullopt; } + { + bool const negative = text.front() == '-'; + std::string_view const magnitude = negative ? text.substr(1) : text; + auto const spells = [magnitude](std::string_view word) { + return std::ranges::equal(magnitude, word, [](char got, char want) { + return std::tolower(static_cast(got)) == want; + }); + }; + if (spells("inf") || spells("infinity")) { + return negative ? -std::numeric_limits::infinity() : std::numeric_limits::infinity(); + } + } std::istringstream stream{std::string{text}}; stream.imbue(std::locale::classic()); double value = 0; @@ -166,6 +182,43 @@ inline constexpr std::size_t kCheckEvery = 2048; #endif } +/// @brief Splits a measure operand: a decimal, or a decimal, one space and a unit id. +/// +/// The form a filter operand on a `Measure` column has on the wire, whatever the user's locale: `"250 g"`, +/// `"0.3 kg"`; a decimal with no unit names the ratio's unit `""`. The decimal is read by `parseDecimal`. +/// @param text The operand. +/// @return The amount and the unit's id, or nothing when @p text has another form. +[[nodiscard]] inline std::optional> splitMeasureOperand( + std::string_view text) { + auto const space = text.find(' '); + auto const amount = parseDecimal(text.substr(0, space)); + if (!amount) { + return std::nullopt; + } + if (space == std::string_view::npos) { + return std::pair{*amount, std::string_view{}}; + } + auto const unit = text.substr(space + 1); + if (unit.empty() || unit.contains(' ')) { + return std::nullopt; + } + return std::pair{*amount, unit}; +} + +/// @brief The place of a dimension in a `Measure` column: the index its group sorts at. +/// @param info The column. +/// @param registry The registry. +/// @param dimension The dimension's name. +/// @return Its index in `info.dimensions`, or in `registry.dimensions()` when the column names none; -1 when the +/// column does not allow it. +[[nodiscard]] inline std::int32_t dimensionPlace(ColumnInfo const& info, UnitRegistry const& registry, + std::string_view dimension) { + std::span const order = + info.dimensions.empty() ? registry.dimensions() : std::span{info.dimensions}; + auto const found = std::ranges::find(order, dimension); + return found == order.end() ? -1 : static_cast(found - order.begin()); +} + } // namespace detail /// @brief One column's keys, built once and shared, immutable, between jobs. @@ -174,7 +227,9 @@ inline constexpr std::size_t kCheckEvery = 2048; /// `ints` for `Integer`, `Key`, `Date`, `DateTime` and `Bool`; `exact` for /// `Decimal` and `Quantity`; `reals` for `Number`; `text`, `folded` and `raw` /// for `Text`; `cells` for a `Custom` column with a known comparator, and -/// `text` for one without (ordered by display text). +/// `text` for one without (ordered by display text); `exact` and `places` for +/// `Measure`, whose key is the pair of its dimension's place and its amount in +/// the dimension's base unit. struct KeyColumn { /// @brief The column's kind. ColumnKind kind = ColumnKind::Text; @@ -182,8 +237,15 @@ struct KeyColumn { std::vector states; /// @brief Integer keys. std::vector ints; - /// @brief Exact keys. + /// @brief Exact keys; a measure's amount in its dimension's base unit. std::vector exact; + /// @brief A `Measure` column's places: each row's dimension, as its index among the column's dimensions. + std::vector places; + /// @brief A `Measure` column's dimension place of each unit, by unit number: -1 for a tombstone or a dimension + /// the column does not allow. Built once from the registry, so a cell's unit is read by its number. + std::vector unitPlaces; + /// @brief A `Measure` column's factor of each unit to its dimension's base, by unit number. + std::vector unitFactors; /// @brief Floating-point keys. std::vector reals; /// @brief Collation keys. @@ -239,6 +301,22 @@ struct KeyColumn { out.text.resize(rows); } break; + case ColumnKind::Measure: + out.exact.assign(rows, math::Rational{}); + out.places.assign(rows, 0); + if (services.units != nullptr) { + auto const& registry = *services.units; + out.unitPlaces.assign(registry.size(), -1); + out.unitFactors.assign(registry.size(), math::Rational{}); + for (UnitId unit = 0; unit < registry.size(); ++unit) { + if (registry.contains(unit)) { + auto const& known = registry.info(unit); + out.unitPlaces[unit] = detail::dimensionPlace(info, registry, known.dimension); + out.unitFactors[unit] = known.toBase; + } + } + } + break; default: break; } @@ -256,6 +334,10 @@ struct KeyColumn { private: [[nodiscard]] CellState read(std::size_t row, Cell const& cell, ColumnInfo const& info, Services const& services) { + // Before the kind: every kind treats an unloaded cell alike, and none stores a key for it. + if (std::holds_alternative(cell)) { + return CellState::Unloaded; + } if (std::holds_alternative(cell)) { return CellState::Empty; } @@ -292,12 +374,51 @@ struct KeyColumn { text[row] = detail::collatorOf(services).sortKey(displayText(cell)); } return CellState::Valid; + case ColumnKind::Measure: + return readMeasure(row, cell, services); default: break; } return CellState::Invalid; } + // A measure, a plain number (the ratio's unit, number 0) or an operand's text. A measure's unit is read by its + // number through the tables `forColumn` built, so building keys looks no unit up by its id. + [[nodiscard]] CellState readMeasure(std::size_t row, Cell const& cell, Services const& services) { + math::Rational amount; + UnitId unit = 0; + if (auto const* const value = std::get_if(&cell)) { + amount = value->amount; + unit = value->unit; + } else if (auto const* const exactValue = std::get_if(&cell)) { + amount = *exactValue; + } else if (auto const* const integer = std::get_if(&cell)) { + amount = math::Rational{*integer, math::DecimalPlaces{0}}; + } else if (auto const* const textValue = std::get_if(&cell)) { + auto const operand = detail::splitMeasureOperand(*textValue); + auto const found = + operand && services.units != nullptr ? services.units->find(operand->second) : std::nullopt; + if (!found) { + return CellState::Invalid; + } + amount = operand->first; + unit = *found; + } else { + return CellState::Invalid; + } + if (unit >= unitPlaces.size() || unitPlaces[unit] < 0) { + return CellState::Invalid; + } + // Checked: a product that does not fit is an invalid cell, as for a quantity. + auto const base = math::checkedMul(amount, unitFactors[unit]); + if (!base) { + return CellState::Invalid; + } + exact[row] = *base; + places[row] = static_cast(unitPlaces[unit]); + return CellState::Valid; + } + [[nodiscard]] CellState readInteger(std::size_t row, Cell const& cell) { if (auto const* value = std::get_if(&cell)) { ints[row] = *value; @@ -424,21 +545,35 @@ inline void buildKeys(RowSnapshot const& snapshot, std::size_t column, ColumnInf snapshot.readColumn(column, sink, first, last); } -/// @brief Compares two rows' keys in one column, valid before invalid in -/// either direction. +/// @brief Compares two rows' keys in one column: valid cells first, then empty +/// and invalid ones, then unloaded ones, in either direction. /// @param keys The column's keys. /// @param left One row. /// @param right Another row. -/// @param dir The key's direction; it does not move invalid cells. +/// @param dir The key's direction; it does not move empty, invalid or unloaded cells. /// @return Negative, zero or positive as row @p left orders before, with, or after @p right. [[nodiscard]] inline int compareKeys(KeyColumn const& keys, std::uint32_t left, std::uint32_t right, SortDirection dir) { - bool const validA = keys.states[left] == CellState::Valid; - bool const validB = keys.states[right] == CellState::Valid; - if (validA != validB) { - return validA ? -1 : 1; + // Valid 0; Empty and Invalid 1 (they tie); Unloaded 2 (they tie). Ranks never flip with the direction, so an + // unloaded cell is never placed among the empties it might not belong to. + auto const rank = [](CellState state) { + switch (state) { + case CellState::Valid: + return 0; + case CellState::Unloaded: + return 2; + case CellState::Empty: + case CellState::Invalid: + default: + return 1; + } + }; + int const rankA = rank(keys.states[left]); + int const rankB = rank(keys.states[right]); + if (rankA != rankB) { + return rankA < rankB ? -1 : 1; } - if (!validA) { + if (rankA != 0) { return 0; } auto const sign = [](auto ordering) -> int { @@ -470,6 +605,14 @@ inline void buildKeys(RowSnapshot const& snapshot, std::size_t column, ColumnInf result = keys.usesComparator() ? sign(keys.comparator(keys.cells[left], keys.cells[right])) : sign(keys.text[left].compare(keys.text[right]) <=> 0); break; + case ColumnKind::Measure: + // Dimensions keep their declared order in either direction: comparing kilograms with percent means + // nothing, so there is nothing to reverse between them. + if (keys.places[left] != keys.places[right]) { + return keys.places[left] < keys.places[right] ? -1 : 1; + } + result = sign(keys.exact[left] <=> keys.exact[right]); + break; default: break; } diff --git a/include/morph/table/state_store.hpp b/include/morph/table/state_store.hpp new file mode 100644 index 000000000..7865afa39 --- /dev/null +++ b/include/morph/table/state_store.hpp @@ -0,0 +1,624 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file table/state_store.hpp +/// @brief A table's persisted state: the store interface, the memory store, and the state document. +/// +/// A table's arrangement (column layout, sort chain, filters, the saved view it came from) is stored as a JSON +/// document per table through an `ITableStateStore` the application injects. `readState` reads the stored +/// shape, `fitState` fits it to the description the caller receives, keeping what names a column or group the +/// description lacks as `carried`, and `writeState` writes it back with the carried parts in their places. +/// +/// See `docs/spec/table/table.md`, "Persisted state". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table { + +/// @brief Which table's state. No member names a person: a store keeps one person's state apart from another's +/// itself. +struct TableStateKey { + /// @brief The application. + std::string application; + /// @brief The model's type; empty for a table over a document's rows. + std::string model; + /// @brief The table's id; for a `rows` table, the node's id. + std::string table; + /// @brief The screen's id, or what the table's `persist` names. + std::string qualifier; + /// @brief `"state"`, `"views"` or `"shared"`. + std::string part; + + /// @brief Member-wise equality. + /// @param other The key to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(TableStateKey const& other) const = default; +}; + +/// @brief A stored document and the revision that names it. +struct StoredTableState { + /// @brief The document's JSON text. + std::string json; + /// @brief Names this stored document; opaque. + std::string revision; +}; + +/// @brief What a save did. +enum class SaveOutcome : std::uint8_t { + Saved, ///< The document is stored. + Conflict, ///< The stored document's revision is not the expected one; nothing was written. + Refused, ///< The store would not keep the document; `reason` says why. +}; + +/// @brief The answer to a save. +struct SaveResult { + /// @brief What the save did. + SaveOutcome outcome = SaveOutcome::Saved; + /// @brief The revision of what is stored now; empty when nothing is. + std::string revision; + /// @brief Why the store refused, for `Refused`. + std::string reason; +}; + +/// @brief An `expected` revision that stores only when nothing is stored under the key, and answers `Conflict` +/// otherwise. +/// +/// A table whose `views` part was empty when it loaded saves its first view with it, so two windows that both start +/// from no views cannot overwrite each other's first view. An empty `expected` cannot say that: it means "replace +/// whatever is stored". +inline constexpr std::string_view kNoDocument = "-"; + +/// @brief The version of the views document this framework writes. +inline constexpr int kViewsVersion = 1; + +/// @brief A saved view: a name with a column layout, a sort chain and filters. +struct SavedView { + /// @brief The view's name, unique in its document. + std::string name; + /// @brief The column layout. + ColumnLayoutValue layout; + /// @brief The sort chain. + SortChain sort; + /// @brief The filters. + FilterSpec filters; +}; + +/// @brief Which views document: the user's own (`part: "views"`) or the one published for everyone +/// (`part: "shared"`). +enum class ViewsPart : std::uint8_t { + Own, ///< The user's own views, with a default and `defaultOnMount`. + Shared, ///< The shared views, which have neither: those are each user's own choice. +}; + +/// @brief A views document: the `views` or the `shared` part of a table's persisted state. +/// +/// Its JSON is `{"version", "default", "defaultOnMount", "views"}`; a `Shared` document writes neither `default` nor +/// `defaultOnMount`. +struct ViewsDocument { + /// @brief The document's version. + int version = kViewsVersion; + /// @brief The view applied when the table mounts and no `state` is stored. + std::optional defaultView; + /// @brief Whether the default view's sort and filters are applied at every mount, over the stored state's. + bool defaultOnMount = false; + /// @brief The views, in the order they were added. + std::vector views; +}; + +/// @brief Adds a view under a name no view has. +struct AddView { + /// @brief The view. + SavedView view; +}; + +/// @brief Replaces the layout, sort and filters of the view of the same name. +struct ReplaceView { + /// @brief The view, named as the one it replaces. + SavedView view; +}; + +/// @brief Renames a view. +struct RenameView { + /// @brief The view's name now. + std::string from; + /// @brief Its new name, which no other view has. + std::string to; +}; + +/// @brief Removes a view; removing the default view clears the default. +struct RemoveView { + /// @brief The view's name. + std::string name; +}; + +/// @brief Sets or clears the default view of the user's own views. +struct SetDefaultView { + /// @brief The view's name; nothing clears the default. + std::optional name; +}; + +/// @brief Sets whether the default view's sort and filters apply at every mount. +struct SetDefaultOnMount { + /// @brief Whether they do. + bool on = false; +}; + +/// @brief One change to a views document. Its JSON is one member: `{"add": view}`, `{"replace": view}`, +/// `{"rename": {"from", "to"}}`, `{"remove": name}`, `{"default": name|null}` or `{"defaultOnMount": bool}`. +using ViewOperation = std::variant; + +/// @brief Why an operation does not apply to a views document. +enum class ViewError : std::uint8_t { + NameTaken, ///< An added or renamed view's name is another view's. + NoSuchView, ///< The operation names no view of the document. + NotShared, ///< A default, which the shared document does not have. +}; + +namespace detail { + +/// @brief A sort key as the state and views documents store it: `{"column", "direction"}`, where the wire says `dir`. +struct StoredSortKey { + /// @brief The column's id. + std::string column; + /// @brief The key's direction, `asc` or `desc`. + SortDirection direction = SortDirection::Ascending; +}; + +/// @brief A saved view as it is stored. +struct StoredView { + /// @brief The view's name. + std::string name; + /// @brief The column layout. + ColumnLayoutValue layout; + /// @brief The sort chain. + std::vector sort; + /// @brief The filters. + FilterSpec filters; +}; + +/// @brief A views document as it is stored. +struct StoredViews { + /// @brief The document's version. + int version = kViewsVersion; + /// @brief The default view's name, written as `default`. + std::optional defaultView; + /// @brief Whether the default view applies at every mount; absent from a shared document. + std::optional defaultOnMount; + /// @brief The views. + std::vector views; + + /// @brief The JSON member names: `defaultView` is `default`. + // NOLINTNEXTLINE(readability-identifier-naming): glaze looks the meta type up by this name. + struct glaze { + /// @brief The members. + static constexpr auto value = + glz::object("version", &StoredViews::version, "default", &StoredViews::defaultView, "defaultOnMount", + &StoredViews::defaultOnMount, "views", &StoredViews::views); + }; +}; + +/// @brief The version member alone, read before the rest. +struct ViewsVersion { + /// @brief The version; a document without one reads as 0. + int version = 0; +}; + +/// @brief Reads views documents and operations leniently: a member this version does not know is skipped. +inline constexpr glz::opts kViewsRead{.error_on_unknown_keys = false}; + +/// @brief @p view as it is stored. +/// @param view The view. +/// @return The stored shape. +[[nodiscard]] MORPH_API StoredView storedView(SavedView const& view); + +/// @brief A stored view as the framework holds it. +/// @param stored The stored shape. +/// @return The view. +[[nodiscard]] MORPH_API SavedView savedView(StoredView stored); + +/// @brief A views error: `InvalidSpec` with @p message. +/// @param message What is wrong. +/// @return The error. +[[nodiscard]] MORPH_API std::unexpected viewsError(std::string message); + +/// @brief @p value as JSON text. +/// @tparam T The value's type. +/// @param value The value. +/// @return Its JSON. +template +[[nodiscard]] std::string viewsJson(T const& value) { + return glz::write_json(value).value_or(std::string{}); +} + +/// @brief Reads @p text as a @p T. +/// @tparam T The type. +/// @param text The JSON text. +/// @param what What it is, for the message. +/// @return The value, or the error. +template +[[nodiscard]] std::expected readViewsJson(std::string_view text, std::string_view what) { + T value{}; + if (auto const error = glz::read(value, text); error) { + return viewsError(std::string{what} + " does not read: " + glz::format_error(error, text)); + } + return value; +} + +} // namespace detail + +/// @brief Reads a stored views document. +/// +/// No version before 1 exists, so a document of a lower version, or of none, is refused, as is one of a version above +/// `kViewsVersion`. A member this version does not know is skipped, and a view repeating an earlier view's name is +/// dropped, so names stay unique. +/// @param json The stored text. +/// @return The document; or `InvalidSpec` when the text is not JSON, or its version is not one this framework reads. +[[nodiscard]] MORPH_API std::expected readViews(std::string_view json); + +/// @brief Writes a views document at `kViewsVersion`. +/// @param document The document. +/// @param part `Shared` writes neither `default` nor `defaultOnMount`; `Own` writes `defaultOnMount` always and +/// `default` when one is set. +/// @return The JSON text. +[[nodiscard]] MORPH_API std::string writeViews(ViewsDocument const& document, ViewsPart part); + +/// @brief Writes one operation as its one-member JSON object. +/// @param operation The operation. +/// @return The JSON text. +[[nodiscard]] MORPH_API std::string writeViewOperation(ViewOperation const& operation); + +/// @brief Reads one operation from its one-member JSON object. +/// @param json The JSON text. +/// @return The operation; or `InvalidSpec` when the text is not one object of exactly one member this function knows, +/// or a view in it has no name. +[[nodiscard]] MORPH_API std::expected readViewOperation(std::string_view json); + +/// @brief Applies one operation to a views document. +/// @param document The document, as stored now. +/// @param operation The operation. +/// @param part Which document it is: a `Shared` one has no default. +/// @return The changed document; `NameTaken` for an `AddView` or `RenameView` onto another view's name, `NoSuchView` +/// for a `ReplaceView`, `RenameView`, `RemoveView` or `SetDefaultView` naming no view, `NotShared` for a +/// `SetDefaultView` or `SetDefaultOnMount` on a `Shared` document. Removing the default view clears the +/// default; renaming it renames the default. +[[nodiscard]] MORPH_API std::expected applyViewOperation(ViewsDocument document, + ViewOperation const& operation, + ViewsPart part); + +/// @brief Whether a store keeps the `shared` part for everyone. +enum class Sharing : std::uint8_t { + Private, ///< It does not: it offers no publishing. + Shared, ///< It does: `publish` applies operations to the `shared` part. +}; + +/// @brief Where every table stores and loads its state. Completions are delivered on an executor the store owns. +class MORPH_API ITableStateStore { +public: + ITableStateStore() = default; + ITableStateStore(ITableStateStore const&) = delete; + ITableStateStore& operator=(ITableStateStore const&) = delete; + ITableStateStore(ITableStateStore&&) = delete; + ITableStateStore& operator=(ITableStateStore&&) = delete; + virtual ~ITableStateStore() = default; + + /// @brief Reads a stored document. + /// @param key Which table's state, and which part. + /// @return The stored document, or nothing when none is stored. + [[nodiscard]] virtual async::Completion> load(TableStateKey const& key) = 0; + + /// @brief Stores @p json. With @p expected empty it replaces whatever is stored; with `kNoDocument` it stores only + /// when nothing is stored; otherwise it stores only when the stored document has that revision. + /// @param key Which table's state, and which part. + /// @param json The document. + /// @param expected The revision the caller loaded, `kNoDocument` when it loaded nothing, or empty. + /// @return `Saved` with the new revision; `Conflict` with the current revision when @p expected does not hold. + [[nodiscard]] virtual async::Completion save(TableStateKey const& key, std::string json, + std::string expected = {}) = 0; + + /// @brief Forgets a stored document. + /// @param key Which table's state, and which part. + /// @return Whether a document was stored. + [[nodiscard]] virtual async::Completion remove(TableStateKey const& key) = 0; + + /// @brief Whether the store keeps the `shared` part for everyone rather than for one person. + /// @return `false` unless a store overrides it. + [[nodiscard]] virtual bool shares() const { return false; } + + /// @brief Applies one operation to the `shared` part, under the `expected` rule of `save`. A store that does not + /// share answers `Refused`, "this store does not share views", as `refusePublish` does. + /// + /// Pure, so that every store says what it does: the interface owns no executor, and a completion is delivered on + /// the store's own. + /// @param key Which table's state; its `part` is `"shared"`. + /// @param operation The operation. + /// @param expected The revision the caller loaded, `kNoDocument` when it loaded nothing, or empty. + /// @return `Saved` with the new revision; `Conflict` with the current revision when @p expected does not hold; + /// `Refused` when the operation does not apply or the store does not share. + [[nodiscard]] virtual async::Completion publish(TableStateKey const& key, + ViewOperation const& operation, + std::string expected) = 0; + +protected: + /// @brief The answer of a store that does not share to `publish`: `Refused`, "this store does not share views". + /// @param executor Where the completion is delivered: the store's own. Borrowed: it must outlive the delivery. + /// @return The settled completion. + [[nodiscard]] static async::Completion refusePublish(exec::IExecutor& executor); +}; + +/// @brief Why @p error stops @p operation, in words a status line can show. +/// @param error The error. +/// @param operation The operation it stopped. +/// @return The text. +[[nodiscard]] MORPH_API std::string viewErrorText(ViewError error, ViewOperation const& operation); + +/// @brief A store that keeps every document in a map, for as long as it lives. +/// +/// Each call is a task on its own strand, and its completion is delivered there. Revisions are `"1"`, `"2"`, … +/// per key, counted across removals, so a revision never names two documents of one key. Built with +/// `Sharing::Shared` it keeps the `shared` part for everyone and `publish` applies operations to it; built with +/// `Sharing::Private`, the default, it offers no publishing. +class MORPH_API MemoryTableStateStore final : public ITableStateStore { +public: + /// @brief A store whose strand runs on @p executor. + /// @param executor Where the strand's tasks run and completions are delivered. Borrowed: it must outlive the + /// store. + /// @param sharing Whether it keeps the `shared` part for everyone. + explicit MemoryTableStateStore(exec::IExecutor& executor MORPH_LIFETIMEBOUND, Sharing sharing = Sharing::Private) + : _sharing{sharing}, _strand{executor} {} + + /// @brief Reads a stored document. + /// @param key Which table's state, and which part. + /// @return The stored document, or nothing when none is stored. + [[nodiscard]] async::Completion> load(TableStateKey const& key) override; + + /// @brief Stores @p json under the `expected` rule of `ITableStateStore::save`. + /// @param key Which table's state, and which part. + /// @param json The document. + /// @param expected The revision the caller loaded, `kNoDocument` when it loaded nothing, or empty. + /// @return `Saved` with the new revision, or `Conflict` with the current one. + [[nodiscard]] async::Completion save(TableStateKey const& key, std::string json, + std::string expected = {}) override; + + /// @brief Applies @p operation to the `shared` part under the `expected` rule of `save`, when the store shares. + /// @param key Which table's state; its `part` is `"shared"`. + /// @param operation The operation. + /// @param expected The revision the caller loaded, `kNoDocument` when it loaded nothing, or empty. + /// @return `Saved` with the new revision; `Conflict` with the current one; `Refused` over `Sharing::Private`, + /// for a key of another part, an operation that does not apply, or a stored document that does not read. + [[nodiscard]] async::Completion publish(TableStateKey const& key, ViewOperation const& operation, + std::string expected) override; + + /// @brief Forgets a stored document. + /// @param key Which table's state, and which part. + /// @return Whether a document was stored. + [[nodiscard]] async::Completion remove(TableStateKey const& key) override; + + /// @brief Whether the store keeps the `shared` part for everyone. + /// @return `true` when built with `Sharing::Shared`. + [[nodiscard]] bool shares() const override { return _sharing == Sharing::Shared; } + +private: + using Key = std::tuple; + using Documents = std::map; + + [[nodiscard]] static Key tie(TableStateKey const& key) { + return Key{key.application, key.model, key.table, key.qualifier, key.part}; + } + + /// The `Conflict` @p wanted answers over @p found, or nothing when it holds. + [[nodiscard]] std::optional conflictOf(Documents::const_iterator found, + std::string const& wanted) const; + + /// Stores @p text under @p entry when @p wanted holds; runs on the strand. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the text to store, then the text the entry is expected to hold. + [[nodiscard]] SaveResult store(Key const& entry, std::string text, std::string const& wanted); + + Sharing _sharing; + Documents _documents; + std::map _counts; + /// After the maps, so it is destroyed first: a task running on it reads them. + exec::OwnerStrand _strand; +}; + +/// @brief The version of the state document this framework writes. +inline constexpr int kStateVersion = 1; + +/// @brief Parts of a stored state that name a column or group the caller's description lacks. Not applied; merged +/// back by `writeState` into the places they had. +struct CarriedState { + /// @brief A column the description lacks, with what the layout held for it. + struct Column { + /// @brief The column's id. + std::string id; + /// @brief The id it followed in the stored `order`; empty when it was first. + std::string after; + /// @brief Whether it was hidden. + bool hidden = false; + /// @brief Its width, when one was set. + std::optional width; + /// @brief Its display units: dimension to unit id, as stored. + std::map units; + + /// @brief Member-wise equality. + /// @param other The column to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(Column const& other) const = default; + }; + /// @brief The columns, in stored order. + std::vector columns; + /// @brief Each sort key with its index in the stored chain. + std::vector> sort; + /// @brief Column filters, by the absent column's id. + std::map filters; + /// @brief Group filters naming an absent group or column. + std::vector groupFilters; + /// @brief User-formed groups that name an absent column, whole. + std::vector groups; + + /// @brief Member-wise equality. + /// @param other The carried state to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(CarriedState const& other) const = default; +}; + +/// @brief The `state` part of a table's persisted state: its arrangement in use. +struct StateDocument { + /// @brief The document's version. + int version = kStateVersion; + /// @brief The column layout, when one is stored. + std::optional layout; + /// @brief The sort chain, when one is stored. + std::optional sort; + /// @brief The filters, when any are stored. + std::optional filters; + /// @brief The saved view the arrangement was taken from. + std::optional view; + /// @brief What the caller's description lacks, written back as it was. + CarriedState carried; +}; + +/// @brief One entry `fitState` dropped. +struct FitDrop { + /// @brief What was dropped. + enum class What : std::uint8_t { + Column, ///< A layout column. + SortKey, ///< A sort key. + Filter, ///< A column filter. + GroupFilter, ///< A group filter. + Group, ///< A user-formed group. + Unit, ///< A display unit. + }; + /// @brief What was dropped. + What what = What::Column; + /// @brief The column or group; a user group's filter by its group's id; a filter over listed columns by them, + /// joined with `,`; a unit as `column/dimension`. + std::string id; + /// @brief `true`: kept in `carried`, the description lacking it; `false`: gone. + bool carried = false; + + /// @brief Member-wise equality. + /// @param other The drop to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(FitDrop const& other) const = default; +}; + +/// @brief What `fitState` dropped. +struct FitReport { + /// @brief The drops, in the order of the fitting list: columns, sort keys, filters, units, user groups with + /// their filters. + std::vector dropped; +}; + +namespace detail { + +/// @brief The state document as it is stored. +struct StoredState { + /// @brief The document's version. + int version = kStateVersion; + /// @brief The column layout. + std::optional layout; + /// @brief The sort chain. + std::optional> sort; + /// @brief The filters. + std::optional filters; + /// @brief The saved view's name. + std::optional view; +}; + +/// @brief The version member alone, read before the rest. +struct StateVersion { + /// @brief The version; a document without one reads as 0. + int version = 0; +}; + +/// @brief Reads state documents leniently: a member this version does not know is skipped. +inline constexpr glz::opts kStateRead{.error_on_unknown_keys = false}; + +/// @brief Whether @p description lists unit @p unit of dimension @p dimension: whether a stored display unit still +/// names a unit the table's measures may be shown in. +/// @param description The description. +/// @param dimension The dimension, such as `mass`. +/// @param unit The unit's id. +/// @return `true` when `description.units` holds a unit of that id and dimension. +[[nodiscard]] MORPH_API bool listsUnit(TableDescription const& description, std::string_view dimension, + std::string_view unit); + +/// @brief Whether @p a and @p b hold the same column ids, in any order. +/// @param left One list. +/// @param right The other. +/// @return `true` when they hold the same ids. +[[nodiscard]] MORPH_API bool sameColumns(std::vector left, std::vector right); + +/// @brief @p columns joined with `,`. +/// @param columns The ids. +/// @return The joined text. +[[nodiscard]] MORPH_API std::string joinedColumns(std::vector const& columns); + +} // namespace detail + +/// @brief Reads a stored state document, bringing an older version forward one version at a time. +/// +/// No version before 1 exists, so a document of a lower version, or of none, has no migration and is refused, as +/// is one of a version above `kStateVersion`. A member this version does not know is skipped. +/// @param json The stored text. +/// @return The document, its `carried` empty; or a message when the text is not JSON, or its version is not one +/// this framework reads. +[[nodiscard]] MORPH_API std::expected readState(std::string_view json); + +/// @brief Writes a state document at `kStateVersion`, its carried parts merged back into their places. +/// +/// A carried column goes into `order` right after its `after` id, first when `after` is empty, or at the end when +/// `after` is not in the written order, with its hidden flag, width and units; a carried sort key goes in at its +/// stored index, clamped to the chain's length; carried filters, group filters and groups are appended. `hidden` is +/// written in `order`'s order, then any hidden id `order` does not name, as listed. +/// @param document The document. +/// @return The JSON text. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] MORPH_API std::string writeState(StateDocument const& document); + +/// @brief Fits a stored state to the description the caller receives; the state is never refused. +/// +/// In the order of the fitting list: columns are fitted as `ColumnLayout::apply` fits them; a sort key on a +/// missing or unsortable column, or repeating an earlier key's column, is dropped; a filter on a missing column or +/// group, or one that does not compile for its columns, is dropped, and so is a display unit the description does +/// not list; a user-formed group left with fewer than two columns is dropped with its filter. A user group's +/// filter is the group filter with no `group` whose `columns` are the group's, in any order. +/// +/// What is dropped because the description lacks its column or group moves into `carried`; anything else is gone. +/// A user group that names an absent column is carried whole, with its filter. +/// @param document The stored state; its own `carried` is replaced. +/// @param description The caller's description. +/// @param report Receives every drop, appended in the order above. +/// @return The fitted document. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +[[nodiscard]] MORPH_API StateDocument fitState(StateDocument document, TableDescription const& description, + FitReport& report); + +} // namespace morph::table + +/// @cond detail +/// A save's outcome on the wire: `saved`, `conflict` or `refused`. +template <> +struct glz::meta { + using enum morph::table::SaveOutcome; + static constexpr auto value = glz::enumerate("saved", Saved, "conflict", Conflict, "refused", Refused); +}; +/// @endcond diff --git a/include/morph/table/view_cache.hpp b/include/morph/table/view_cache.hpp new file mode 100644 index 000000000..5cbdd579a --- /dev/null +++ b/include/morph/table/view_cache.hpp @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file table/view_cache.hpp +/// @brief The server's cache of computed views: the order and the undecided rows of a sort and filter, kept +/// while the rows and the order levels they were computed from are unchanged. +/// +/// Sorting and filtering many rows is the expensive part of a reply, and every page of a scroll, every keyed +/// fetch and every watcher refetching after an arrival asks for the same view. A `ViewCache` keeps one entry per +/// table record, scope and canonical sort and filter, valid while the source's snapshot has the identity the entry +/// was computed from and each order level the generation it read. Requests that need an entry being computed wait +/// for that one computation. +/// +/// See `docs/spec/table/table.md`, "The view cache". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table { + +/// @brief What names a cached view. +struct ViewKey { + /// @brief The table's record name, `.`. + std::string record; + /// @brief `ServedTable::scope`: what about the caller changes the rows or their order. + std::string scope; + /// @brief The canonical JSON of the validated query's `sort` and `filters`. + std::string query; + + /// @brief Member-wise ordering. + /// @param other The key to compare with. + /// @return The order of `(record, scope, query)`. + [[nodiscard]] auto operator<=>(ViewKey const& other) const = default; +}; + +/// @brief What a computation returns: the view, and the order levels it found unloaded or failed. +struct ViewComputation { + /// @brief The view. + detail::ComputedView view; + /// @brief The order levels unloaded for some row of the view or of the undecided rows. + std::vector awaiting; + /// @brief The order levels failed for some such row. + std::vector failed; + /// @brief The keys of the view's rows and of the undecided rows: what the query's order levels are wanted + /// for, kept with the view so that a repeated want is one a level can recognise. Null for a query with + /// no order level. + std::shared_ptr const> orderKeys; +}; + +/// @brief One cached view: what it was computed from, and the lookups a keyed query reads, built at its first. +/// +/// Held only by `std::shared_ptr`, never copied or moved. +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- source rows are below the snapshot's row count +class MORPH_API ViewEntry { +public: + /// @brief An entry of @p computation. + /// @param snapshotIn The rows the view was computed over. + /// @param levelsIn Each order level read, with the generation of its snapshot. + /// @param computation The view, `awaiting` and `failed`. + ViewEntry(std::shared_ptr snapshotIn, + std::vector> levelsIn, ViewComputation computation) + : snapshot{std::move(snapshotIn)}, + levels{std::move(levelsIn)}, + view{std::move(computation.view)}, + awaiting{std::move(computation.awaiting)}, + failed{std::move(computation.failed)}, + orderKeys{std::move(computation.orderKeys)}, + _orderKeyBytes{keysBytes(orderKeys.get())} {} + + ViewEntry(ViewEntry const&) = delete; + ViewEntry& operator=(ViewEntry const&) = delete; + ViewEntry(ViewEntry&&) = delete; + ViewEntry& operator=(ViewEntry&&) = delete; + /// @brief Frees the view and the lookups. + ~ViewEntry() = default; + + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes): the entry is a record of one + // computation, built whole and read by the cache's lookups; no member has an invariant of its own to guard. + + /// @brief The rows the view was computed over; held, so the address its identity names is not reused. + std::shared_ptr snapshot; + /// @brief Each order level the view read, with its snapshot's generation. + std::vector> levels; + /// @brief The view. + detail::ComputedView view; + /// @brief The order levels unloaded for some row of the view or of the undecided rows. + std::vector awaiting; + /// @brief The order levels failed for some such row. + std::vector failed; + /// @brief The keys of the view's rows and of the undecided rows, for the order levels' wants; null for a + /// query with no order level. + std::shared_ptr const> orderKeys; + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes) + + /// @brief The view row of each source row, `detail::kNotInView` for a row not in the view. + /// @return The table, built at the first call. + [[nodiscard]] std::span viewRowOf() const; + + /// @brief The source row of a key. + /// @param key The key. + /// @return The row, or nothing when the snapshot has no row with that key. + [[nodiscard]] std::optional sourceRowOf(RowId const& key) const; + + /// @brief What the entry holds. + /// @return 4 bytes a row of the view and of the undecided rows; the order keys, each by `rowIdBytes`, and + /// their vector's spare capacity; once the keyed lookups are built, 4 bytes a source row for the view + /// rows and one `(hash, row)` pair a source row for the key index. + [[nodiscard]] std::size_t bytes() const; + +private: + // Counted once: the keys never change after the entry is made. + [[nodiscard]] static std::size_t keysBytes(std::vector const* keys) noexcept; + + void build() const; + + mutable std::once_flag _once; + std::size_t _orderKeyBytes = 0; + mutable std::atomic _built{false}; + mutable std::vector _viewRowOf; + mutable std::vector> _byHash; +}; +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + +/// @brief The server's computed views, across its tables, bounded by `ViewCacheOptions::maxBytes`. +/// +/// Thread-safe. An entry is found under a mutex and computed outside it, on the calling thread; requests for the +/// same key, snapshot identity and order-level generations while it is computed wait for that computation. The +/// mutex is held for bookkeeping alone: an entry that leaves the cache is released after it. +/// +/// `ViewCacheOptions::maxBytes` bounds what the entries themselves hold (`ViewEntry::bytes`), not the snapshots +/// they keep alive: an entry over an old snapshot holds that snapshot's rows until the entry is evicted or found +/// invalid. +class MORPH_API ViewCache { +public: + /// @brief The result of a find. + using Found = std::expected, TableError>; + + /// @brief A cache bounded as @p options says. + /// @param options The bound and the computation hook. + explicit ViewCache(ViewCacheOptions options = {}) : _options{std::move(options)} {} + + /// @brief The entry of @p key valid for @p snapshot and @p levels, computing it when there is none. + /// + /// An entry whose snapshot has the identity of @p snapshot and whose every level generation equals + /// @p levels' is a hit. Any other entry of the key is dropped, unless the request is not at least as new as it + /// in every part (its @p newness and each order level's generation): such a request computes its view without + /// displacing the entry. A miss + /// joins a running computation of the same key, identity and generations, or computes on the calling thread, + /// calling `ViewCacheOptions::onCompute` first. A failed computation is not cached, and an entry replaces the + /// key's only when it is at least as new. Entries this call evicts or drops are released after the mutex is. + /// @param key The view's key. + /// @param snapshot The rows the view is of: the table's pinned source snapshot. + /// @param levels Each order level the query reads, with its snapshot's generation. + /// @param compute Computes the view over the request's snapshots. + /// @param newness How recently @p snapshot was taken, larger for later; 0 when unknown. + /// @return The entry, or what the computation refused. + [[nodiscard]] Found find(ViewKey const& key, std::shared_ptr const& snapshot, + std::span const> levels, + std::function()> const& compute, + std::uint64_t newness = 0); + + /// @brief The counters. + /// @return What the cache has done, and the bytes it holds. + [[nodiscard]] ViewCacheStats stats() const { + return ViewCacheStats{.hits = _hits.load(), + .misses = _misses.load(), + .computations = _computations.load(), + .waits = _waits.load(), + .evictions = _evictions.load(), + .invalidations = _invalidations.load(), + .bytes = _bytes.load()}; + } + +private: + struct Running { + ViewKey key; + void const* identity = nullptr; + std::vector> levels; + std::shared_ptr snapshot; + std::uint64_t newness = 0; + std::uint64_t order = 0; + std::promise promise; + std::shared_future done; + }; + + struct Slot { + std::shared_ptr entry; + std::uint64_t newness = 0; + std::uint64_t order = 0; + std::size_t bytes = 0; + std::list::iterator recency; + }; + + using Entries = std::map; + + // Ends @p running and caches its entry, unless the key's entry is newer: of a later snapshot, or of the same + // newness and a later computation. What leaves the cache is released after the mutex. + void finish(std::shared_ptr const& running, Found const& result); + + void remeasure(Slot& slot); + + // Whether (newness, levels) is at least (otherNewness, otherLevels) in every part: the rows were pinned no + // earlier, and no order level the other read is at an older generation. + [[nodiscard]] static bool atLeastAsNew(std::uint64_t newness, + std::vector> const& levels, + std::uint64_t otherNewness, + std::vector> const& otherLevels); + + // Under the mutex: removes an entry, moving it into @p released for the caller to free after the mutex. + void drop(Entries::iterator found, std::vector>& released); + + // Under the mutex: evicts the least recently used entries until the bound holds, into @p released. + void bound(std::vector>& released); + + ViewCacheOptions _options; + std::mutex _mutex; + Entries _entries; + std::list _recency; // most recent first + std::vector> _running; + std::uint64_t _started = 0; + std::size_t _held = 0; + std::atomic _hits{0}; + std::atomic _misses{0}; + std::atomic _computations{0}; + std::atomic _waits{0}; + std::atomic _evictions{0}; + std::atomic _invalidations{0}; + std::atomic _bytes{0}; +}; + +} // namespace morph::table diff --git a/include/morph/tui/backend.hpp b/include/morph/tui/backend.hpp index 6c0cc1625..dcb6cfdcf 100644 --- a/include/morph/tui/backend.hpp +++ b/include/morph/tui/backend.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "../attributes.hpp" #include "../ui/backend.hpp" @@ -127,6 +128,11 @@ class Backend final : public ui::IViewBackend { /// @copydoc ui::IViewBackend::setOnWidthClass void setOnWidthClass(std::function onWidthClass) override; + /// @brief Puts text on the clipboard through the terminal: an OSC 52 sequence written to the screen's output. + /// @param text The text, UTF-8. + /// @return True: the sequence was written; whether the terminal honours it cannot be known. + bool copyText(std::string_view text) override; + /// @brief Calls the width class listener when the screen's class differs from the one last reported; a frontend /// calls it after dispatching a resize, outside the draw, so the re-render comes on the next turn. void refreshWidthClass(); diff --git a/include/morph/ui/author.hpp b/include/morph/ui/author.hpp index e07ae8b53..45de73dbf 100644 --- a/include/morph/ui/author.hpp +++ b/include/morph/ui/author.hpp @@ -95,9 +95,16 @@ struct ActionFacts { [[nodiscard]] static std::vector secretFields() { return {}; } }; -/// @brief Satisfied when `Model` runs `Action`: the model has an `execute` that takes it. +/// @brief Satisfied when `Model` runs `Action`: the model has an `execute` that takes it, or the action runs itself +/// on the model through a static `invoke`, as a table's `Table.` and `Table..describe` do. template -concept Runs = requires(Model& model, Action& action) { model.execute(action); }; +concept Runs = requires(Model& model, Action& action) { model.execute(action); } || + ::morph::model::detail::DeclaresInvoke; + +/// @brief Satisfied when `Model` has an `execute` that takes `Action`: an action of the model's own, which an +/// `evaluate` or a `mutation` may name. A table's actions run themselves and only read, so they are not. +template +concept Executes = requires(Model& model, Action& action) { model.execute(action); }; namespace detail { @@ -175,7 +182,12 @@ template [[nodiscard]] inline std::vector recordsInfo(std::string_view actionId) { std::vector out; for (auto const& held : ::morph::effects::recordsOf(actionId)) { - out.push_back(ActionRecordInfo{.record = held.record, .keyField = held.keyField, .paths = held.paths}); + out.push_back(ActionRecordInfo{.record = held.record, + .keyField = held.keyField, + .paths = held.paths, + .open = held.open, + .partial = held.partial, + .opaque = held.opaque}); } return out; } @@ -226,16 +238,19 @@ struct CatalogFacts { void action() { model(); auto const actionId = std::string{::morph::model::ActionTraits::typeId()}; - actions.emplace(actionId, ActionInfo{ - .modelType = std::string{::morph::model::ModelTraits::typeId()}, - .calculatedFields = ActionFacts::calculatedFields(), - .secretFields = ActionFacts::secretFields(), - .credential = ActionFacts::credential, - .listFields = detail::listFields<::morph::model::HandlerResultT< - decltype(std::declval().execute(std::declval()))>>(), - .effects = detail::effectsInfo(actionId), - .records = detail::recordsInfo(actionId), - }); + actions.emplace( + actionId, + ActionInfo{ + .modelType = std::string{::morph::model::ModelTraits::typeId()}, + .calculatedFields = ActionFacts::calculatedFields(), + .secretFields = ActionFacts::secretFields(), + .credential = ActionFacts::credential, + .listFields = + detail::listFields<::morph::model::HandlerResultT(), std::declval()))>>(), + .effects = detail::effectsInfo(actionId), + .records = detail::recordsInfo(actionId), + }); } /// @brief The facts as a `ui::Catalog`. @@ -2378,7 +2393,7 @@ class DeclScope { /// @return The query's handle. Its value is the action body as the server reconciled it, computed fields /// filled, with `errors` and `ready` beside the fields. template - requires Runs + requires Executes QueryHandle evaluate(std::string const& name, ModelHandle const& model, Body const& body = {}, QueryOptions const& options = {}) { declareQuery(name, model.alias(), "evaluate", body, options); @@ -2393,7 +2408,7 @@ class DeclScope { /// @param options Its body, concurrency, optimistic write and command lists. /// @return The mutation's handle. template - requires Runs + requires Executes MutationHandle mutation(std::string const& name, ModelHandle const& model, MutationOptions const& options = {}) { Json decl = Json::object_t{}; @@ -4701,6 +4716,9 @@ struct TableColumn { /// instead of the table scrolling sideways, and gives up its width before the other stretch columns; /// writes `shrink: true`. It needs a stretch `width`. bool shrink = false; + /// @brief Whether a column with a `name` draws a filter button on its header and offers "Filter…" in its menu; + /// `false` writes `filterable: false`, for a column the design gives no filter. + bool filterable = true; }; /// @brief Columns from cells alone, without ids or labels. @@ -4833,6 +4851,9 @@ namespace detail { if (column.shrink) { detail::put(part, "shrink", true); } + if (!column.filterable) { + detail::put(part, "filterable", false); + } if (column.sortBy.present()) { detail::put(part, "sortBy", column.sortBy.json()); } diff --git a/include/morph/ui/backend.hpp b/include/morph/ui/backend.hpp index 7d5abc1a3..8e351cb35 100644 --- a/include/morph/ui/backend.hpp +++ b/include/morph/ui/backend.hpp @@ -1,12 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once +#include #include #include #include #include #include #include +#include #include #include #include @@ -85,7 +87,8 @@ class Widget { /// @brief Declares the keyboard chords the widget handles while focus is inside it. /// - /// A chord pressed while focus is inside several widgets that declare it goes to the innermost of them only. + /// A chord pressed while focus is inside several widgets that declare it goes to the innermost of them only. A + /// widget that declares `Tab` or `Shift+Tab` receives them instead of focus moving. /// @param chords The chords, each modifiers joined to a key name, such as `"Ctrl+S"`. /// @param onChord Called with the chord that was pressed. virtual void setKeys(std::vector const& chords, std::function onChord) = 0; @@ -372,33 +375,6 @@ class SelectWidget : public FieldWidget { virtual void setCaption(std::string_view label, bool shown) = 0; }; -/// @brief One entry of a menu as a `MenuWidget` shows it. -struct MenuEntry { - /// @brief The caption. - std::string label; - /// @brief The icon's name in the theme's icon map; empty shows none. - std::string icon; - /// @brief The chord shown beside the label; empty shows none. - std::string keys; - /// @brief Engaged: a checkable entry with this mark; `nullopt`: not checkable. - std::optional checked; - /// @brief Whether the entry can be chosen, or its submenu opened. - bool enabled = true; - /// @brief The submenu; empty for an entry that is chosen. - std::vector items; - /// @brief Whether the entry is a line between entries: never chosen, never opened, and its other fields empty. - bool separator = false; - /// @brief A muted line of help shown with the entry; empty shows none. - std::string description; - /// @brief Whether the entry is a label that is not a command: drawn as muted text, exposed as static text, never - /// chosen or opened. Its other fields are empty. - bool heading = false; - - /// @brief Memberwise equality, submenus included. - /// @return Whether every field matches. - bool operator==(MenuEntry const&) const = default; -}; - /// @brief The marker a button-style menu's trigger draws after its text, to say that it opens. enum class MenuCaret : std::uint8_t { None, ///< No marker. @@ -755,6 +731,55 @@ enum class RowClick : std::uint8_t { Range, ///< Shift+click: the rows from the anchor to this one are selected, in place of the rest. }; +/// @brief A backend's horizontal measure for a table's columns (`TableWidget::tableMeasure`). +struct TableMeasure { + /// @brief The backend's measure of one `Sizing` unit: a fixed column of `n` units is `n * unit` wide. + double unit = 1.0; + /// @brief The measure of one monospace character, the unit of a fixed column whose role is `TextRole::Mono`. + double monoUnit = 1.0; + /// @brief The width a column that declares none starts from, in the backend's measure, before its cells measure. + int contentEstimate = 100; + /// @brief What a column takes beyond its content, in the backend's measure: added to a fixed column's width and to + /// a width the user set, so a column is as wide windowed as unwindowed (a graphical backend's cell padding + /// on both sides, a terminal's gap after the column). + int padding = 0; + /// @brief The narrowest a stretch column with `shrink` goes, padding included: a column whose header is narrower + /// keeps its header. + int shrinkFloor = 8; +}; + +/// @brief What a backend measured of one table column (`TableWidget::setOnColumnMeasured`), in its own measure with +/// the +/// column's padding added. A width of 0 reports nothing of that kind. +struct ColumnMeasure { + /// @brief The width of the column's header: its label, and the marks and button it draws. + int header = 0; + /// @brief The width a shown cell asks for. + int natural = 0; + /// @brief The narrowest a shown cell is laid out without losing content: a text's widest word, else `natural`. + int least = 0; + + /// @brief Member-wise equality. + /// @param other The measure to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(ColumnMeasure const& other) const = default; +}; + +/// @brief A key that moves a table's focused cell, which the mount resolves over rows and columns it may not have +/// realized. +enum class FocusMove : std::uint8_t { + Up, ///< One row up. + Down, ///< One row down. + Left, ///< One visible column left. + Right, ///< One visible column right. + Home, ///< The row's first visible column. + End, ///< The row's last visible column. + First, ///< The view's first row (Ctrl+Home). + Last, ///< The view's last row, or the last row known under a lower bound (Ctrl+End). + PageUp, ///< Up by the rows in view. + PageDown, ///< Down by the rows in view. +}; + /// @brief Keyed rows under column headers, with selection and activation by key. /// /// Its children are the rows, each a horizontal stack whose children are the cells in column order. A hidden cell @@ -781,7 +806,9 @@ enum class RowClick : std::uint8_t { /// A range runs over the keys in row order, rows the backend has not realized included. class MORPH_API TableWidget : public ContainerWidget { public: - /// @brief Sets the column headers and widths. + /// @brief Sets the column headers and widths. A column's `unit` is drawn after its label, as `headerText` writes + /// it ("Mass [kg]") or on a second, muted line, and the header's accessible name is + /// `headerAccessibleName` ("Mass, kg"). /// @param columns The columns, in order. virtual void setColumns(std::vector const& columns) = 0; @@ -793,7 +820,8 @@ class MORPH_API TableWidget : public ContainerWidget { /// @param mode None, one, or any number. virtual void setSelectionMode(SelectionMode mode) = 0; - /// @brief Tells the table which key a row stands for; called once per row, right after it is built. Marks the row + /// @brief Tells the table which key a row stands for; called once per row, right after it is built, and again + /// when a table over a `TableSource` gives a row it holds to another key. Marks the row /// when its key is requested. /// @param row One of this table's rows. /// @param key The row's key. @@ -835,11 +863,20 @@ class MORPH_API TableWidget : public ContainerWidget { /// past the last row once a change settles), but a backend derives which cells are covered from the rows' /// current order when it lays out or paints, never here, and clips a span that runs past its last row or /// onto a heading row. A spanning cell is drawn once over the rows it covers, in its column, with the - /// look of this row; the covered rows' cells in that column are not shown. + /// look of this row; the covered rows' cells in that column are not shown. A span whose `columns` is above + /// 1 also covers that many visible columns from its own, its own included, in each row it covers; the + /// backend clips it at the last visible column. /// @param row One of this table's rows. /// @param spans The row's effective spans, by column, each column once. virtual void setRowSpans(Widget& row, std::vector const& spans) = 0; + /// @brief Makes a row a summary row; called once, right after `setRowKey`, for a summary row. It is drawn on the + /// theme's summary surface (`color.table.summary`), never selected, activated or focused for an edit, and + /// its cells are set as any row's. Pasting into it and copying it are the grid's. A row made a summary row + /// (or a heading) keeps that role for as long as it lives: the mount never gives it another key. + /// @param row One of this table's rows. + virtual void setRowSummary(Widget& row) { static_cast(row); } + /// @brief Requests the rows with these keys, and marks those it has. Never calls the `onSelectionChange` handler. /// @param keys The selected keys. virtual void setSelection(std::vector const& keys) = 0; @@ -853,25 +890,126 @@ class MORPH_API TableWidget : public ContainerWidget { /// @param onActivate The handler; empty does nothing. virtual void setOnActivate(std::function onActivate) = 0; - /// @brief Marks a column's header with the direction the rows are sorted by it, or marks none. The table never - /// reorders its rows: they arrive sorted. Never calls the `onSort` handler; the mount calls it only for a - /// table with a sortable column. - /// @param sort The column and direction, or none. - virtual void setSort(std::optional sort) = 0; + /// @brief Marks the headers of the sort chain's columns. Each draws its key's mark after its label + /// (`sortMarkText`: the direction, and with two or more keys its place from 1) and carries its accessible + /// description (`sortDescription`); a header not in the chain draws no mark and has no description. The + /// table never reorders its rows: they arrive sorted. Never calls the `onSort` handler; the mount calls it + /// only for a table with a sortable column. + /// @param chain The keys, most significant first; empty marks no header. + virtual void setSort(std::vector const& chain) = 0; /// @brief Sets what a user's request to sort calls: a click on a sortable column's header (or Enter or Space on /// it, where the header takes focus) calls it with the column's index among the columns `setColumns` gave, - /// which the select column is not one of. A header that is not sortable reports nothing. What the request + /// which the select column is not one of, and `HeaderClick::Plain`; a `Shift`+click, `Shift+Enter` or + /// `Shift+Space` with `HeaderClick::Shift`. A header that is not sortable reports nothing. What the request /// means is the caller's to decide; the backend only shows `setSort`. /// @param onSort The handler; empty does nothing. - virtual void setOnSort(std::function onSort) = 0; - - /// @brief Tells the backend how many of the table's rows are realized, where, and how many exist in total, so - /// it can size a scrollbar and place leading/trailing space for the rows that are not realized. A - /// backend that never virtualizes (the default for every implementer but a windowed Qt Quick table) - /// never calls `setOnVisibleRangeChanged`, so this is never called either. - /// @param first The view index of the first realized row. - /// @param count How many rows are realized, starting at `first`. + virtual void setOnSort(std::function onSort) = 0; + + /// @brief Gives the headers and the table their menus. A header's menu opens on a right click on it, or on + /// `Shift+F10` or the context-menu key with it focused; the table's menu from a `⋯` button at the header + /// row's trailing end, whose accessible name is `Table options`. The entries are asked for each time a menu + /// opens. Called only for a table that has menus; a table never told this draws no `⋯` and opens none. + /// @param entries The entries of a column's menu (an index into the columns `setColumns` gave), or of the + /// table's menu (none). + /// @param onChoose Called with the menu's column, or none, and the chosen entry's path, an index per level from + /// the top; never for a separator, a heading, a disabled entry or one with a submenu. + virtual void setMenu( + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `entries` by value to move it into their widget, and an override must match this signature; the default only discards it + std::function(std::optional)> entries, + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onChoose` by value to move it into their widget, and an override must match this signature; the default only discards it + std::function, std::vector)> onChoose) { + static_cast(entries); + static_cast(onChoose); + } + + /// @brief Gives the cells their menu. A right click, a long press, or `Shift+F10` or the context-menu key on the + /// focused cell opens it on that cell: the backend first makes the cell's row the selection alone, reported + /// as `Replace`, when the row is not selected already (a row already selected keeps the selection as it + /// is), then asks for the entries, which focuses the cell when it is not focused, and shows them at the + /// cell. While the table has the focus, a key the table does not take itself that is one of the chords + /// `setCellMenuKeys` gave asks for the focused cell's entries and is matched against their `keys` at every + /// level: the first enabled entry without a submenu whose chord it is runs, as if chosen from the menu, and + /// the key stops there. Any other key never asks for the entries. + /// @param entries The entries of a cell's menu, given its row's key and its column (an index into the columns + /// `setColumns` gave); asked for each time the menu opens or a key is matched. + /// @param chosen Called with the cell's row and column and the chosen entry's path, an index per level from the + /// top; never for a separator, a heading, a disabled entry or one with a submenu. + virtual void setCellMenu( + std::function(Key const& row, std::size_t column)> entries, + std::function const& path)> chosen) = 0; + + /// @brief The chords the cell menu's entries may declare, the only keys that ask for the focused cell's entries + /// (`setCellMenu`). Called for a table with a cell menu, once it is built; a table never told this runs no + /// entry from a key. + /// @param chords The chords, as an entry's `keys` writes them. + virtual void setCellMenuKeys(std::vector const& chords) { static_cast(chords); } + + /// @brief Tells the backend which columns are visible, in their places, so that a move and a group header count + /// places as the arrangement does. Called for a table over a `TableSource` once it is built and whenever + /// its visible columns change; a table never told this shows every column in its own order. + /// @param visible Indices into the columns `setColumns` gave, in layout order. + virtual void setVisibleColumns(std::vector const& visible) { static_cast(visible); } + + /// @brief Sets what moving a column calls: dragging a header onto another, or `Ctrl+Shift+Left` and + /// `Ctrl+Shift+Right` on a focused header, with the column and its new place among the visible columns + /// (one less, or one more, for the keys). A move to the place the column holds, or past either end, + /// reports nothing. + /// @param handler The handler; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `handler` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnColumnMove(std::function handler) { + static_cast(handler); + } + + /// @brief Sets what dragging a header's trailing edge calls, with the column and its new width in `Sizing` units + /// (`tableMeasure`'s unit), or none for a double click on the edge. Called only for a table whose columns + /// can be resized; a backend that draws no edge to drag ignores it. + /// @param handler The handler; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `handler` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnColumnResize(std::function units)> handler) { + static_cast(handler); + } + + /// @brief Sets what a filterable column's filter button calls, with the column. + /// @param handler The handler; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `handler` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnFilter(std::function handler) { static_cast(handler); } + + /// @brief Fills the filter buttons of the columns that have a filter, and names their headers "{label}, + /// filtered" for assistive technology; every other filterable column's button is drawn empty. + /// @param columns Indices into the columns `setColumns` gave. + virtual void setFiltered(std::vector const& columns) { static_cast(columns); } + + /// @brief Draws a group header row over the groups' columns, each group's caption over the visible places it + /// names, with its own filter button, filled while it is `filtered`; an empty list draws no group row. + /// @param groups The groups, in order. + virtual void setColumnGroups(std::vector const& groups) { static_cast(groups); } + + /// @brief Draws the header bands above the column headers (and above a group row): each run over the visible + /// columns it names, at its level, its label followed by its unit in brackets when it has one; an empty + /// list draws none. Called once at mount and again whenever the runs change, as the column window or the + /// layout moves. + /// @param runs The runs, outermost level first, each level left to right. + virtual void setBands(std::vector const& runs) { static_cast(runs); } + + /// @brief Sets what a group's filter button calls, with the group's index among those `setColumnGroups` gave. + /// @param handler The handler; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `handler` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnGroupFilter(std::function handler) { static_cast(handler); } + + /// @brief Sets what `Ctrl+C` on the focused table calls. + /// @param onCopy The handler; empty lets the key go on. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onCopy` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnCopy(std::function onCopy) { static_cast(onCopy); } + + /// @brief Tells the backend which contiguous range of view rows is realized and how many rows exist in total, so + /// it can size a scrollbar and place leading/trailing space for the rows that are not realized. Called + /// after each pass for every table over a `TableSource` (one that realizes every row with the whole view, + /// `(0, count, count)`), and for a table over `rows` at or above its `Virtualization::threshold`, whether + /// or not the backend reports a range. The focused row a source table keeps realized beyond the range is + /// not counted: `setRowIndex` places it. + /// @param first The view index of the first row of the range. + /// @param count How many rows the range holds, from `first`. /// @param total How many rows the table's data has, realized or not. virtual void setRealizedWindow(std::size_t first, std::size_t count, std::size_t total); @@ -894,6 +1032,280 @@ class MORPH_API TableWidget : public ContainerWidget { /// @param keys Every key currently in the table's data, in row order, so a range or Ctrl+A covers the rows the /// backend has not realized. virtual void setExistingKeys(std::vector const& keys) { static_cast(keys); } + + /// @brief Sets what a `Multiple` table's `Ctrl+A` calls in place of selecting the rows the backend holds and + /// reporting them: the caller selects the whole view, and sets the selection back through `setSelection`. + /// A backend that does not take it selects as before. + /// @param onSelectAll The handler; empty to select as before. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onSelectAll` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnSelectAll(std::function onSelectAll) { static_cast(onSelectAll); } + + /// @brief Marks every row of the table selected but those whose key is in @p except, rows the backend does not + /// hold included, until the next `setSelection`. In that state a `Ctrl`+click reports `Extend` with the + /// keys now selected among the rows the backend holds, so the caller reads each held key absent from the + /// report as left out and each present one as selected again; a plain click reports `Replace` and ends the + /// state. A backend that takes `setOnSelectAll` must take this too: the caller selects the view through it, + /// and a backend that kept drawing its key selection would report every other shown row as left out. + /// @param except The keys left out of the selection. + virtual void setSelectionView(std::vector const& except) { static_cast(except); } + + /// @brief Sets what choosing one of the status line's entries (`TableStatus::entries` and `standingEntries`, each + /// drawn as a button with its label) calls, with the entry's id. + /// @param onStatusEntry The handler; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onStatusEntry` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnStatusEntry(std::function onStatusEntry) { + static_cast(onStatusEntry); + } + + /// @brief Sets a row's marks; called after `setRowKey` for a row whose look carries marks, and on every change. + /// An `unmatched` row draws muted, a `busy` one with the busy mark, a `locked` one with the locked mark, + /// and `tooltip` is the row's tooltip; `RowMarks{}` draws an unmarked row. A backend that marks no row + /// ignores it. + /// @param row One of this table's rows. + /// @param marks The marks. + virtual void setRowMarks(Widget& row, RowMarks const& marks) { + static_cast(row); + static_cast(marks); + } + + /// @brief Shows the table's status line: its counts, the state of a failed fetch or level with "Retry" when it + /// offers it, and the latest message; a status that is not `shown` takes no space. Called once the table + /// is built and on every change. A backend without a status line ignores it. + /// @param status The status line. + virtual void setStatus(TableStatus const& status) { static_cast(status); } + + /// @brief Sets what choosing the status line's "Retry" calls. + /// @param onRetry The handler; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onRetry` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnRetry(std::function onRetry) { static_cast(onRetry); } + + /// @brief Sets a cell's load state; called after the row's key, and on every change, for a table whose rows come + /// from a `TableSource`. `Unloaded` draws a placeholder of a fixed width in the column's alignment and + /// `Failed` an error mark of the same width, over the cell's own content; neither widens the column. + /// A cell no call names is `Loaded`. + /// @param row One of this table's rows. + /// @param column The cell's column: an index into the columns `setColumns` gave. + /// @param load The state. + virtual void setCellLoad(Widget& row, std::size_t column, CellLoad load) { + static_cast(row); + static_cast(column); + static_cast(load); + } + + /// @brief Sets what a cell shows beside its text; called after the row's key, on every change, and whenever a + /// cell is attached to a row at a column, for a table whose rows come from a `TableSource`. A `tone` tints + /// the cell with the theme's tone surface under its selection and focus marks; a `tooltip` shows on hover + /// after the theme's delay and on keyboard focus at once, is the cell's accessible description, and draws + /// the theme's "more here" mark; `invalid` draws the theme's error mark in place of the cell's text. A + /// cell no call names has no accent. + /// @param row One of this table's rows. + /// @param column The cell's column: an index into the columns `setColumns` gave. + /// @param accent The accent. + virtual void setCellAccent(Widget& row, std::size_t column, CellAccent const& accent) { + static_cast(row); + static_cast(column); + static_cast(accent); + } + + /// @brief Tells the backend which columns the mount realizes, for a table whose rows come from a `TableSource` + /// and whose columns the mount lays out: once the backend reported its horizontal viewport, or the + /// arrangement is not the default. The header shows these columns only, each at its offset and width; the + /// first @p pinned stay in view whatever the horizontal scroll. Called again whenever any of it changes. + /// @param columns Indices into the columns `setColumns` gave: the pinned ones first, then the scrolled range. + /// @param offsets Each column's offset from the table's left edge, as if every visible column were laid out, + /// in the backend's measure (`tableMeasure`). + /// @param widths Each column's width, in the backend's measure. + /// @param totalWidth The width of every visible column together, in the backend's measure, which sizes the + /// horizontal scroll bar. + /// @param pinned How many of @p columns are pinned. + virtual void setColumnWindow( + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `offsets` and `widths` are the window's two parallel int spans, and the mount builds both with `columns` from one window and passes them in this order + std::span columns, std::span offsets, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `totalWidth` is a width and `pinned` a column count; the one call site in the mount passes the extents' total first, then the pinned count + std::span widths, int totalWidth, std::size_t pinned) { + static_cast(columns); + static_cast(offsets); + static_cast(widths); + static_cast(totalWidth); + static_cast(pinned); + } + + /// @brief Sets what the backend calls when its horizontal scroll or viewport changes, so the mount can window the + /// columns. A backend that never calls it gets every visible column realized. + /// @param handler The handler, with the scroll offset and the viewport's width, both in the backend's measure + /// (`tableMeasure`); empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `handler` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnHorizontalRange(std::function handler) { + static_cast(handler); + } + + /// @brief Moves the horizontal scroll offset without reporting it back: the mount keeps the columns in view where + /// they were when a column left of them grew. + /// @param scrollX The offset, in the backend's measure. + virtual void setHorizontalOffset(int scrollX) { static_cast(scrollX); } + + /// @brief Sets what the backend calls for a range gesture (Shift+click, Shift+arrow) over rows it does not hold + /// keys for, instead of resolving the range itself. + /// @param handler The handler, with the view rows of the range's anchor and end, and the kind of change; empty + /// does nothing. + virtual void setOnSelectRange( + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `handler` by value to move it into their widget, and an override must match this signature; the default only discards it + std::function handler) { + static_cast(handler); + } + + /// @brief Shows keyboard focus on a cell, and announces it; a row not fetched yet is announced as loading. + /// @param viewRow The cell's view row. + /// @param column The cell's column: an index into the columns `setColumns` gave. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`viewRow`, `column`): the row position then the column, the pair every table seam in this header passes in this order + virtual void setFocusCell(std::size_t viewRow, std::size_t column) { + static_cast(viewRow); + static_cast(column); + } + + /// @brief Sets what the backend calls with the widths a column's header and cells measured, so the mount can grow + /// a + /// content column and fit the stretch columns to the table. A report only ever adds to what the mount + /// knows: it keeps the largest of each width reported. + /// @param handler The handler, with the column (an index into the columns `setColumns` gave) and what was + /// measured, + /// in the backend's measure (`tableMeasure`), padding included; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `handler` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnColumnMeasured(std::function handler) { + static_cast(handler); + } + + /// @brief Sets what the backend calls for a key that moves the focused cell, which the mount resolves over rows + /// and columns it may not have realized. + /// @param handler The handler, with the move; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `handler` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnFocusMove(std::function handler) { static_cast(handler); } + + /// @brief Sets what printable text typed while a cell has focus and no editor is open calls, with the text. + /// @param onText The handler; empty does nothing and lets the key go on. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onText` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnText(std::function onText) { static_cast(onText); } + + /// @brief Sets what a click on a cell calls: a single click with `false`, the second click of a double click with + /// `true` (its first click calls it with `false`, as a single click does). + /// @param onClick The handler, with the cell's view row and its column (an index into the columns `setColumns` + /// gave); empty does nothing. + virtual void setOnCellClick( + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onClick` by value to move it into their widget, and an override must match this signature; the default only discards it + std::function onClick) { + static_cast(onClick); + } + + /// @brief Sets what focus moving to a widget outside the table, its cell editor and its popups calls. + /// @param onFocusOut The handler; empty does nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onFocusOut` by value to move it into their widget, and an override must match this signature; the default only discards it + virtual void setOnFocusOut(std::function onFocusOut) { static_cast(onFocusOut); } + + /// @brief Draws a cell editor over a cell's area in place of the cell's content, or the cell again. + /// @param row One of this table's rows; @p editor is one of its children. + /// @param column The cell's column: an index into the columns `setColumns` gave. + /// @param editor The editor, or null to draw the cell again. + virtual void setCellEditor(Widget& row, std::size_t column, Widget* editor) { + static_cast(row); + static_cast(column); + static_cast(editor); + } + + /// @brief Draws a rectangle of selected cells in place of a row selection, or none. Never calls the handler + /// `setOnCellSelect` gave. + /// @param rect `{firstRow, rowCount, firstPosition, positionCount}`: view rows, and places among the visible + /// columns + /// in layout order (a rectangle is of the layout, so these are positions, not indices into the columns + /// `setColumns` gave); empty draws none. + virtual void setCellSelection(std::optional> rect) { static_cast(rect); } + + /// @brief Makes the table select cells, not rows: it draws no row selection and reports no `onSelectionChange`. + /// It calls the handler with the rectangle a drag from cell to cell or a `Shift`+click selects, a row + /// header's click (anchor `(row, 0)`, focus `(row, last position)`) and a column header's selection gesture + /// (anchor + /// `(0, position)`, focus `(last row, position)`). `Shift` with an arrow and `Ctrl+A` are the table's own + /// chords, declared with `setKeys`, not the backend's. + /// @param onSelect The handler, with the anchor's and the focus's view rows and visible positions; empty selects + /// rows again. + virtual void setOnCellSelect( + std::function + // NOLINTNEXTLINE(performance-unnecessary-value-param): overrides take `onSelect` by value to move it into their widget, and an override must match this signature; the default only discards it + onSelect) { + static_cast(onSelect); + } + + /// @brief Sets a cell's marks; called after the row's key, on every change, and whenever a cell is attached to a + /// row at a column, for a table whose rows come from a `TableSource`. `readOnly` draws the theme's + /// read-only cell surface, `modified` the modified mark, `error` the error mark, `stale` and `muted` the + /// stale and muted looks. A cell no call names has no marks. + /// @param row One of this table's rows. + /// @param column The cell's column: an index into the columns `setColumns` gave. + /// @param marks The marks. + virtual void setCellMarks(Widget& row, std::size_t column, CellMarks const& marks) { + static_cast(row); + static_cast(column); + static_cast(marks); + } + + /// @brief Sets whether a row draws the row header's modified mark; called after `setRowKey` for a row whose look + /// carries it, and on every change. + /// @param row One of this table's rows. + /// @param modified Whether a cell of the row changed since the record was loaded. + virtual void setRowModified(Widget& row, bool modified) { + static_cast(row); + static_cast(modified); + } + + /// @brief Tells the backend the counts it reports to assistive technology. + /// @param rows The view's total when it is exact; nothing when it is a lower bound or not known yet. + /// @param columns The visible columns. + virtual void setCounts(std::optional rows, std::size_t columns) { + static_cast(rows); + static_cast(columns); + } + + /// @brief Scrolls a view row into view. + /// @param viewRow The row. + virtual void scrollToRow(std::size_t viewRow) { static_cast(viewRow); } + + /// @brief Marks one row as the one a linked view highlights, or none; neither selection nor focus. + /// @param viewRow The row's view index; nothing clears the mark. + virtual void setHighlightedRow(std::optional viewRow) { static_cast(viewRow); } + + /// @brief Places a cell of a row in a column, for a table whose rows come from a `TableSource`: called when a cell + /// joins its row's cells and when a pooled cell is given another column, and with nothing when the cell + /// leaves the column window or waits for its turn to be bound. A cell with no column is pooled: it is not + /// drawn and takes no place, and the column it left draws blank at its width until a cell is placed + /// there. + /// @param row One of this table's rows. + /// @param cell One of @p row's children. + /// @param column An index into the columns `setColumns` gave, or nothing. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`row`, `cell`): the table's realized row then its child cell, which both call sites in the mount pass in that order + virtual void setCellColumn(Widget& row, Widget& cell, std::optional column) { + static_cast(row); + static_cast(cell); + static_cast(column); + } + + /// @brief Tells the backend a realized row's view index, for a table whose rows come from a `TableSource`: called + /// for a row once it is realized and whenever its index changes. The realized rows are the children in + /// view order, but not always contiguous: the focused row stays realized beyond `setRealizedWindow`'s + /// range, so a backend places each row by its index, not by its position among the children. + /// @param row One of this table's rows. + /// @param viewRow The row's view index. + virtual void setRowIndex(Widget& row, std::size_t viewRow) { + static_cast(row); + static_cast(viewRow); + } + + /// @brief How this backend measures a table's widths, for a table whose rows come from a `TableSource`. The + /// horizontal scroll and viewport it reports, the widths it measures and the offsets and widths + /// `setColumnWindow` gives it are all in its own measure (pixels for a graphical backend, cells for a + /// terminal); the mount turns a column's `Sizing::fixed` amount, and a width the user set, into that + /// measure with these factors. The default measure is one per unit, with a content column estimated at 100. + /// @return The measure. + [[nodiscard]] virtual TableMeasure tableMeasure() const { return {}; } }; /// @brief A date or date-and-time field, in the mode and display zone fixed at creation. @@ -1573,6 +1985,20 @@ class MORPH_API IViewBackend { /// `widthClass()` for the current class. /// @param onWidthClass The listener, given the new class; empty clears it. virtual void setOnWidthClass(std::function onWidthClass) = 0; + + /// @brief Puts text on the system clipboard: Qt Quick's clipboard, the terminal's through an OSC 52 sequence. + /// A backend without a clipboard keeps this default. + /// @param text The text, UTF-8. + /// @return Whether the text was handed to the clipboard. + virtual bool copyText(std::string_view text) { + static_cast(text); + return false; + } + + /// @brief Reads the system clipboard's text, what a grid's paste writes into its cells. A backend that cannot + /// read a clipboard keeps this default. + /// @return The text, UTF-8; nothing when there is no clipboard or it holds no text. + [[nodiscard]] virtual std::optional pasteText() { return std::nullopt; } }; /// @brief The width, in units, from which a surface is `expanded`: the compact bound, 80, plus the shell's sidebar diff --git a/include/morph/ui/bundle.hpp b/include/morph/ui/bundle.hpp index 243123eda..ca4fba34f 100644 --- a/include/morph/ui/bundle.hpp +++ b/include/morph/ui/bundle.hpp @@ -409,6 +409,23 @@ namespace detail { return std::nullopt; } +/// @brief Words joined by single spaces, for a refusal's reason. +/// @param words The words. +/// @return The words, space separated. Built by appending: concatenating `std::string{}` temporaries with `+` makes +/// GCC at -O3 report a `-Wrestrict` overlap inside the standard library that cannot happen. +[[nodiscard]] inline std::string joinedLabel(std::initializer_list words) { + std::string joined; + bool first = true; + for (std::string_view const word : words) { + if (!first) { + joined += ' '; + } + first = false; + joined += word; + } + return joined; +} + /// @brief The must-understand keys of a message: its top level, every element of its listed arrays and every value /// of its listed maps. /// @param root The parsed message. @@ -434,7 +451,7 @@ namespace detail { continue; } for (Json const& item : *items) { - if (auto reason = mustUnderstand(item, std::string{what} + " " + std::string{key})) { + if (auto reason = mustUnderstand(item, joinedLabel({what, key}))) { return reason; } } @@ -446,7 +463,7 @@ namespace detail { continue; } for (auto const& [name, item] : *items) { - if (auto reason = mustUnderstand(item, std::string{what} + " " + std::string{key} + " " + name)) { + if (auto reason = mustUnderstand(item, joinedLabel({what, key, name}))) { return reason; } } diff --git a/include/morph/ui/cell_format.hpp b/include/morph/ui/cell_format.hpp new file mode 100644 index 000000000..202ed3bdf --- /dev/null +++ b/include/morph/ui/cell_format.hpp @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file ui/cell_format.hpp +/// @brief How a table column shows its cells: the one formatter every backend, the copy, the status line and the +/// filter menu call. +/// +/// A cell crosses the wire as its exact value; the client turns it into text here, in the session's locale, by the +/// column's `table::ColumnDisplay`. Order, filters and distinct values always use the exact value, never this text. +/// +/// See `docs/spec/table/table.md`, "How a column shows its cells" and "Values with units". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +/// @brief How a cell draws, beside its text. +enum class CellLook : std::uint8_t { + Text, ///< The cell's text: its value's, or a label's. + Empty, ///< An empty cell: the column's `empty` text. + Unloaded, ///< A value that has not arrived: the backend draws its placeholder, and the text is empty. + Invalid, ///< A value that cannot be read as the column's kind: an error mark, and the text is empty. +}; + +/// @brief What a `Measure` cell is shown through, which the column alone does not carry. +struct DisplayUnits { + /// @brief The table's units, not owned; null shows every `Measure` cell as `Invalid`. + table::UnitRegistry const* units = nullptr; + /// @brief Per dimension, the unit id the user chose to show it in; a dimension not named shows each cell in its + /// own unit. + std::map> byDimension; +}; + +namespace detail::cells { + +/// @brief A number as canonical decimal text, split: its sign, its whole digits and its fraction digits. +struct Digits { + /// @brief Whether the number is below zero. + bool negative = false; + /// @brief The digits before the point; at least one. + std::string whole; + /// @brief The digits after the point; empty for none. + std::string fraction; +}; + +/// @brief Reads canonical `-?digits(.digits)?` text. +/// @param text The text. +/// @return The parts; nothing for text of another shape. +[[nodiscard]] MORPH_API std::optional digitsOf(std::string_view text); + +/// @brief Canonical text of @p digits: no sign on a value whose digits are all zero. +/// @param digits The parts. +/// @return The text. +[[nodiscard]] MORPH_API std::string textOf(Digits const& digits); + +/// @brief Rounds canonical text to @p places fraction digits, then pads or trims it. +/// +/// The dropped tail decides: above half rounds the magnitude up, below keeps it, and exactly half rounds up under +/// `HalfUp` and to the even last kept digit under `HalfEven`. With @p pad the fraction is padded to @p places; +/// without, trailing zeros and a bare point go. +/// @param digits The number. +/// @param places The places kept. +/// @param rounding The rule for a half. +/// @param pad Whether fewer places are padded with zeros. +/// @return The canonical text. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): the rounding decision reads the dropped tail, the half cases of each Rounding mode and the pad rule in sequence, each step needing the digits the one before left +[[nodiscard]] MORPH_API std::string roundText(Digits digits, std::size_t places, table::Rounding rounding, bool pad); + +/// @brief The exact digits of a `Rational` whose value has at most @p places fraction digits. +/// @param value The value; the caller rounded it to @p places. +/// @param places The fraction digits written. +/// @return The canonical text, every one of @p places written. +[[nodiscard]] MORPH_API std::string exactText(math::Rational const& value, std::uint32_t places); + +/// @brief The rounding mode of the arithmetic for a column's rule. +/// @param rounding The column's rule. +/// @return The mode. +[[nodiscard]] constexpr math::RoundingMode modeOf(table::Rounding rounding) noexcept { + return rounding == table::Rounding::HalfUp ? math::RoundingMode::HalfAwayFromZero : math::RoundingMode::HalfEven; +} + +/// @brief A `double`'s shortest round-trip text in fixed notation. +/// @param value The number. +/// @return The text; nothing for a value that is not finite. +[[nodiscard]] MORPH_API std::optional doubleText(double value); + +/// @brief Whether @p kind's cells are numbers a column's `decimals` applies to. +/// @param kind The kind. +/// @return `true` for `Integer`, `Decimal`, `Quantity` and `Number`. +[[nodiscard]] constexpr bool numeric(table::ColumnKind kind) noexcept { + using table::ColumnKind; + return kind == ColumnKind::Integer || kind == ColumnKind::Decimal || kind == ColumnKind::Quantity || + kind == ColumnKind::Number; +} + +/// @brief A text cell of a column whose kind is not text, read for the kind. +/// @param text The text. +/// @param kind The column's kind. +/// @return The value it reads as, the text itself for a text kind, or nothing for text that does not read. +[[nodiscard]] MORPH_API std::optional readText(std::string const& text, table::ColumnKind kind); + +/// @brief A cell as its column reads it: a text cell of a non-text column read for the kind. +/// @param cell The cell. +/// @param kind The column's kind. +/// @return The cell to show; nothing when its text does not read. +[[nodiscard]] MORPH_API std::optional normalized(table::Cell const& cell, table::ColumnKind kind); + +/// @brief A number cell's value as canonical text at the column's display, before the locale writes it. +/// @param cell The cell: an `int64`, a `Rational`, a `double` or a `QuantityCell`. +/// @param display The column's display. +/// @return The canonical text; nothing when the value cannot be shown (an overflow, a non-finite number). +[[nodiscard]] MORPH_API std::optional numberText(table::Cell const& cell, + table::ColumnDisplay const& display); + +/// @brief A measure in the unit it is shown in, as canonical text and the unit's symbol. +/// @param measure The cell. +/// @param units The table's units. +/// @return The number and the symbol; nothing for an unknown unit, no registry, or a conversion that overflows. +[[nodiscard]] MORPH_API std::optional> measureText(table::Measure const& measure, + DisplayUnits const& units); + +/// @brief Days since 1970-01-01, or UTC seconds shifted to the display zone, as text in the column's pattern. +/// @param value The days or the seconds. +/// @param column The column: its kind and its pattern. +/// @param locale The session's formatting: its patterns and the display zone. +/// @return The text; the number's own digits outside the years 0 to 9999. +[[nodiscard]] MORPH_API std::string dateText(std::int64_t value, table::TableColumn const& column, + FormatContext const& locale); + +/// @brief Whether a label's operand names @p operand: by value for a `Decimal` or `Number` column, so `"3"` names +/// 3.0; by text otherwise. +/// @param label The label's operand. +/// @param operand The cell's operand. +/// @param kind The column's kind. +/// @return `true` when they name the same value. +[[nodiscard]] MORPH_API bool sameOperand(std::string_view label, std::string_view operand, table::ColumnKind kind); + +} // namespace detail::cells + +/// @brief How a cell draws beside its text: empty, unloaded, invalid, or a text. +/// @param cell The cell. +/// @param column Its column. +/// @param units What a `Measure` cell is shown through. +/// @return `Unloaded` for an unloaded cell, `Empty` for an empty one, `Invalid` for text a non-text column cannot +/// read, a `Measure` with no registry or an unknown unit, and a number that cannot be shown; else `Text`. +[[nodiscard]] MORPH_API CellLook cellLook(table::Cell const& cell, table::TableColumn const& column, + DisplayUnits const& units = {}); + +/// @brief A cell's value as a filter entry takes it. +/// @param cell The cell. +/// @param column Its column. +/// @param units What a `Measure` cell's unit is named through. +/// @return An integer's digits, a `Rational` at its own places, a `double`'s shortest round-trip text, `"true"` or +/// `"false"`, text as it is, a quantity's canonical amount, a measure's amount, a space and its unit's id; +/// nothing for an empty, an unloaded or an invalid cell. +[[nodiscard]] MORPH_API std::optional operandOf(table::Cell const& cell, table::TableColumn const& column, + DisplayUnits const& units = {}); + +/// @brief The cell an operand names in @p column: `operandOf`'s inverse for the column's kind. +/// @param operand The operand. +/// @param column The column. +/// @param units What a `Measure` operand's unit id is found in. +/// @return The cell; the operand as text when it does not read as the kind, which shows as `Invalid`. +[[nodiscard]] MORPH_API table::Cell cellOfOperand(std::string_view operand, table::TableColumn const& column, + DisplayUnits const& units = {}); + +/// @brief A cell's text by its column's display, in the session's formatting. +/// +/// An unloaded cell is `""`: the backend draws its placeholder. An empty cell is the column's `empty`. Text in a +/// numeric or `Bool` column is read for the kind; text that does not read is `""` (`CellLook::Invalid`), and text +/// that reads shows as the value it reads as. Then the first label whose operand names the cell's value gives the +/// text. Otherwise a number is rounded to `decimals` (or shown at its own places) and written with the locale's +/// separators, grouped when `grouping` says; a date in the column's pattern, else the session's, else ISO; a measure +/// in its unit (or the dimension's chosen one) to that unit's decimals, then a space and the unit's symbol. +/// @param cell The cell. +/// @param column Its column. +/// @param locale The session's formatting: numbers, date patterns and the display zone. +/// @param units What a `Measure` cell is shown through. +/// @return The text. +[[nodiscard]] MORPH_API std::string formatCell(table::Cell const& cell, table::TableColumn const& column, + FormatContext const& locale, DisplayUnits const& units = {}); + +/// @brief The values list's entries as the column shows them. +/// +/// Each operand is read with `cellOfOperand` and formatted; a date bucket's range operand (`a..b`) keeps the server's +/// text. Entries whose texts are equal are formatted again at their own places (`decimals` cleared), so two values +/// that show alike stay two entries a user can tell apart. +/// @param values The distinct values, in the reply's order. +/// @param column Their column. +/// @param locale The session's formatting. +/// @param units What a `Measure` value is shown through. +/// @return One text per value, in order. +[[nodiscard]] MORPH_API std::vector distinctTexts(std::span values, + table::TableColumn const& column, + FormatContext const& locale, + DisplayUnits const& units = {}); + +/// @brief A column header's text with its unit: what the header and "Copy with headers" write. +/// @param label The header's label. +/// @param unit The column's unit; empty for none. +/// @return `"Mass [kg]"`, or the label alone. +[[nodiscard]] MORPH_API std::string headerText(std::string_view label, std::string_view unit); + +/// @brief A column header's accessible name with its unit. +/// @param label The header's label. +/// @param unit The column's unit; empty for none. +/// @return `"Mass, kg"`, or the label alone. +[[nodiscard]] MORPH_API std::string headerAccessibleName(std::string_view label, std::string_view unit); + +} // namespace morph::ui diff --git a/include/morph/ui/document.hpp b/include/morph/ui/document.hpp index 3b2f75fa3..5e5416100 100644 --- a/include/morph/ui/document.hpp +++ b/include/morph/ui/document.hpp @@ -60,13 +60,22 @@ struct ActionRecordInfo { std::string record; /// @brief The record's key field; absent for a keyless record. std::optional keyField; - /// @brief The JSON paths at which the result holds the record; `""` is the result itself. + /// @brief The JSON paths at which the result holds the record; `""` is the result itself. Empty when `opaque`. std::vector paths; + /// @brief The paths of members that open the entry: while any is set, a row the entry does not hold may come + /// to belong to it, so every change of the record marks it. + std::vector open; + /// @brief The paths of members that make the entry partial: while any is set, an `updates` effect on the + /// record marks the entry instead of merging into it. + std::vector partial; + /// @brief The result holds the record at no path a key can be read at: every change of the record marks the + /// entry, which is never merged into, and its reply keeps fractional numbers as decimals. + bool opaque = false; /// @brief Memberwise equality. /// @param lhs One entry. /// @param rhs The other. - /// @return True when record, key field and paths match. + /// @return True when record, key field, paths, open and partial members and opacity match. friend bool operator==(ActionRecordInfo const& lhs, ActionRecordInfo const& rhs) = default; }; @@ -832,4 +841,11 @@ enum class NameCategory : std::uint8_t { /// @return Their `kind` spellings. [[nodiscard]] MORPH_API std::vector partKinds(); +/// @brief The top-level members of an action's request schema that hold a table query: each property marked +/// `x-table` (`table::TableQuery::schemaMarker()`), in name order. A table over the action writes its +/// query into the one member this names. +/// @param schemaJson The schema, as `Catalog::schema` answers it. +/// @return The members' names; empty when the text is not a schema object or no property is marked. +[[nodiscard]] MORPH_API std::vector tableQueryMembers(std::string_view schemaJson); + } // namespace morph::ui diff --git a/include/morph/ui/expression.hpp b/include/morph/ui/expression.hpp index 2668de195..1d6bafe28 100644 --- a/include/morph/ui/expression.hpp +++ b/include/morph/ui/expression.hpp @@ -462,6 +462,33 @@ struct Number { [[nodiscard]] MORPH_API std::optional convertUnit(math::Rational const& value, std::string_view from, std::string_view target, UnitTable const& units); +/// @brief Orders two values of one comparable kind as the expression language does: numbers by exact value, a +/// quantity converted to the other's unit, timestamps by instant, strings by their bytes, and +/// booleans with `false` before `true`. +/// @param lhs A value. +/// @param rhs The other. +/// @param units The unit table quantities convert through. +/// @return The ordering; `std::nullopt` when the two are not of one comparable kind. +[[nodiscard]] MORPH_API std::optional valueOrder(Value const& lhs, Value const& rhs, + UnitTable const& units); + +/// @brief Equality of two non-null values as the expression language's `eq` reads it: numbers by value (an `int` +/// equals the equal `decimal`, places do not count, a quantity equals one of another unit that converts to +/// it), lists and records element by element, other kinds by `Value ==`. +/// @param lhs A value. +/// @param rhs The other. +/// @param units The unit table quantities convert through. +/// @return Whether they are equal. +[[nodiscard]] MORPH_API bool valuesEqual(Value const& lhs, Value const& rhs, UnitTable const& units); + +/// @brief Equality of two elements, as `valuesEqual` where `null` equals only `null`: whether two adjacent rows +/// belong to one run of a `runs` or of a table's `group`. +/// @param left A value. +/// @param right The other. +/// @param units The unit table quantities convert through. +/// @return Whether they are the same element. +[[nodiscard]] MORPH_API bool sameElement(Value const& left, Value const& right, UnitTable const& units); + /// @brief The display text of a unit. /// @param unit The unit id. /// @param units The unit table. diff --git a/include/morph/ui/form_rows.hpp b/include/morph/ui/form_rows.hpp new file mode 100644 index 000000000..6816b899a --- /dev/null +++ b/include/morph/ui/form_rows.hpp @@ -0,0 +1,268 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file ui/form_rows.hpp +/// @brief `FormRowsSource`: the `table::DataSource` over a form's `ObjectArray` field, whose rows a grid of the form +/// lays out. +/// +/// Specified in `docs/spec/table/editing.md`, "A grid of a form". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../forms/engine/form_session.hpp" +#include "table_rows.hpp" + +namespace morph::ui { + +/// @brief The record member a grid's row record holds its row's key in. No member of a row type has the name: `#` +/// introduces a row key in `forms::FormSession::field` paths. +inline constexpr std::string_view kGridKeyField = "#key"; + +namespace detail { + +/// @brief The column kind a member of a form's row type sorts and filters as. +/// @param kind The member's field kind. +/// @return `Integer` for an integer or a slider, `Decimal` for a decimal or a quantity, `Number` for a plain number, +/// `Date` and `DateTime` for dates, `Bool` for a Boolean, `Text` for every other kind. +[[nodiscard]] MORPH_API table::ColumnKind columnKindOf(forms::FieldKind kind) noexcept; + +/// @brief A member's cell: its encoding as a cell of its column's kind, empty when blank, and, when the draft does +/// not encode, the draft's text, which a column of any kind but `Text` reads as an invalid cell. +/// @param field The member. Read untracked by the caller. +/// @param kind The column's kind. +/// @return The cell. +// One case per kind of the column. +// NOLINTNEXTLINE(readability-function-cognitive-complexity) +[[nodiscard]] MORPH_API table::Cell memberCell(forms::FieldState const& field, table::ColumnKind kind); + +/// @brief The cell of a member a column edits per row, whose kind varies by row: text, so the column sorts and filters +/// as one kind. A member that encodes a string (an Enum's or a Choice's option, a text) gives the string, not +/// the draft's JSON literal; any other gives its draft. +/// @param field The member. Read untracked by the caller. +/// @return The cell; empty while the draft is blank. +[[nodiscard]] MORPH_API table::Cell perRowCell(forms::FieldState const& field); + +/// @brief The rows of a form's collection as a snapshot: each row's key, its cells and its record. +class FormRowsSnapshot final : public table::RowSnapshot { +public: + /// @brief A snapshot of rows. + /// @param columns How many columns each row has. + /// @param keys The rows' keys. + /// @param cells The rows' cells, one vector per row. + /// @param records The rows' records. + /// @param runs Each run's heading record, in the array's order; none for rows that are not grouped. + FormRowsSnapshot(std::size_t columns, std::vector keys, std::vector> cells, + std::vector records, std::vector runs = {}) + // Parentheses for the records: braces would make a list of one value holding them all. + : _columns{columns}, + _keys{std::move(keys)}, + _cells{std::move(cells)}, + _records(std::move(records)), + _runs(std::move(runs)) {} + + /// @brief How many rows. + /// @return The count. + [[nodiscard]] std::size_t rowCount() const override { return _keys.size(); } + + /// @brief A row's key. + /// @param row The row. + /// @return Its key. + [[nodiscard]] table::RowId rowId(std::size_t row) const override { return _keys.at(row); } + + /// @brief A row's cell. + /// @param row The row. + /// @param column The column. + /// @return The cell; empty past the columns. + [[nodiscard]] table::Cell cell(std::size_t row, std::size_t column) const override { + return column < _columns ? _cells.at(row).at(column) : table::Cell{}; + } + + /// @brief A row's record. + /// @param row The row. + /// @return The record. + [[nodiscard]] Value const& record(std::size_t row) const { return _records.at(row); } + + /// @brief Every row's cells. + /// @return They, by row. + [[nodiscard]] std::vector> const& cells() const noexcept { return _cells; } + + /// @brief Every row's record. + /// @return They, by row. + [[nodiscard]] std::vector const& records() const noexcept { return _records; } + + /// @brief Every row's key. + /// @return They, in the array's order. + [[nodiscard]] std::vector const& keys() const noexcept { return _keys; } + + /// @brief Each run's heading record. + /// @return They, by run index. + [[nodiscard]] std::vector const& runs() const noexcept { return _runs; } + +private: + std::size_t _columns; + std::vector _keys; + std::vector> _cells; + std::vector _records; + std::vector _runs; +}; + +} // namespace detail + +/// @brief The rows of a form's `ObjectArray` field as a `table::DataSource`, in the array's order. +/// +/// A row's id is its `forms::RowState::key()`. A cell is its member's encoding as a cell of the column's kind +/// (`detail::memberCell`), so sorting and filtering follow the table's rules, and the source never writes the array: a +/// grid's order is the view's, never the record's. A change of the field's rows or of a member's draft is taken in at +/// the next turn of the owner, and at once by `sync`, which whatever reads the rows calls first: a draft change of one +/// member notifies `Updated` for its row alone, rows added at the end or removed notify `Inserted` or `Removed`, and +/// any other change of the rows `Reset`. +class MORPH_API FormRowsSource final : public table::DataSource { +public: + /// @brief A source over a collection of @p form. + /// @param form The form. Borrowed: it must outlive the source. + /// @param arrayPath The collection's path (`forms::FormSession::field`). + /// @param columns The columns. + /// @param members The member of the row type each column reads, by index into @p columns; empty: each column's + /// id names its member. + /// @param perRow For a column whose member varies by row, by index into @p columns, the member's name for a + /// row; + /// its member in @p members is then empty, and its cell is text (`detail::perRowCell`, a `Text` + /// column). + /// Empty: no column varies. + /// @throws std::out_of_range when no field has @p arrayPath. + /// @throws std::invalid_argument when the field is not a collection, @p members is neither empty nor one per + /// column, @p perRow is neither empty nor one per column, or a column reads no member. + FormRowsSource(forms::FormSession& form, std::string arrayPath, std::vector columns, + std::vector members = {}, + std::vector> perRow = {}); + + FormRowsSource(FormRowsSource const&) = delete; + FormRowsSource& operator=(FormRowsSource const&) = delete; + FormRowsSource(FormRowsSource&&) = delete; + FormRowsSource& operator=(FormRowsSource&&) = delete; + /// @brief Stops watching the field. + ~FormRowsSource() override = default; + + /// @brief The columns. + /// @return They, as given. + [[nodiscard]] std::span columns() const override { return _columns; } + + /// @brief The rows as last taken in. + /// @return The same pointer until they change. + [[nodiscard]] std::shared_ptr snapshot() const override { return _held; } + + /// @brief Registers @p listener. + /// @param listener The listener. + void subscribe(table::ChangeListener& listener) override { _listeners.add(listener); } + + /// @brief Removes @p listener; safe from inside a notification. + /// @param listener The listener. + void unsubscribe(table::ChangeListener& listener) override { _listeners.remove(listener); } + + /// @brief The form. + /// @return It. + [[nodiscard]] forms::FormSession& form() const noexcept { return *_form; } + + /// @brief The collection's path. + /// @return It, as given. + [[nodiscard]] std::string const& arrayPath() const noexcept { return _arrayPath; } + + /// @brief The collection field. + /// @return It. + [[nodiscard]] forms::FieldState& array() const noexcept { return *_array; } + + /// @brief A row of the collection by its id. Untracked. + /// @param key The row's id. + /// @return The row, or null when the collection has none with that key. + [[nodiscard]] forms::RowState* row(table::RowId const& key) const; + + /// @brief Groups the rows by @p by: adds the column `kGroupRunColumn` (`Integer`, laid out by no grid), whose cell + /// is a row's run index, runs counted over the array's order, a new run where `by` differs from the + /// previous row's (`detail::sameElement`). Notifies `Reset`. + /// + /// `by` is read untracked, whenever the rows are taken in. + /// @param groupBy A row's group value; empty: no groups, and the column goes. + void setGroup(std::function groupBy); + + /// @brief Each run's heading record, `{key, count, first, last, items}` with its heading key in + /// `detail::kGroupHeadingField`, by run index, as of the rows last taken in. + /// @return They; none while the rows are not grouped. + [[nodiscard]] std::span runRecords() const noexcept { return _held->runs(); } + + /// @brief How many times the rows were read whole into a snapshot: once at construction and once per change taken + /// in, whatever reads the rows in between. + /// @return The count. + [[nodiscard]] std::size_t builds() const noexcept { return _builds; } + + /// @brief What `EngineRows` reads a row's key and record through: the grid's own record, `{"": the + /// member's + /// encoded value, null when blank or not encoding, …, "#key": the row's key}`. + /// @return The reader; it holds nothing of the source. + [[nodiscard]] static RecordOf recordOf(); + + /// @brief Takes in the field's rows as they are now, notifying what changed since they were last taken in. Costs + /// nothing while neither the rows nor a member's draft changed since. + /// @return Whether anything was taken in. + bool sync(); + +private: + // An insertion or a removal that keeps every other row and its cells: its indices; anything else is a reset. + [[nodiscard]] static std::optional structural(detail::FormRowsSnapshot const& before, + detail::FormRowsSnapshot const& after); + + // The version of what the rows hold, read untracked. + [[nodiscard]] std::uint64_t currentVersion() const { + return _form->runtime().untracked([&] { return _version->get(); }); + } + + // The rows as the field holds them now, read untracked. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one pass building the snapshot's parallel vectors. + [[nodiscard]] std::shared_ptr build() const; + + // The runs of the rows in the array's order: each row's run index appended to its cells, and each run's heading + // record. A heading's key is its run's key and its ordinal among the runs with an equal key, as a `rows` table's. + [[nodiscard]] std::vector groupRuns(std::vector const& records, + std::vector>& cells) const; + + // Tracks the rows and every member's draft; a change is taken in at the owner's next turn. + void watch(); + + forms::FormSession* _form; + std::string _arrayPath; + forms::FieldState* _array; + std::vector _columns; + std::vector _members; + std::vector> _perRow; + std::function _group; + std::shared_ptr _held; + table::detail::Listeners _listeners; + bool _watching = false; + bool _posted = false; + async::CallbackScope _alive; + mutable std::uint64_t _versions = 0; + std::uint64_t _synced = 0; + mutable std::uint64_t _indexed = 0; + mutable std::unordered_map _byKey; + mutable std::size_t _builds = 0; + std::unique_ptr> _version; + std::unique_ptr _watch; +}; + +} // namespace morph::ui diff --git a/include/morph/ui/grid.hpp b/include/morph/ui/grid.hpp new file mode 100644 index 000000000..43be35a1d --- /dev/null +++ b/include/morph/ui/grid.hpp @@ -0,0 +1,2376 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file ui/grid.hpp +/// @brief A grid: a table whose cells are edited. `GridController` holds a grid's focus, its cell editor and its walk +/// over a `GridSource`; `FormGridSource` is a grid of a form's `ObjectArray` field, and `makeFormGrid` the node +/// that shows one; `FixedGridSource` is a fixed grid, whose rows a standard fixes and whose cells are each a +/// field of their own; `ModelGridSource` is the cells of a model's table, edited through its edit actions. +/// +/// Specified in `docs/spec/table/editing.md`. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "form_rows.hpp" +#include "mount.hpp" + +namespace morph::ui { + +/// @brief Where `Enter` moves after it commits a cell's editor. +enum class EnterMoves : std::uint8_t { + Down, ///< To the first editable cell below, in the same column. + Right, ///< To the next editable cell of the row. + None, ///< Nowhere: focus stays on the cell. +}; + +/// @brief The order `Tab` walks a grid's editable cells in. +enum class Walk : std::uint8_t { + Rows, ///< Along a row, then the next row. + Columns, ///< Down a column, then the next column. +}; + +/// @brief One column of a grid of a form: a member of the row type it edits, or a display column. +struct GridColumn { + /// @brief The column's id (`TableColumn::id`). + std::string id; + /// @brief The header's text. + std::string label; + /// @brief The member of the row type the column edits; empty for a display column, or one with `fieldOf`. + std::string field; + /// @brief A display column's text for a row; read only while `field` and `fieldOf` are empty. + std::function value; + /// @brief The member the column edits in a row, when it varies by row: the record decides a value's kind. Tracked. + /// A name that is no member leaves the row's cell with no field, so it is read-only. + std::function fieldOf; + /// @brief The entry places of the row's member, which are also its wire `dp`; nothing keeps the field's. Tracked. + std::function(forms::RowState const&)> decimals; + /// @brief The unit the row's member is entered in, an id of its `FieldSpec::units`: applied, converting the draft + /// as the + /// editor's unit select does, when it first gives a unit for the row or gives another one, so a unit the + /// user picks afterwards stays; nothing, or an id the field does not have, after a unit restores the + /// field's entry unit. The first unit a loaded row's member takes, while the overlay had given none before, + /// counts as loaded + /// (`forms::FormSession::switchUnitsAsLoaded`): the cell is not modified by it, and a revert returns to it. + /// Tracked. + std::function(forms::RowState const&)> unit; + /// @brief Whether the row's cell is read-only beyond its field (`CellFacts::overlayReadOnly`). Tracked. + std::function readonly; + /// @brief The options the row's member offers, as their values' JSON literals, narrowing a choice's; nothing + /// offers every option. Tracked. + std::function>(forms::RowState const&)> options; + /// @brief The row's member's placeholder; empty keeps the field's. Tracked. + std::function placeholder; +}; + +/// @brief How a grid walks and what activating a read-only cell does. +struct GridOptions { + /// @brief Where `Enter` moves after a commit. + EnterMoves enterMoves = EnterMoves::Down; + /// @brief The order `Tab` follows. + Walk walk = Walk::Rows; + /// @brief The table's `onActivate`: what `Enter` or a double click on a read-only cell runs, with its row's key. + std::function onActivate; + /// @brief Whether the walk past the end and `Enter` below the last row add a row, and an "Add row" button under + /// the grid does, up to the field's `maxItems`. + bool appendRows = false; + /// @brief Whether the rows are the record's: no row is inserted, deleted or appended, and no entry offers it. + bool rowsFixed = false; + /// @brief The most values one paste writes or drops: a larger block is refused whole, and nothing is written. + std::size_t maxPasteCells = 10'000; + /// @brief The most rows one copy puts on the clipboard (`GridController::copyRefusal`). + std::size_t maxCopyRows = 10'000; + /// @brief The timers the offer to undo a deletion ends on; without one it ends only at the grid's next change. + reactive::Scheduler* scheduler = nullptr; + /// @brief How long the offer to undo a deletion lasts, unless a change of the grid ends it first: a status line + /// notice's hold. + std::chrono::milliseconds undoHold{6000}; +}; + +/// @brief What a paste did with each value of its block. +struct PasteResult { + /// @brief The values written into editable cells. + std::size_t written = 0; + /// @brief The values dropped on read-only or covered cells. + std::size_t readOnly = 0; + /// @brief The values dropped on rows past the last one that could not be added. + std::size_t pastRows = 0; + /// @brief The values dropped past the last visible column. + std::size_t pastColumns = 0; +}; + +/// @brief The status line's notice after a paste. +/// @param result What the paste did. +/// @return `Pasted {written} values`, then, when anything was dropped, `; `, the parts present joined by ` and ` — +/// `{readOnly} on read-only cells`, `{pastRows} past the last row`, `{pastColumns} past the last column` — +/// and ` were dropped`. +[[nodiscard]] MORPH_API std::string pasteMessage(PasteResult const& result); + +/// @brief Which row operations a grid offers now. +struct RowOps { + /// @brief Whether a row can be inserted or appended. + bool insert = false; + /// @brief Whether a row can be deleted. + bool remove = false; + /// @brief Why one is not: the bound it would pass; empty when both are offered, or the rows are fixed. + std::string why; +}; + +/// @brief Every fact a cell's read-only state follows from; `cellReadOnly` is the one rule over them. +struct CellFacts { + /// @brief The cell's field; null for a column with no field (a display column), or a cell with none. + forms::FieldState const* field = nullptr; + /// @brief Whether the column has an edit: a form's member, or an edit action. + bool hasEdit = true; + /// @brief The column's `readonly` overlay, for the cell's row. + bool overlayReadOnly = false; + /// @brief The column's `EditInfo::readonly` companion, for the cell's row. + bool companionReadOnly = false; + /// @brief The row is busy with an action that is not the table's own edit. + bool busy = false; + /// @brief The row is locked by someone else. + bool locked = false; + /// @brief The cell's value is not loaded. + bool unloaded = false; + /// @brief The cell's value is in a unit its field cannot hold: a measure the table's units cannot convert into its + /// field's unit. + bool foreignUnit = false; +}; + +/// @brief Whether a cell is read-only: what the walk skips, what refuses an edit, a paste and a fill, and what draws +/// on the read-only surface. Tracked through the field's `readonly()`. +/// @param facts The cell's facts. +/// @return `true` when the cell has no field or no edit, its field is read-only (`x-readonly`, `x-computed`, +/// `x-derived`, a `readonlyWhen` reaching it), or any other fact holds. +[[nodiscard]] MORPH_API bool cellReadOnly(CellFacts const& facts); + +/// @brief What a grid's controller gives its source to keep the focus on its row's key. Where the focused row is in +/// the view, and the row that takes focus when it leaves, are the mount's, as for any table. +struct FocusLink { + /// @brief A row's key changed from the first to the second: the focus and an open editor on it follow. + std::function moved; +}; + +/// @brief What a grid edits: its rows by view index, which a model's table holds only a window of, and its cells by +/// row key and column id. +// NOLINTBEGIN(cppcoreguidelines-special-member-functions) +class MORPH_API GridSource { +public: + GridSource() = default; + GridSource(GridSource const&) = delete; + GridSource& operator=(GridSource const&) = delete; + virtual ~GridSource() = default; + + /// @brief The view's rows, fetched or not. + /// @return The count. + [[nodiscard]] virtual std::size_t rowCount() const = 0; + + /// @brief The key of the row at a view position. + /// @param viewRow The position. + /// @return The key; empty while that row is not fetched. + [[nodiscard]] virtual std::optional keyAt(std::size_t viewRow) const = 0; + + /// @brief Where a key's row is in the view now. + /// @param key The key. + /// @return The view position; empty when the view has no row with the key. + [[nodiscard]] virtual std::optional positionOf(Key const& key) const = 0; + + /// @brief The ids of the visible columns in layout order: the walk's order. A cell is named by its column's id. + /// @return The ids. + [[nodiscard]] virtual std::vector columns() const = 0; + + /// @brief The editor of an editable cell, built once per opening: the forms control of the cell's field. Never + /// asked of a read-only cell, or of one that `toggles`. + /// @param key The row's key. + /// @param column The column's id. + /// @return The editor. + [[nodiscard]] virtual Node editor(Key const& key, std::string_view column) = 0; + + /// @brief Whether a cell's field is a Boolean, which `Space` flips and which opens no editor. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` for a Boolean's cell. + [[nodiscard]] virtual bool toggles(Key const& key, std::string_view column) const = 0; + + /// @brief Whether a cell is read-only (`cellReadOnly`). Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` when read-only. + [[nodiscard]] virtual bool readOnly(Key const& key, std::string_view column) const = 0; + + /// @brief Whether a cell is covered by a span. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` when covered. + [[nodiscard]] virtual bool covered(Key const& key, std::string_view column) const = 0; + + /// @brief The spans a row gives, for the mount to draw, while they apply (`covered` says when). + /// @param key The row's key. + /// @return Each span as `cutColumns` cuts it over the layout; none by default. + [[nodiscard]] virtual std::vector spans(Key const& key) const; + + /// @brief Whether any row may give spans: the mount then resolves them over every realized row. + /// @return `false` by default. + [[nodiscard]] virtual bool spanning() const { return false; } + + /// @brief A data row's cell content as a grid draws it, before its marks: its text, and its error as an accent. + /// @param column The column's id. + /// @param row The signal holding the row's record; it must outlive the node. + /// @return The cell's node. + [[nodiscard]] Node cellContent(std::string const& column, reactive::Signal const& row); + + /// @brief A data row's cell as a grid draws it: `cellContent` with the cell's marks. + /// @param column The column's id. + /// @param row The signal holding the row's record; it must outlive the node. + /// @return The cell's node. + [[nodiscard]] Node cellView(std::string const& column, reactive::Signal const& row); + + /// @brief A cell's draft, as the user typed it. Untracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The draft; empty for a cell with no field. + [[nodiscard]] virtual std::string draft(Key const& key, std::string_view column) const = 0; + + /// @brief A cell's display text. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The text. + [[nodiscard]] virtual std::string text(Key const& key, std::string_view column) const = 0; + + /// @brief Why a cell's value is refused. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The message; empty for none. + [[nodiscard]] virtual std::optional error(Key const& key, std::string_view column) const = 0; + + /// @brief Writes a user's draft into a cell. + /// @param key The row's key. + /// @param column The column's id. + /// @param draft The draft. + virtual void write(Key const& key, std::string_view column, std::string draft) = 0; + + /// @brief An edit is meant: called once per change a user commits. + virtual void committed() = 0; + + /// @brief A cell's marks. Tracked: every read it depends on is tracked, so a binding over it follows drafts, + /// errors, edits and row states. + /// @param key The row's key. + /// @param column The column's id. + /// @return The marks. + [[nodiscard]] virtual CellMarks marks(Key const& key, std::string_view column) const = 0; + + /// @brief The key of the row a record is: a cell view knows its row only through the record its signal holds. + /// @param record The record. + /// @return The key; empty for a record with no key, which draws no marks. + [[nodiscard]] virtual std::optional keyOf(Value const& record) const = 0; + + /// @brief Whether some cell of a row is modified, or the row was added since the load. Tracked. + /// @param key The row's key. + /// @return `true` when modified. + [[nodiscard]] virtual bool rowModified(Key const& key) const = 0; + + /// @brief The data rows, by view index: what `rowCount`, `keyAt` and `positionOf` count. + /// @return The rows. + [[nodiscard]] virtual TableRows& view() = 0; + + /// @brief Restores a cell's loaded value. A source with no loaded values does nothing. + /// @param key The row's key. + /// @param column The column's id. + virtual void revertCell(Key const& key, std::string_view column); + + /// @brief Restores a row's loaded values. A source with no loaded values does nothing. + /// @param key The row's key. + virtual void revertRow(Key const& key) { static_cast(key); } + + /// @brief Holds the row an editor is open on where it is in the view, whatever its values do to the sort and the + /// filter; nothing lets it go. A source whose rows never move under an edit does nothing. + /// @param key The row's key, or nothing. + // NOLINTNEXTLINE(performance-unnecessary-value-param): `key` is moved into the source by its overriding implementation, which takes it by value; this default only discards it + virtual void holdRow(std::optional key) { static_cast(key); } + + /// @brief A cell's editor opened: a choice in it fetches its options from now on. A source with nothing to fetch + /// does nothing. + /// @param key The row's key. + /// @param column The column's id. + virtual void editorOpened(Key const& key, std::string_view column); + + /// @brief Whether the derived values are the last ones loaded before a failed round, until a round succeeds: what + /// the + /// status line offers to recalculate. Tracked. + /// @return `true` while it holds; `false` for a source with no derived values. + [[nodiscard]] virtual bool deriveFailed() const { return false; } + + /// @brief Makes one more round of derived values. A source with none does nothing. + virtual void recalculate() {} + + /// @brief Whether the grid's rows are its own to insert, delete and append: a source that is not offers no row + /// operation, as `GridOptions::rowsFixed` does. + /// @return `false` unless a source says otherwise. + [[nodiscard]] virtual bool rowsEditable() const { return false; } + + /// @brief How many rows the record holds, whatever the filter shows: what `bounds` is compared with. Tracked. + /// @return The count; `rowCount` for a source whose view is its record. + [[nodiscard]] virtual std::size_t heldRows() const { return rowCount(); } + + /// @brief The fewest and the most rows the record holds. + /// @return `{minItems, maxItems}`; `{0, nothing}` for a source with no bound. + [[nodiscard]] virtual std::pair> bounds() const { + return {0, std::nullopt}; + } + + /// @brief Appends a blank row to the record. A source whose rows are not its own adds none. + /// @return The new row's key; nothing when no row was added. + virtual std::optional appendRow() { return std::nullopt; } + + /// @brief Inserts a blank row before the row at a view position. A source whose rows are not its own adds none. + /// @param position The view position; `rowCount()` appends. + /// @return The new row's key; nothing when no row was added. + virtual std::optional insertRow(std::size_t position); + + /// @brief Removes rows from the record in one change, kept so `undoRemove` can put them back. + /// @param keys The rows' keys. + /// @return `true` when one of them held a value. + virtual bool removeRows(std::span keys); + + /// @brief Puts the rows the last `removeRows` took back, each where it stood, in one change, while the record has + /// not changed since; does nothing after a change. + virtual void undoRemove() {} + + /// @brief Why typing on a read-only cell is refused, where the source can say more than that it is read-only. + /// @param key The row's key. + /// @param column The column's id. + /// @return The status line's text; nothing for the plain refusal. + [[nodiscard]] virtual std::optional refusal(Key const& key, std::string_view column) const; + + /// @brief Focus moved: to a row, or onto no fetched row or out of the table. A source that holds a row's edits + /// back until focus leaves the row commits them here. + /// @param key The row focus is on now; nothing when it is on none. + virtual void focusRow(std::optional const& key) { static_cast(key); } + + /// @brief `Ctrl+Enter`: commits what the source holds back. A source that holds nothing does nothing. + virtual void commitHeld() {} + + /// @brief Whether a cell's draft was committed and refused before it was sent, so committing it again sends it + /// even though the user did not change it. + /// @param key The row's key. + /// @param column The column's id. + /// @return `false` unless a source holds such a draft. + [[nodiscard]] virtual bool resends(Key const& key, std::string_view column) const; + + /// @brief Whether the grid selects rectangles of cells, and so takes a paste and a fill: a source whose rows are + /// selected as rows takes neither, and its `Shift`+arrows and `Ctrl+A` are the table's row selection. + /// `Delete` on the focused cell blanks it either way. + /// @return `true` unless a source says otherwise. + [[nodiscard]] virtual bool selectsCells() const { return true; } + + /// @brief Gives the source what follows the focused row's key when the key changes. A source whose keys never + /// change ignores it. + /// @param link The controller's side; empty members when the controller goes. + // NOLINTNEXTLINE(performance-unnecessary-value-param): `link` is moved into the source by its overriding implementation, which takes it by value; this default only discards it + virtual void followFocusWith(FocusLink link) { static_cast(link); } + + /// @brief Gives the source what moves focus to a cell while the table has focus: how a refusal that arrives after + /// focus left its row brings focus back. A source that never moves focus ignores it. + /// @param refocus Focuses a cell while the table has focus; empty when the controller goes. + // NOLINTNEXTLINE(performance-unnecessary-value-param): `refocus` is moved into the source by its overriding implementation, which takes it by value; this default only discards it + virtual void refocusWith(std::function refocus) { static_cast(refocus); } +}; +// NOLINTEND(cppcoreguidelines-special-member-functions) + +/// @brief The rows of a grid of a form: the engine's view over a `FormRowsSource`, less the rows added since the sort +/// or the filter last changed, which follow it in the order they were added and pass the filter until it +/// changes, and less the row `hold` holds, which keeps the place it had and passes the filter until it is let +/// go. With no sort and no filter the view is the array's order, an inserted row in its place. +/// +/// A grid of a form runs no action per row: its `states()` hold nothing, and `moveKey` does nothing, since a form +/// row's key never changes. +class MORPH_API GridRows final : public TableRows, private table::ChangeListener { +public: + /// @brief Rows over a form's collection. + /// @param source The collection's rows. Must not be null. + /// @throws std::invalid_argument when @p source is null. + explicit GridRows(std::shared_ptr source); + + GridRows(GridRows const&) = delete; + GridRows& operator=(GridRows const&) = delete; + GridRows(GridRows&&) = delete; + GridRows& operator=(GridRows&&) = delete; + + /// @brief Stops hearing the source; the engine goes first. + ~GridRows() override; + + /// @brief The source. + /// @return It. + [[nodiscard]] FormRowsSource& source() const noexcept { return *_source; } + + /// @brief Takes in the field's rows as they are now, and the engine the change at once, so the view read next is + /// the field's. + void sync(); + + /// @brief Every row of the view, counted exactly. + /// @return The total. + [[nodiscard]] TableTotal total() const override; + + /// @brief The row at a view index. + /// @param index The view index. + /// @return The row; nothing past the view. + [[nodiscard]] std::optional row(std::int64_t index) const override; + + /// @brief No level: every cell of a form is here. + /// @param index Unused. + /// @return Nothing unloaded. + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override; + + /// @brief Does nothing: every row is present. + /// @param first Unused. + /// @param count Unused. + /// @param columns Unused. + void visible(std::int64_t first, std::int64_t count, std::span columns) override; + + /// @brief The keys of a range of view rows, at once. + /// @param first The first view row. + /// @param count The rows. + /// @return The keys; `InvalidSpec` for a range outside the view. + async::Completion, table::TableError>> keysOf(std::int64_t first, + std::int64_t count) override; + + /// @brief Finds a key's view index. + /// @param key The row's key. + /// @param stop Once a stop is requested, @p done is not called. + /// @param done Called on the owner with the index, or nothing when the view lacks the key. + void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) override; + + /// @brief Rows by key, from the engine. + /// @param keys The keys. + /// @param columns The columns. + /// @return The engine's answer. + async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) override { + return _engine->fetchRows(std::move(keys), std::move(columns)); + } + + /// @brief Sets the sort: the rows added since the last sort or filter change join the order. + /// @param sort The keys. + /// @return The engine's error, or nothing. + std::expected setSort(SortChain sort) override; + + /// @brief Sets the filter: the rows added since the last sort or filter change join the view or leave it. + /// @param filter The filter. + /// @return The engine's error, or nothing. + std::expected setFilter(table::FilterSpec filter) override; + + /// @brief A column's distinct values, from the engine. + /// @param request The request. + /// @return The engine's answer. + async::Completion> distinctValues( + table::DistinctRequest request) override { + return _engine->distinctValues(std::move(request)); + } + + /// @brief The counts: the view's rows, and the engine's source and pending state. + /// @return The counts. + [[nodiscard]] TableCountsView counts() const override; + + /// @brief No row of a form is busy or failed. + /// @return The empty states. + [[nodiscard]] RowStates& states() override { return _states; } + + /// @brief No row of a form is busy or failed. + /// @return The empty states. + [[nodiscard]] RowStates const& states() const override { return _states; } + + /// @brief Does nothing: a form row's key never changes. + /// @param from Unused. + /// @param target Unused. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`from`, `target`): the old key first, as every `moveKey` caller and override reads it + void moveKey(table::RowId const& from, table::RowId const& target) override; + + /// @brief Sets the one receiver of the view's changes. + /// @param handler The receiver; empty to stop receiving. + void onChange(std::function handler) override { _onChange = std::move(handler); } + + /// @brief Holds a row where it is in the view, and in it, whatever its values do to the sort and the filter, until + /// another row is held or none: the row an editor is open on stays under the editor. Letting it go puts it + /// where the sort and the filter place it. + /// @param key The row to hold; nothing lets the held row go. + void hold(std::optional key); + + /// @brief Whether a sort orders the view. + /// @return `true` while the sort is not empty. + [[nodiscard]] bool sorted() const noexcept { return _sorted; } + + /// @brief Groups the rows (`FormRowsSource::setGroup`) and takes the change in at once, so a sort that names + /// `kGroupRunColumn` is accepted from the next call. + /// @param groupBy A row's group value; empty: no groups. + void setGroup(std::function groupBy); + + /// @brief The row `hold` holds. + /// @return Its key; nothing while none is held. + [[nodiscard]] std::optional const& held() const noexcept { return _held; } + + /// @brief Where a key is in the view. + /// @param key The key. + /// @return Its view index, or nothing. + [[nodiscard]] std::optional positionOf(table::RowId const& key) const; + +private: + // A view row: its key, and its place in the engine's view, if it has one. + struct Item { + std::optional engine; + table::RowId key; + }; + + [[nodiscard]] static std::shared_ptr checked(std::shared_ptr source); + + // A row added while the view is ordered is shown at its end until the order next changes. + void rowsChanged(table::RowChange const& change) override; + + // The view's keys, in order. + [[nodiscard]] std::vector keys() const; + + // The view: the engine's rows but the added ones and the held one, then the added ones still in the source, and + // the held one at its place. + void rebuild(); + + // The record of an added row the filter rejects, built from the source's snapshot and kept until it changes. + [[nodiscard]] RowRecord const* heldRecord(table::RowId const& key) const; + + std::shared_ptr _source; + std::unique_ptr _engine; + std::function _onChange; + std::vector _appended; + std::vector _items; + std::unordered_map _positions; + mutable std::unordered_map _records; + RowStates _states; + bool _sorted = false; + bool _filtered = false; + std::optional _held; + std::size_t _heldAt = 0; + bool _aligned = true; +}; + +/// @brief The record member naming a summary row's spec: its key. A data record never holds it. +inline constexpr std::string_view kSummaryField = "#summary"; +/// @brief The record member holding the first data row a summary row's scope covers. +inline constexpr std::string_view kSummaryFirstField = "#first"; +/// @brief The record member holding how many data rows a summary row's scope covers. +inline constexpr std::string_view kSummaryCountField = "#count"; +/// @brief The record member holding a group summary's run ordinal; absent for a table's own summary. +inline constexpr std::string_view kSummaryRunField = "#run"; +/// @brief The record member a summary row's record changes in whenever the data rows change, so its cells are +/// evaluated again. +inline constexpr std::string_view kSummaryVersionField = "#version"; + +/// @brief The records of view rows of the data rows, a summary row's `rows` scope. +/// @param rows The data rows (a grid's `GridSource::view()`, or a `rows` table's rows), never a `SummaryRows`. +/// @param first The first view row. +/// @param count How many view rows. +/// @return The records, in view order; a row not fetched is left out. A grid row's record holds each member's encoded +/// value, `null` when blank or not encoding. +[[nodiscard]] MORPH_API ValueList summaryScopeRows(TableRows const& rows, std::int64_t first, std::int64_t count); + +/// @brief A summary row a table or a group declares: its key, and whether it is drawn before the rows it summarises. +struct SummarySpec { + /// @brief The summary's key, unique among the table's (or the group's) summaries. + std::string key; + /// @brief Whether it is drawn before the rows (`position: "top"`); after them otherwise. + bool top = false; +}; + +/// @brief The rows a mount is handed for a table with summary rows: the data rows, with the table's summaries before +/// or after them and each run's after (or before) the run, and, once `setHeadings` is given, each run's +/// heading before it. +/// +/// A forwarding decorator: it holds the data rows' one change slot and tells the mount each change in its own indices. +/// Summary and heading rows are outside the count, the selection, the sort and the filter: `total()` and `counts()` +/// are the data rows', `keysOf` skips them, and `mountedTotal()` is what the mount positions rows by. A summary row's +/// key is `"\x1Fsummary:" + key` (a group's `"\x1Fsummary:" + run ordinal + "/" + key`) and its record +/// `{"#summary": key, "#first": first data row, "#count": data rows in scope, "#version": n}`, a group's with +/// `"#run"` too; `#version` changes whenever the data rows change, so the summary's cells are evaluated again. A data +/// change the layout keeps is told as its own operations and a change of every summary and heading row. +class MORPH_API SummaryRows final : public TableRows { +public: + /// @brief The runs of the data rows, each `{first, count}` in the data rows' view. + using Runs = std::function>()>; + + /// @brief Summary rows over data rows. + /// @param data The data rows. Must not be null. + /// @param table The table's own summaries, in order. + /// @param perRun Each run's summaries, in order. + /// @param runs The runs of the data rows' view; empty or answering none for an ungrouped table. + /// @throws std::invalid_argument when @p data is null. + SummaryRows(std::shared_ptr data, std::vector table, std::vector perRun, + Runs runs); + + SummaryRows(SummaryRows const&) = delete; + SummaryRows& operator=(SummaryRows const&) = delete; + SummaryRows(SummaryRows&&) = delete; + SummaryRows& operator=(SummaryRows&&) = delete; + + /// @brief Gives the data rows' change slot up. + ~SummaryRows() override { _data->onChange({}); } + + /// @brief Draws a heading row before each run, from now on. + /// @param heading A run's heading row by its index among the runs: its key and record; empty draws none. + void setHeadings(std::function heading); + + /// @brief Takes the runs and the data rows in again, as a change of the data rows would, and tells the mount. + void relayout(); + + /// @brief The data rows. + /// @return They. + [[nodiscard]] TableRows& data() const noexcept { return *_data; } + + /// @brief The data rows' total: a summary row is outside the count. + /// @return It. + [[nodiscard]] TableTotal total() const override { return _data->total(); } + + /// @brief Every row the mount realizes: data, summary and heading rows. + /// @return The total. + [[nodiscard]] TableTotal mountedTotal() const override; + + /// @brief The row at a mounted index. + /// @param index The index. + /// @return A data row as the data rows give it, a summary or heading row as built; nothing past the rows. + [[nodiscard]] std::optional row(std::int64_t index) const override; + + /// @brief The mounted index of a data row. + /// @param dataRow The data row's view index. + /// @return Its mounted index; nothing past the data rows. + [[nodiscard]] std::optional mounted(std::int64_t dataRow) const; + + /// @brief The data row at a mounted index, or the nearest one to a summary or heading row (the one above on a + /// tie). + /// @param mountedRow The mounted index. + /// @return The data row's view index; nothing with no data row or past the rows. + [[nodiscard]] std::optional data(std::int64_t mountedRow) const; + + /// @brief Whether a mounted row is a summary row. + /// @param mountedRow The mounted index. + /// @return `true` for a summary row. + [[nodiscard]] bool summary(std::int64_t mountedRow) const; + + /// @brief The data rows' levels of a data row; nothing for a summary or heading row. + /// @param index The mounted index. + /// @return The levels. + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override; + + /// @brief Tells the data rows the data rows of a mounted range. + /// @param first The first mounted row. + /// @param count The rows. + /// @param columns The columns. + void visible(std::int64_t first, std::int64_t count, std::span columns) override; + + /// @brief The keys of the data rows of a mounted range: summary and heading rows are outside the selection. + /// @param first The first mounted row. + /// @param count The rows. + /// @return The data rows' answer. + async::Completion, table::TableError>> keysOf(std::int64_t first, + std::int64_t count) override; + + /// @brief Finds a key's mounted index. + /// @param key The key. + /// @param stop Once a stop is requested, @p done is not called. + /// @param done Called with the mounted index, or nothing. + void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) override; + + /// @brief Rows by key, from the data rows. + /// @param keys The keys. + /// @param columns The columns. + /// @return The data rows' answer. + async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) override { + return _data->fetchRows(std::move(keys), std::move(columns)); + } + + /// @brief Sorts the data rows. + /// @param sort The keys. + /// @return The data rows' answer. + std::expected setSort(SortChain sort) override { return _data->setSort(std::move(sort)); } + + /// @brief Filters the data rows. + /// @param filter The filter. + /// @return The data rows' answer. + std::expected setFilter(table::FilterSpec filter) override { + return _data->setFilter(std::move(filter)); + } + + /// @brief A column's distinct values, from the data rows. + /// @param request The request. + /// @return The data rows' answer. + async::Completion> distinctValues( + table::DistinctRequest request) override { + return _data->distinctValues(std::move(request)); + } + + /// @brief The data rows' counts. + /// @return They. + [[nodiscard]] TableCountsView counts() const override { return _data->counts(); } + + /// @brief The data rows' view as a selection takes it. + /// @return Their answer. + [[nodiscard]] std::expected selectView() const override { + return _data->selectView(); + } + + /// @brief The data rows' count of a selection. + /// @param selection The selection. + /// @return Their answer. + [[nodiscard]] SelectedCount selectedCount(TableSelection const& selection) const override { + return _data->selectedCount(selection); + } + + /// @brief Whether the data rows' view left a key. + /// @param key The key. + /// @return Their answer. + [[nodiscard]] bool leftView(table::RowId const& key) const override { return _data->leftView(key); } + + /// @brief Retains data rows. + /// @param keys The keys. + /// @return Their answer. + [[nodiscard]] RetainResult retain(std::span keys) override { return _data->retain(keys); } + + /// @brief Drops the data rows' retained rows. + void clearRetained() override { _data->clearRetained(); } + + /// @brief Whether a data row is retained and unmatched. + /// @param key The key. + /// @return Their answer. + [[nodiscard]] bool unmatched(table::RowId const& key) const override { return _data->unmatched(key); } + + /// @brief Holds the data rows' refetches. + /// @param run The run. + void holdRefetches(std::uint64_t run) override { _data->holdRefetches(run); } + + /// @brief Releases the data rows' refetches. + /// @param run The run. + void releaseRefetches(std::uint64_t run) override { _data->releaseRefetches(run); } + + /// @brief The data rows of a mounted range, with their cells. + /// @param first The first mounted row. + /// @param count The rows. + /// @param columns The columns. + /// @return The data rows' answer, in their view's indices. + async::Completion, table::TableError>> rowsOf( + std::int64_t first, std::int64_t count, std::span columns) override; + + /// @brief The data rows' states. + /// @return They. + [[nodiscard]] RowStates& states() override { return _data->states(); } + + /// @brief The data rows' states. + /// @return They. + [[nodiscard]] RowStates const& states() const override { return _data->states(); } + + /// @brief Moves a data row's key. + /// @param from The old key. + /// @param target The new key. + void moveKey(table::RowId const& from, table::RowId const& target) override { _data->moveKey(from, target); } + + /// @brief Sets the one receiver of the changes, in mounted indices. + /// @param handler The receiver; empty to stop receiving. + void onChange(std::function handler) override { _onChange = std::move(handler); } + +private: + struct Entry { + enum class Kind : std::uint8_t { Data, Summary, Heading } kind = Kind::Data; + std::int64_t data = 0; + bool perRun = false; + Key key; + Value record; + }; + + [[nodiscard]] static std::shared_ptr checked(std::shared_ptr data); + + // The data row exactly at a mounted index; nothing for a summary or heading row. + [[nodiscard]] std::optional exact(std::int64_t index) const; + + // The data rows of a mounted range: contiguous in the data rows' view, since summary and heading rows only + // interleave them. A range of summary rows alone is the empty range at the data row it stands before. + [[nodiscard]] std::pair dataRange(std::int64_t first, std::int64_t count) const; + + // A summary row of @p spec over the data rows [first, first + count). + [[nodiscard]] Entry summaryEntry(SummarySpec const& spec, std::optional run, std::int64_t first, + std::int64_t count) const; + + // The mounted rows, from the data rows' count and runs now. + void rebuild(); + + // Whether the rows hold a row per run: a heading or a group's summary. + [[nodiscard]] static bool perRun(std::vector const& entries) { + return std::ranges::any_of(entries, &Entry::perRun); + } + + // The data rows changed: the layout follows, and the mount hears the change in mounted indices, with every summary + // row changed after it. A change whose rows a run's rows move among is a reset. + void heard(table::ViewChange const& change); + + std::shared_ptr _data; + std::vector _table; + std::vector _perRun; + Runs _runs; + std::function _heading; + std::function _onChange; + std::vector _entries; + std::vector _mounted; + std::uint64_t _version = 0; +}; + +/// @brief The formatting a form's values are shown in, read from its options when called: a later +/// `forms::FormSession::setFormat` is read by the next call. +/// @param form The form. +/// @return `{locale: options().bcp47, numeric: options().locale, datePattern, dateTimePattern}`. +[[nodiscard]] MORPH_API FormatContext formatOf(forms::FormSession const& form); + +namespace detail { + +/// @brief Applies a `unit` overlay to a field: only when it first gives a unit, or gives another one than it last did, +/// since the overlay is read again on every change and a unit the user then picks in the editor must stay. It +/// switches as the editor does, converting the draft; no unit, or one the field does not have, after a unit +/// restores the field's entry unit. The first unit a field is given is part of how it is shown as loaded: it +/// goes to @p asLoaded, so the cell is not modified by it and a revert returns to it. A unit the field already +/// holds is not switched to, so applying the overlay again writes nothing. +/// @param applied The unit the overlay last gave each field, by path; updated. +/// @param state The field. +/// @param unit The unit the overlay gives now, an id of the field's units; nothing for none. +/// @param asLoaded The fields whose first unit is switched as loaded, with the unit's index, after the caller's walk. +MORPH_API void applyUnitOverlay(std::unordered_map>& applied, + forms::FieldState& state, std::optional const& unit, + std::vector>& asLoaded); + +/// @brief A field's cell text as a grid shows it. Tracked. +/// @param state The field. +/// @param column The column's id. +/// @param format How values are shown. +/// @return The draft while blank or not encoding, else the value at the places the field takes: its `places()`, its +/// `x-decimalPlaces`, its display places, or none for an integer. +[[nodiscard]] MORPH_API std::string fieldText(forms::FieldState& state, std::string_view column, + FormatContext const& format); + +} // namespace detail + +/// @brief A grid of a form's `ObjectArray` field: its rows are the field's, and each cell is a member's field. +/// +/// Every row of a form is fetched, so `keyAt` is never empty below `rowCount`. A cell's text is its draft while blank +/// or not encoding, else its value shown at the places its field takes. +class MORPH_API FormGridSource final : public GridSource { +public: + /// @brief A grid of a form's collection. + /// @param form The form. Borrowed: it must outlive the source. + /// @param arrayPath The collection's path. + /// @param columns The columns, each id once. + /// @param format How values are shown. + /// @throws std::out_of_range when no field has @p arrayPath. + /// @throws std::invalid_argument when the field is not a collection, or a column's `field` names no member. + FormGridSource(forms::FormSession& form, std::string arrayPath, std::vector columns, + FormatContext format); + + FormGridSource(FormGridSource const&) = delete; + FormGridSource& operator=(FormGridSource const&) = delete; + FormGridSource(FormGridSource&&) = delete; + FormGridSource& operator=(FormGridSource&&) = delete; + + /// @brief Removes the commit `onBeforeSubmit` registered. + ~FormGridSource() override; + + /// @brief The rows of the view; the field's rows are taken in first. + /// @return The count. + [[nodiscard]] std::size_t rowCount() const override; + + /// @brief The key at a view position; the field's rows are taken in first. + /// @param viewRow The position. + /// @return The key; empty past the view. + [[nodiscard]] std::optional keyAt(std::size_t viewRow) const override; + + /// @brief Where a key is in the view; the field's rows are taken in first. + /// @param key The key. + /// @return The position, or nothing. + [[nodiscard]] std::optional positionOf(Key const& key) const override; + + /// @brief The visible columns in layout order. + /// @return The ids, as `setLayout` gave them; every column in declared order before it. + [[nodiscard]] std::vector columns() const override { return _layout; } + + /// @brief Shows the cells in another formatting from now on: a mounted cell's text follows. + /// @param format How values are shown. + void setFormat(FormatContext format); + + /// @brief Sets the visible columns in layout order: what the walk follows. + /// @param visible The column ids. + void setLayout(std::vector visible); + + /// @brief A cell's field: the member its column names, or the one `GridColumn::fieldOf` names for the row. + /// Tracked through `fieldOf`. + /// @param row The row's key. + /// @param column The column's id. + /// @return The field; null for a display column, an unknown column, a row the field does not hold, or a name + /// `fieldOf` gives that is no member. + [[nodiscard]] forms::FieldState* field(Key const& row, std::string_view column) const; + + /// @brief A row by its key. + /// @param row The row's key. + /// @return The row; null for one the field does not hold. + [[nodiscard]] forms::RowState* rowOf(Key const& row) const { return _rowsSource->row(row); } + + /// @brief The forms control of the cell's field. + /// @param key The row's key. + /// @param column The column's id. + /// @return The editor; a muted text for a cell with no field. + [[nodiscard]] Node editor(Key const& key, std::string_view column) override; + + /// @brief Whether the cell's field is a Boolean. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` for a Boolean. + [[nodiscard]] bool toggles(Key const& key, std::string_view column) const override; + + /// @brief `cellReadOnly` over the cell's field. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` when read-only. + [[nodiscard]] bool readOnly(Key const& key, std::string_view column) const override; + + /// @brief Whether another row's span covers a cell: the rows below the spanning cell's, up to its `rows`, and + /// the columns `cutColumns` gives it over the layout. Spans apply only while the grid is unsorted and under + /// its windowing thresholds (`Virtualization`'s defaults). Untracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` when covered; the spanning cell itself is not. + [[nodiscard]] bool covered(Key const& key, std::string_view column) const override; + + /// @brief The spans a row gives while spans apply, each cut over the layout. + /// @param key The row's key. + /// @return The spans; none while the grid is sorted or past its thresholds. + [[nodiscard]] std::vector spans(Key const& key) const override; + + /// @brief Whether `setSpans` gave spans. + /// @return `true` once it did. + [[nodiscard]] bool spanning() const override { return static_cast(_spansOf); } + + /// @brief Gives the rows' spans: each row's cells that cover the cells below and beside them. + /// @param spansOf A row's spans, read untracked; empty: no spans. + void setSpans(std::function(forms::RowState const&)> spansOf); + + /// @brief The cell's draft. Untracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The draft. + [[nodiscard]] std::string draft(Key const& key, std::string_view column) const override; + + /// @brief The cell's text: a display column's value, a draft while blank or not encoding, else the value at the + /// field's places. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The text. + [[nodiscard]] std::string text(Key const& key, std::string_view column) const override; + + /// @brief Why the cell's value is refused: its draft does not encode, or the last submission refused it. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The forms error's message, else the refusal's; empty for none. + [[nodiscard]] std::optional error(Key const& key, std::string_view column) const override; + + /// @brief Writes a user's draft into the cell's field. + /// @param key The row's key. + /// @param column The column's id. + /// @param draft The draft. + void write(Key const& key, std::string_view column, std::string draft) override; + + /// @brief An edit is meant: the form's derived values follow (`forms::FormSession::noteCommit`), then the observer + /// `onCommitted` gave is told. + void committed() override; + + /// @brief A cell's editor opened: its field fetches its options from now on (`forms::FieldState::openOptions`). + /// @param key The row's key. + /// @param column The column's id. + void editorOpened(Key const& key, std::string_view column) override; + + /// @brief Whether the form's derived values are the last ones loaded before a failure. Tracked. + /// @return `forms::FormSession::deriveFailing`: from a failed round until a round succeeds, a retry in flight + /// included. + [[nodiscard]] bool deriveFailed() const override { return _form->deriveFailing(); } + + /// @brief Makes one more round of the form's derived values (`forms::FormSession::recalculate`). + void recalculate() override { _form->recalculate(); } + + /// @brief A form's collection takes rows. + /// @return `true`. + [[nodiscard]] bool rowsEditable() const override { return true; } + + /// @brief How many rows the collection holds. Tracked. + /// @return The count. + [[nodiscard]] std::size_t heldRows() const override { return _rowsSource->array().rows().size(); } + + /// @brief The collection's `minItems` and `maxItems`. + /// @return `{minItems or 0, maxItems}`. + [[nodiscard]] std::pair> bounds() const override; + + /// @brief Appends a blank row to the collection (`forms::FieldState::addRow`), below `maxItems`. + /// @return The new row's key; nothing at `maxItems`. + std::optional appendRow() override; + + /// @brief Inserts a blank row into the collection before the row at a view position, below `maxItems`: at that + /// row's place in the record, which the view shows there while it is neither sorted nor filtered. + /// @param position The view position; at or past `rowCount()` the row is appended. + /// @return The new row's key; nothing at `maxItems`. + std::optional insertRow(std::size_t position) override; + + /// @brief Removes rows from the collection in one change (`forms::FieldState::removeRows`), kept until the next + /// removal for `undoRemove`. + /// @param keys The rows' keys. + /// @return `true` when one of them was not blank. + bool removeRows(std::span keys) override; + + /// @brief Puts the rows the last `removeRows` took back where they stood (`forms::FieldState::restoreRows`), while + /// the collection holds what it held after the removal; after any change it does nothing. + void undoRemove() override; + + /// @brief Calls @p observer at the end of each `committed`: a test seam. + /// @param observer The observer; empty for none. + void onCommitted(std::function observer) { _committed = std::move(observer); } + + /// @brief The cell's marks: read-only, modified, and not encoding; a computed or derived member's cell muted while + /// a round of derived values is in flight, and stale from a failed round until a round succeeds. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The marks. + [[nodiscard]] CellMarks marks(Key const& key, std::string_view column) const override; + + /// @brief The key a grid's record holds in `#key`. + /// @param record The record. + /// @return The key; empty for a record without one. + [[nodiscard]] std::optional keyOf(Value const& record) const override; + + /// @brief `forms::FormSession::rowModified` of the row. Tracked. + /// @param key The row's key. + /// @return `true` when modified. + [[nodiscard]] bool rowModified(Key const& key) const override; + + /// @brief The grid's rows. + /// @return They. + [[nodiscard]] GridRows& view() override { return *_rows; } + + /// @brief Holds the row an editor is open on in the view (`GridRows::hold`). + /// @param key The row's key, or nothing to let it go. + void holdRow(std::optional key) override { _rows->hold(std::move(key)); } + + /// @brief Restores the cell's loaded value. + /// @param key The row's key. + /// @param column The column's id. + void revertCell(Key const& key, std::string_view column) override; + + /// @brief Restores the row's loaded values; a row added since the load is removed. + /// @param key The row's key. + void revertRow(Key const& key) override; + + /// @brief Registers @p commit with the form's submit for the source's life, so the form's submit ends an open edit + /// first. + /// @param commit The commit. + void onBeforeSubmit(std::function commit); + + /// @brief How many cells of the grid's columns are modified. Tracked. + /// @return The count. + [[nodiscard]] std::size_t modifiedCount() const { + return countCells([this](forms::FieldState const& state) { return _form->modified(state.path()); }); + } + + /// @brief How many rows are modified. Tracked. + /// @return The count. + [[nodiscard]] std::size_t modifiedRows() const; + + /// @brief How many cells of the grid's columns do not encode, or were refused. Tracked. + /// @return The count. + [[nodiscard]] std::size_t errorCount() const; + + /// @brief The grid's columns. + /// @return They, as given. + [[nodiscard]] std::vector const& gridColumns() const noexcept { return _columns; } + + /// @brief A cell as its column's filter reads it: the cell of the column's kind and the column. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The cell and its column, the column's id that of the rows' column; nothing for a display column or a + /// row the field does not hold. + [[nodiscard]] std::optional> filterCell(Key const& key, + std::string_view column) const; + +private: + // Whether the collection holds `maxItems` rows already. + [[nodiscard]] bool atMost() const; + + [[nodiscard]] GridColumn const* columnOf(std::string_view columnId) const; + + // A column with an edit: a member it names, or one per row. + [[nodiscard]] static bool edits(GridColumn const& column) { return column.fieldOf || !column.field.empty(); } + + // The member a column edits in a row; null for none. + [[nodiscard]] static forms::FieldState* memberOf(GridColumn const& column, forms::RowState const& row); + + // The columns' overlays per row, onto each row's member: its places, its entry unit, its options and its + // placeholder. Rerun when a row, an overlay's reads or the member a row's column edits changes. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): applies each column's overlay to each row's member in one pass over the rows; the places, entry unit, options and placeholder steps read the same row state + void applyOverlays(); + + // A row's `unit` overlay onto its member (`detail::applyUnitOverlay`). + void applyUnit(forms::FieldState& state, std::optional const& unit, + std::vector>& asLoaded) { + detail::applyUnitOverlay(_unitApplied, state, unit, asLoaded); + } + + template + [[nodiscard]] std::size_t countCells(Test test) const { + std::size_t count = 0; + for (auto const& row : _rowsSource->array().rows()) { + for (GridColumn const& column : _columns) { + forms::FieldState const* const state = memberOf(column, *row); + count += state != nullptr && test(*state) ? 1U : 0U; + } + } + return count; + } + + // The cells the spans cover and the spans each row gives, as of a snapshot of the rows, the layout and the sort. + struct Coverage { + std::shared_ptr snapshot; + std::vector layout; + bool sorted = false; + std::unordered_map> covered; + std::unordered_map> given; + }; + + // The coverage of the rows now, computed again once the rows, the layout or the sort changed. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): rows, their spans, and the cells each covers. + [[nodiscard]] Coverage const& coverageNow() const; + + forms::FormSession* _form; + std::weak_ptr _formAlive; + std::string _arrayPath; + std::vector _columns; + std::function(forms::RowState const&)> _spansOf; + mutable std::optional _coverage; + FormatContext _format; + reactive::Signal _formatVersion; + // Moves with each change of `_layout`, which a drawn span's columns follow. + reactive::Signal _layoutVersion; + std::vector _layout; + std::shared_ptr _rowsSource; + std::unique_ptr _rows; + std::function _committed; + std::optional _hook; + // The unit each member's `unit` overlay last gave, by the member's path; a member it never reached has none. + std::unordered_map> _unitApplied; + std::unique_ptr _overlays; + // The rows the last removal took, and what the collection held right after it: an undo puts them back only while + // it still holds that. + std::vector _removed; + std::string _afterRemove; +}; + +/// @brief One cell of a fixed grid's row: a field of the form it edits, an expression it shows, or a literal text. +/// +/// A cell with `field` edits that field; a cell without one is read-only and shows `value`, else `text`. +struct FixedCell { + /// @brief The path of the form field the cell edits (`limits.density.min`); in a block, relative to the block's + /// row, so `mass` is `specimens#.mass`. Empty for a cell that shows `value` or `text`. + std::string field; + /// @brief What a `{value}` cell shows, read with the block's row, null outside a block. Tracked. + std::function value; + /// @brief What a `{text}` cell shows. + std::string text; + /// @brief How many rows the cell covers, its own included, downwards. + std::size_t rows = 1; + /// @brief How many columns the cell covers, its own included, to the right in the layout. + std::size_t columns = 1; + /// @brief Whether the cell is read-only beyond its field (`CellFacts::overlayReadOnly`), read with the block's + /// row, + /// null outside a block. Tracked. + std::function readonly; + /// @brief The entry places of the cell's field, which are also its wire `dp`, read with the block's row, null + /// outside a block; nothing keeps the field's. Tracked. + std::function(forms::RowState const*)> decimals; + /// @brief The unit the cell's field is entered in, an id of its `FieldSpec::units`, read with the block's row, + /// null + /// outside a block; applied as a grid column's `unit` overlay is (`GridColumn::unit`). Tracked. + std::function(forms::RowState const*)> unit; + /// @brief The options the cell's field offers, as their values' JSON literals, narrowing a choice's, read with the + /// block's row, null outside a block; nothing offers every option. Tracked. + std::function>(forms::RowState const*)> options; + /// @brief The cell's field's placeholder, read with the block's row, null outside a block; empty keeps the + /// field's. + /// Tracked. + std::function placeholder; +}; + +/// @brief One row of a fixed grid: its key, its label and its cells by column id. +struct FixedRow { + /// @brief The row's key, unique among the grid's parts. + std::string key; + /// @brief The row's name: what an assistive technology reads for it. + std::string label; + /// @brief The row's cells, by column id; a column with no cell here shows nothing and takes no edit. + std::map> cells; +}; + +/// @brief Rows of a fixed grid repeated for each row of a form's `ObjectArray` field. +struct FixedBlock { + /// @brief The path of the collection the rows repeat over. + std::string forEach; + /// @brief The rows repeated for each of its rows, in order; a cell's `field` is relative to that row. + std::vector rows; +}; + +/// @brief A fixed grid: rows a standard or a specification fixes, each cell its own field of a form, of its own kind, +/// places and editor. +/// +/// Every row is held, so `keyAt` is never empty below `rowCount`. A fixed row's key is its `FixedRow::key`; a block +/// row's is the collection row's key and the part's joined, `"/"`, so it stays the same while rows of +/// the collection are added and removed. The rows are in the parts' order, a block's in its collection's order, and +/// are never sorted, filtered or rearranged; the columns may be hidden and resized. Spans always apply. A cell with no +/// field is read-only. +class MORPH_API FixedGridSource final : public GridSource { +public: + /// @brief A part of a fixed grid: a row, or a block of rows. + using Part = std::variant; + + /// @brief A fixed grid. + /// @param runtime The runtime its state is tracked on, and whose owner its rows are delivered on. Borrowed. + /// @param form The form whose fields the cells edit; null for a grid of `value` and `text` cells only. + /// Borrowed: + /// it must outlive the source. + /// @param rows The parts, in order. + /// @param columns The columns, each id once: only their ids and labels are read. + /// @param format How values are shown. + /// @throws std::invalid_argument when a key is empty, holds a `/` or is given twice, a cell names a field with + /// @p form null or a field the form does not have, or a block repeats over no collection of the form. + FixedGridSource(reactive::Runtime& runtime, forms::FormSession* form, std::vector rows, + std::vector columns, FormatContext format); + + FixedGridSource(FixedGridSource const&) = delete; + FixedGridSource& operator=(FixedGridSource const&) = delete; + FixedGridSource(FixedGridSource&&) = delete; + FixedGridSource& operator=(FixedGridSource&&) = delete; + + /// @brief Stops watching the collections and removes the commit `onBeforeSubmit` registered. + ~FixedGridSource() override; + + /// @brief The rows; the collections' rows are taken in first. + /// @return The count. + [[nodiscard]] std::size_t rowCount() const override; + + /// @brief The key at a position; the collections' rows are taken in first. + /// @param viewRow The position. + /// @return The key; empty past the rows. + [[nodiscard]] std::optional keyAt(std::size_t viewRow) const override; + + /// @brief Where a key's row is; the collections' rows are taken in first. + /// @param key The key. + /// @return The position, or nothing. + [[nodiscard]] std::optional positionOf(Key const& key) const override; + + /// @brief The visible columns in layout order. + /// @return The ids, as `setLayout` gave them; every column in declared order before it. + [[nodiscard]] std::vector columns() const override { return _layout; } + + /// @brief Shows the cells in another formatting from now on: a mounted cell's text follows. + /// @param format How values are shown. + void setFormat(FormatContext format); + + /// @brief Sets the visible columns in layout order: what the walk follows, and what a span is cut over. + /// @param visible The column ids. + void setLayout(std::vector visible); + + /// @brief A cell's field. Tracked through the collections' rows. + /// @param key The row's key. + /// @param column The column's id. + /// @return The field; null for a cell with none, an unknown row or column, or a block row's field its collection + /// row lacks. + [[nodiscard]] forms::FieldState* field(Key const& key, std::string_view column) const; + + /// @brief A row's label. + /// @param key The row's key. + /// @return Its `FixedRow::label`; empty for an unknown row. + [[nodiscard]] std::string label(Key const& key) const; + + /// @brief The forms control of the cell's field. + /// @param key The row's key. + /// @param column The column's id. + /// @return The editor; a muted text for a cell with no field. + [[nodiscard]] Node editor(Key const& key, std::string_view column) override; + + /// @brief Whether the cell's field is a Boolean. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` for a Boolean. + [[nodiscard]] bool toggles(Key const& key, std::string_view column) const override; + + /// @brief `cellReadOnly` over the cell's field and its `readonly` overlay. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` when read-only: always for a `value` or a `text` cell. + [[nodiscard]] bool readOnly(Key const& key, std::string_view column) const override; + + /// @brief Whether a span of another cell covers a cell: the rows below the spanning cell's, up to its `rows`, and + /// the columns `cutColumns` gives it over the layout. Untracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` when covered; the spanning cell itself is not. + [[nodiscard]] bool covered(Key const& key, std::string_view column) const override; + + /// @brief The spans a row's cells give, each cut over the layout. + /// @param key The row's key. + /// @return The spans. + [[nodiscard]] std::vector spans(Key const& key) const override; + + /// @brief Whether a cell spans more than itself. + /// @return `true` when one does. + [[nodiscard]] bool spanning() const override; + + /// @brief The cell's draft. Untracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The draft; empty for a cell with no field. + [[nodiscard]] std::string draft(Key const& key, std::string_view column) const override; + + /// @brief The cell's text: a `text` cell's text, a `value` cell's value, a field's draft while blank or not + /// encoding, else its value at the field's places. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The text. + [[nodiscard]] std::string text(Key const& key, std::string_view column) const override; + + /// @brief Why the cell's value is refused: its draft does not encode, or the last submission refused it. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The forms error's message, else the refusal's; empty for none. + [[nodiscard]] std::optional error(Key const& key, std::string_view column) const override; + + /// @brief Writes a user's draft into the cell's field. + /// @param key The row's key. + /// @param column The column's id. + /// @param draft The draft. + void write(Key const& key, std::string_view column, std::string draft) override; + + /// @brief An edit is meant: the form's derived values follow (`forms::FormSession::noteCommit`). + void committed() override; + + /// @brief A cell's editor opened: its field fetches its options from now on (`forms::FieldState::openOptions`). + /// @param key The row's key. + /// @param column The column's id. + void editorOpened(Key const& key, std::string_view column) override; + + /// @brief Whether the form's derived values are the last ones loaded before a failure. Tracked. + /// @return `forms::FormSession::deriveFailing`; `false` with no form. + [[nodiscard]] bool deriveFailed() const override { return _form != nullptr && _form->deriveFailing(); } + + /// @brief Makes one more round of the form's derived values (`forms::FormSession::recalculate`). + void recalculate() override; + + /// @brief The cell's marks: read-only, modified and not encoding; a computed or derived field's cell muted while a + /// round of derived values is in flight, and stale from a failed round until a round succeeds. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The marks. + [[nodiscard]] CellMarks marks(Key const& key, std::string_view column) const override; + + /// @brief The key a fixed grid's record holds in `#key`. + /// @param record The record. + /// @return The key; empty for a record without one. + [[nodiscard]] std::optional keyOf(Value const& record) const override; + + /// @brief Whether a field cell of the row is modified (`forms::FormSession::modified`). Tracked. + /// @param key The row's key. + /// @return `true` when one is. + [[nodiscard]] bool rowModified(Key const& key) const override; + + /// @brief The rows: one per row, in order, with no sort and no filter. + /// @return They. + [[nodiscard]] EngineRows& view() override; + + /// @brief Restores the cell's loaded value. + /// @param key The row's key. + /// @param column The column's id. + void revertCell(Key const& key, std::string_view column) override; + + /// @brief Restores the loaded values of the row's field cells. + /// @param key The row's key. + void revertRow(Key const& key) override; + + /// @brief Registers @p commit with the form's submit for the source's life, so the form's submit ends an open edit + /// first. Does nothing with no form. + /// @param commit The commit. + void onBeforeSubmit(std::function commit); + + /// @brief How many field cells are modified. Tracked. + /// @return The count. + [[nodiscard]] std::size_t modifiedCount() const { + return countCells([this](forms::FieldState const& state) { return _form->modified(state.path()); }); + } + + /// @brief How many rows have a modified field cell. Tracked. + /// @return The count. + [[nodiscard]] std::size_t modifiedRows() const; + + /// @brief How many field cells do not encode, or were refused. Tracked. + /// @return The count. + [[nodiscard]] std::size_t errorCount() const; + +private: + // A row as shown: its key, its part, the collection row of a block's row, and its cells' fields by column id. + struct Expanded { + Key key; + FixedRow const* row = nullptr; + forms::RowState const* specimen = nullptr; + std::map> fields; + }; + + // The cells the spans cover and the spans each row gives, as of an expansion and a layout. + struct Coverage { + std::uint64_t expansion = 0; + std::vector layout; + std::unordered_map> covered; + std::unordered_map> given; + }; + + // Each block's collection rows, by key and identity: a change of either is a change of the block's rows. + using BlockRows = std::vector>>; + + [[nodiscard]] static std::span rowsOf(Part const& part); + + // The field spec at a path below some fields' specs; null for none. + [[nodiscard]] static forms::FieldSpec const* specAt(std::span fields, + std::string_view path); + + [[noreturn]] static void refuse(std::string why) { + throw std::invalid_argument{"morph::ui::FixedGridSource: " + std::move(why)}; + } + + // Keys are given once and not empty, and every field a cell names is the form's. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one refusal per rule of a part. + void checkParts() const; + + // Each block's collection rows now. Tracked: a reader follows a change of a block's rows. + [[nodiscard]] BlockRows blockRows() const; + + // The rows from the parts and the collections' rows now, given to the rows' source as one reset. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): rebuilds the rows from the parts and the collections in one pass, each part kind appending in the order the document lists them + void expand() const; + + // Takes in the collections' rows when a block's changed, and the engine the reset at once. + void sync() const; + + // A change of a block's rows is taken in at the next turn of the owner, so the mount hears it without a read. + void watch(); + + [[nodiscard]] Expanded const* expandedOf(Key const& key) const; + + // A cell's part and its block's collection row; null for no cell. + [[nodiscard]] std::pair cellOf(Key const& key, + std::string_view column) const; + + // Each field cell's overlays onto its field: its places, its entry unit, its options and its placeholder. Rerun + // when a block's rows, an overlay's reads or the form's load count change. A load sets a field's unit afresh, so + // the units the overlays gave an unmodified field before it are forgotten and given again as loaded. A switch as + // loaded is no load and moves no load count, so no grid takes another grid's switch for a load, whatever units + // they give. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per overlay. + void applyOverlays(); + + template + [[nodiscard]] std::size_t countCells(Test test) const { + sync(); + std::size_t count = 0; + for (Expanded const& row : _expanded) { + for (auto const& [column, state] : row.fields) { + count += state != nullptr && test(*state) ? 1U : 0U; + } + } + return count; + } + + // The coverage of the rows now, computed again once the rows or the layout changed. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): recomputes the coverage once from the rows and the layout; the span walk and the cache check share the running coverage + [[nodiscard]] Coverage const& coverageNow() const; + + reactive::Runtime* _rt; + forms::FormSession* _form; + std::weak_ptr _formAlive; + std::vector _parts; + std::vector _columns; + FormatContext _format; + reactive::Signal _formatVersion; + // Moves with each change of `_layout`, which a drawn span's columns follow. + reactive::Signal _layoutVersion; + std::vector _layout; + std::shared_ptr _data; + std::unique_ptr _rows; + // The rows as shown, their positions by key, the collections' rows they were expanded from, and a count that moves + // with each expansion. + mutable std::vector _expanded; + mutable std::unordered_map _index; + mutable BlockRows _blockRows; + mutable std::uint64_t _expansion = 0; + mutable std::optional _coverage; + std::optional _hook; + // The unit each field's `unit` overlay last gave, by the field's path, and the form's load count it was given at. + std::unordered_map> _unitApplied; + std::uint64_t _unitGeneration = 0; + bool _watching = false; + bool _posted = false; + async::CallbackScope _alive; + std::unique_ptr _watch; + std::unique_ptr _overlays; +}; + +/// @brief One column of a model's table as a grid edits it. +struct ModelColumn { + /// @brief The column's id. + std::string id; + /// @brief The action that edits the column's cells; none leaves the column read-only. + std::optional edit; + /// @brief The edit action's form, `forms::FormModel::fromSchema` over the action's input schema; null for a + /// column with no edit. + std::shared_ptr model; + /// @brief The field of `model` the column's cells are: `value` for a `CellEdit`, `values.` for a + /// `RowEdit`; empty for a column with no edit. + std::string path; +}; + +/// @brief When a model's table commits its edits. +enum class EditMode : std::uint8_t { + Cell, ///< Each committed cell is its own request. + Row, ///< A row's committed cells are collected while focus stays in the row, and sent as one request. +}; + +/// @brief What a model's table's cells are edited and shown with. +struct ModelGridContext { + /// @brief The runtime the source's state and its edit sessions are tracked on. Borrowed. + reactive::Runtime* runtime = nullptr; + /// @brief Fetches a choice field's options. + forms::ChoiceFetcher choices; + /// @brief The edit sessions' locale and patterns. + forms::FormSessionOptions session; + /// @brief How a cell's value is shown. + FormatContext format; + /// @brief Whether the principal may run an action: an edit action it may not run leaves its column read-only. + /// Tracked. + std::function may; +}; + +/// @brief The cells of a model's table as a grid edits them: rows the window holds, each editable column's cells the +/// field of its edit action, drafts and their errors held by `table::CellEdits` by row key and column. +/// +/// The rows are the window's view: `keyAt` is empty for a row not fetched yet, which stops a walk there. `view()` is a +/// decorator over the rows that sets their one change slot itself: on each change it first ends the modified marks of +/// every row the change brought (`table::CellEdits::rowFetched`), then calls the handler the mount set on it. The +/// table's own edits are sent through the `CellEdits`' commit function, never as runs of the session, so they make no +/// row busy: a cell being saved is stale, and its row takes further edits, queued behind it. +class MORPH_API ModelGridSource final : public GridSource { +public: + /// @brief A model's table as a grid. + /// @param rows The window's rows; the decorator `view()` owns their change slot from now on. + /// @param edits The table's drafts and commits. Borrowed: it must outlive the source. + /// @param columns Every column the table shows, each with its id; an editable one with its form and field. + /// @param mode When a row's edits are sent. + /// @param context What the cells are edited and shown with. + ModelGridSource(std::shared_ptr rows, table::CellEdits& edits, std::vector columns, + EditMode mode, ModelGridContext context); + + ModelGridSource(ModelGridSource const&) = delete; + ModelGridSource& operator=(ModelGridSource const&) = delete; + ModelGridSource(ModelGridSource&&) = delete; + ModelGridSource& operator=(ModelGridSource&&) = delete; + /// @brief Leaves the rows' change slot and the edits' receiver to whatever set them last: a source mounted after + /// this one may hold them already, and what this one set is refused once it is gone. + ~ModelGridSource() override = default; + + /// @brief The description the rows follow: its key names a record's key, its columns are shown and edited, and + /// the drafts of a column it no longer has are dropped (`table::CellEdits::keepColumns`). + /// @param description The description. + void setDescription(table::TableDescription const& description); + + /// @brief Sets the visible columns in layout order: what the walk follows. + /// @param visible The column ids. + void setLayout(std::vector visible); + + /// @brief Shows the cells in another formatting from now on. + /// @param format How values are shown. + void setFormat(FormatContext format); + + /// @brief Tells every reader of the cells that something they depend on and cannot track changed: the rows' busy + /// and failed states. + void touch() { bump(); } + + /// @brief Rows a keyed fetch named and found none of: their drafts, errors and marks go + /// (`table::CellEdits::rowAbsent`). + /// @param keys The rows' keys. + void rowsAbsent(std::span keys); + + /// @brief A row's key changed: the rows, the drafts, the cells held for the row's request and the focus move + /// what they hold by it. + /// @param from The row's old key. + /// @param destination The row's new key. + void moveKey(Key const& from, Key const& destination); + + /// @brief A cell's draft while one is held, for a cell view that shows it in place of the row's value. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The draft; nothing while none is held. + [[nodiscard]] std::optional heldDraft(Key const& key, std::string_view column) const; + + /// @brief A cell's held draft as its cell shows it: a `Measure` column's with its field's unit, since the column's + /// other cells name their own. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The text; nothing while no draft is held. + [[nodiscard]] std::optional heldText(Key const& key, std::string_view column) const; + + /// @brief The view's rows, fetched or not. + /// @return `TableRows::total().rows`. Tracked. + [[nodiscard]] std::size_t rowCount() const override; + + /// @brief The key of the row at a view position. Tracked: it answers once the row arrives. + /// @param viewRow The position. + /// @return The key; empty while the row is not fetched. + [[nodiscard]] std::optional keyAt(std::size_t viewRow) const override; + + /// @brief Where a key's row is in the view among the rows held. The index is read from the rows' held ranges, a + /// bounded window of a model's table, once per change of the rows. + /// @param key The key. + /// @return The position; empty when no held row has the key. + [[nodiscard]] std::optional positionOf(Key const& key) const override; + + /// @brief The visible columns in layout order. + /// @return The ids. + [[nodiscard]] std::vector columns() const override { return _layout; } + + /// @brief The forms control of the cell's field, its session loaded with the cell's draft or the row's value. + /// @param key The row's key. + /// @param column The column's id. + /// @return The editor; a muted text for a column with no edit. + [[nodiscard]] Node editor(Key const& key, std::string_view column) override; + + /// @brief Whether the cell's field is a Boolean. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` for a Boolean. + [[nodiscard]] bool toggles(Key const& key, std::string_view column) const override; + + /// @brief `cellReadOnly` over the cell's field, whether the principal may run its edit action, its + /// `EditInfo::readonly` companion, the row's busy and locked states and whether the cell is loaded. + /// Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` when read-only. + [[nodiscard]] bool readOnly(Key const& key, std::string_view column) const override { + return cellReadOnly(factsOf(key, column)); + } + + /// @brief No cell of a model's table is covered. + /// @param key Unused. + /// @param column Unused. + /// @return `false`. + [[nodiscard]] bool covered(Key const& key, std::string_view column) const override; + + /// @brief The cell's draft: the open editor's text, else the draft held, else the row's value as its field shows + /// it for editing. Untracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The draft; empty for a column with no edit. + [[nodiscard]] std::string draft(Key const& key, std::string_view column) const override; + + /// @brief The cell's text: its draft while one is held, else the row's value as the column shows it. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The text. + [[nodiscard]] std::string text(Key const& key, std::string_view column) const override; + + /// @brief Why the cell's value is refused: its draft does not encode, or the edit action refused it. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The message; empty for none. + [[nodiscard]] std::optional error(Key const& key, std::string_view column) const override; + + /// @brief Writes a user's draft into the cell: its field takes it, and the draft is held with the field's error. + /// A draft that is the row's own value again is no draft. + /// @param key The row's key. + /// @param column The column's id. + /// @param draft The draft. + void write(Key const& key, std::string_view column, std::string draft) override; + + /// @brief An edit is meant: each cell written since the last commit is held with its encoding and, when it + /// encodes and the cell takes edits, sent as its own request (`EditMode::Cell`) or kept for its row's + /// request (`EditMode::Row`). + void committed() override; + + /// @brief A cell's editor opened: its session is loaded with the cell, and a choice fetches its options. + /// @param key The row's key. + /// @param column The column's id. + void editorOpened(Key const& key, std::string_view column) override; + + /// @brief The cell's marks: read-only, modified from its commit's success until its row's next fetch, refused, + /// and stale while its commit is out. Tracked. + /// @param key The row's key. + /// @param column The column's id. + /// @return The marks. + [[nodiscard]] CellMarks marks(Key const& key, std::string_view column) const override; + + /// @brief The key a record holds in the description's key column. + /// @param record The record. + /// @return The key; empty for a record without one, or before a description. + [[nodiscard]] std::optional keyOf(Value const& record) const override; + + /// @brief Whether some cell of the row is modified or holds a draft. Tracked. + /// @param key The row's key. + /// @return `true` when one does. + [[nodiscard]] bool rowModified(Key const& key) const override; + + /// @brief The decorator over the rows the mount is handed. + /// @return It. + [[nodiscard]] TableRows& view() override { return *_view; } + + /// @brief Why typing on a read-only cell is refused: the cell is not loaded, the row is being saved, or the row + /// is locked, in that order. + /// @param key The row's key. + /// @param column The column's id. + /// @return The status line's text; nothing for any other read-only cell. + [[nodiscard]] std::optional refusal(Key const& key, std::string_view column) const override; + + /// @brief Focus moved: in `EditMode::Row` the cells held for every other row are sent, a request per row. + /// @param key The row focus is on now; nothing when it is on none. + void focusRow(std::optional const& key) override; + + /// @brief `Ctrl+Enter`: every row's held cells are sent. + void commitHeld() override; + + /// @brief A model's table selects rows, not rectangles of cells: it takes no paste and no fill. + /// @return `false`. + [[nodiscard]] bool selectsCells() const override { return false; } + + /// @brief Keeps what moves the focus with a row's key. + /// @param link The controller's side. + void followFocusWith(FocusLink link) override { _focus = std::move(link); } + + /// @brief Keeps what brings focus back to the first refused cell of a row commit in `EditMode::Row`. + /// @param refocus Focuses a cell while the table has focus. + void refocusWith(std::function refocus) override { _refocus = std::move(refocus); } + + /// @brief Whether a cell's draft was refused when its row's held cells were sent, so its next commit sends it. + /// @param key The row's key. + /// @param column The column's id. + /// @return `true` until the cell is committed again. + [[nodiscard]] bool resends(Key const& key, std::string_view column) const override; + + /// @brief A held cell's refusal when its row became read-only for no reason the cell can name. + static constexpr std::string_view kReadOnlyText = "This cell is read-only"; + /// @brief The status line's refusal of typing on a cell not loaded yet. + static constexpr std::string_view kUnloadedText = "This value is not loaded yet"; + /// @brief The status line's refusal of typing on a measure in a unit its field cannot hold. + static constexpr std::string_view kForeignUnitText = "This value's unit cannot be edited here"; + /// @brief The status line's refusal of typing in a row another run is saving. + static constexpr std::string_view kBusyText = "This row is being saved"; + +private: + // An editable column's form: its session, the row it is loaded with, and its field's text for that row's value. + struct Session { + std::unique_ptr form; + std::optional loadedFor; + std::string base; + }; + + // A held row: its view index and its record, valid until the rows' next change. + struct Located { + std::int64_t index = 0; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members): a view of a record the source holds for the length of the call that returns it; copying the record would defeat the lookup + Value const& record; + }; + + // The rows the mount reads: the window's, with their one change slot set here. + class MORPH_API Rows final : public TableRows { + public: + explicit Rows(ModelGridSource& source) : _source{&source}, _inner{source._rows.get()} { + _inner->onChange(source._alive.guard([this](table::ViewChange const& change) { changed(change); })); + } + + Rows(Rows const&) = delete; + Rows& operator=(Rows const&) = delete; + Rows(Rows&&) = delete; + Rows& operator=(Rows&&) = delete; + ~Rows() override = default; + + [[nodiscard]] TableTotal total() const override { return _inner->total(); } + [[nodiscard]] TableTotal mountedTotal() const override { return _inner->mountedTotal(); } + [[nodiscard]] std::optional row(std::int64_t index) const override { return _inner->row(index); } + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override { + return _inner->unloadedLevels(index); + } + void visible(std::int64_t first, std::int64_t count, std::span columns) override { + _inner->visible(first, count, columns); + } + async::Completion, table::TableError>> keysOf( + std::int64_t first, std::int64_t count) override { + return _inner->keysOf(first, count); + } + void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) override { + _inner->locateRow(std::move(key), std::move(stop), std::move(done)); + } + async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) override { + return _inner->fetchRows(std::move(keys), std::move(columns)); + } + std::expected setSort(SortChain sort) override { + return _inner->setSort(std::move(sort)); + } + std::expected setFilter(table::FilterSpec filter) override { + return _inner->setFilter(std::move(filter)); + } + async::Completion> distinctValues( + table::DistinctRequest request) override { + return _inner->distinctValues(std::move(request)); + } + [[nodiscard]] TableCountsView counts() const override { return _inner->counts(); } + [[nodiscard]] std::expected selectView() const override { + return _inner->selectView(); + } + [[nodiscard]] SelectedCount selectedCount(TableSelection const& selection) const override { + return _inner->selectedCount(selection); + } + [[nodiscard]] bool leftView(table::RowId const& key) const override { return _inner->leftView(key); } + [[nodiscard]] RetainResult retain(std::span keys) override { return _inner->retain(keys); } + void clearRetained() override { _inner->clearRetained(); } + [[nodiscard]] bool unmatched(table::RowId const& key) const override { return _inner->unmatched(key); } + void holdRefetches(std::uint64_t run) override { _inner->holdRefetches(run); } + void releaseRefetches(std::uint64_t run) override { _inner->releaseRefetches(run); } + async::Completion, table::TableError>> rowsOf( + std::int64_t first, std::int64_t count, std::span columns) override { + return _inner->rowsOf(first, count, columns); + } + [[nodiscard]] RowStates& states() override { return _inner->states(); } + [[nodiscard]] RowStates const& states() const override { return _inner->states(); } + [[nodiscard]] std::vector> heldRanges() const override { + return _inner->heldRanges(); + } + void moveKey(table::RowId const& from, table::RowId const& target) override { _source->moveKey(from, target); } + void onChange(std::function handler) override { + _handler = std::move(handler); + } + + private: + // The rows a change brought are fetched: their modified marks end before anything reads the rows, then the + // mount hears the change. + void changed(table::ViewChange const& change); + + ModelGridSource* _source; + TableRows* _inner; + std::function _handler; + }; + + // The view indices, after the whole change, of the rows its `Inserted` and `Changed` operations brought. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): walks the change's operations once, shifting the collected indices as each insert or removal passes; the shift depends on the operation kind + [[nodiscard]] static std::vector broughtRows(table::ViewChange const& change); + + void bump() { _version.set(_version.peek() + 1); } + + [[nodiscard]] ModelColumn const* columnOf(std::string_view columnId) const; + + [[nodiscard]] table::TableColumn const* describedColumn(std::string_view columnId) const; + + [[nodiscard]] Session const* sessionOf(std::string_view column) const; + + [[nodiscard]] forms::FieldState* fieldOf(std::string_view column) const; + + // The held row with a key: its view index and record. Tracked through the source's version. + [[nodiscard]] std::optional locate(Key const& key) const; + + // Every fact the cell's read-only state follows from. Tracked. + [[nodiscard]] CellFacts factsOf(Key const& key, std::string_view column) const; + + // The column's session loaded with the cell: with the row's value, and then the draft held, unless it holds the + // cell already. Null for a column with no edit. + Session* loaded(Key const& key, std::string_view column); + + // Holds the field's text as the cell's draft, with the field's error; the row's own value again is no draft. + void hold(Key const& key, std::string_view column); + + // The cell's draft, held, and its cell of a request when it encodes and the cell takes edits. A cell that became + // read-only while it was edited is not sent: an edit of a value the user has not seen, or of a row another run is + // saving, would overwrite what arrives. + std::optional encode(Key const& key, std::string const& column); + + // Sends a row's held cells as one request. A cell that became read-only since it was held (its row busy with + // another run, locked, or not loaded) is not sent: it keeps its draft, as an edit refused at the cell does. + void send(Key const& row); + + // A row commit settled: the cells follow, and in `EditMode::Row` a refusal brings focus back to the row's first + // refused cell in layout order. + void rowSettled(table::RowId const& row, bool refused); + + // A record's value as its field's wire form. A `Date` cell is `YYYY-MM-DD` text and a `DateTime` cell a timestamp, + // which a `Date` or `DateTime` field reads as it is; an `EpochDate` field reads days and an `EpochDateTime` field + // seconds, so those are counted from the epoch. A measure is an amount in its own unit and a `Quantity` field's + // value an amount in its canonical unit: the amount is converted through the description's units, and one the + // units cannot convert opens blank rather than as a figure in the wrong unit. + [[nodiscard]] std::string wireOf(Value const& value, forms::FieldSpec const& spec) const; + + // A measure's amount in its `Quantity` field's canonical unit, through the description's units; nothing when they + // cannot convert it (a unit they lack, another dimension), so the cell is read-only. + [[nodiscard]] std::optional inFieldUnit(Quantity const& measure, + forms::FieldSpec const& spec) const; + + // A record's value as a cell of its column. + [[nodiscard]] static table::Cell cellOf(Value const* value); + + std::shared_ptr _rows; + table::CellEdits* _edits; + std::vector _columns; + EditMode _mode; + ModelGridContext _context; + reactive::Runtime* _rt; + reactive::Signal _version; + // The cell whose editor is open, or whose text was written last: its field holds its text. + reactive::Signal> _open; + std::vector _layout; + std::optional _description; + std::map> _sessions; + // Cells written since the last commit, and the cells each row holds for its request in `EditMode::Row`. + std::vector _dirty; + std::map> _held; + std::function _refocus; + FocusLink _focus; + // Cells refused when their row's held cells were sent, which their next commit sends. + std::vector _resend; + // The description's units, through which a measure is converted into its field's unit. + std::shared_ptr _units; + // The held rows' view indices by key, as of a count of the rows' changes: the cells' own changes do not move rows. + std::uint64_t _rowsVersion = 0; + mutable std::unordered_map _positions; + mutable std::optional _positionsVersion; + async::CallbackScope _alive; + std::unique_ptr _view; +}; + +/// @brief A grid's focus, its cell editor and its walk over a `GridSource`, and the table node that shows them. +/// +/// The editor's text is the cell's draft, live: an opening keeps the draft the cell held, a commit closes the editor +/// and calls `GridSource::committed` once when the draft changed, and `Escape` writes the kept draft back. A paste, a +/// fill, a clear and each row operation is one change too: it calls `GridSource::committed` once, however many cells +/// or rows it touches. +class MORPH_API GridController : public std::enable_shared_from_this { +public: + /// @brief A controller over a source. + /// @param runtime The runtime its state is tracked on. Borrowed. + /// @param source The source. Borrowed: it must outlive the controller. + /// @param options The walk and the activation. + GridController(reactive::Runtime& runtime, GridSource& source, GridOptions options); + + GridController(GridController const&) = delete; + GridController& operator=(GridController const&) = delete; + GridController(GridController&&) = delete; + GridController& operator=(GridController&&) = delete; + /// @brief Takes back what the source was given to move focus with. + ~GridController(); + + /// @brief The focused cell. Tracked. + /// @return The cell when its row is fetched; empty when nothing has focus or focus stands on a placeholder. + [[nodiscard]] std::optional focus() const; + + /// @brief The focus as the mount shows it, what `Table::gridFocus` binds. Tracked. + /// @return `{key, view position, column}` for a focused cell, `{none, view row, column}` while the walk stopped at + /// a + /// row not fetched yet, which takes its key once the source answers for it. + [[nodiscard]] std::optional place() const; + + /// @brief Takes the cell a click or a key resolved to: `focusCell` for a fetched row, else the placeholder focus. + /// @param target The cell. + void focusPlace(GridFocus target); + + /// @brief Focuses a cell, as a click or an arrow does; a covered cell, and a key the view does not hold, are + /// refused. An open editor on another cell is committed first. The status line shows the cell's error while + /// it has focus. A cell outside the cell selection ends it. + /// @param cell The cell. + void focusCell(CellRef cell); + + /// @brief What `Enter` and `F2` with no editor, and a double click, do: focuses the cell, then opens its editor + /// holding the value on an editable cell (none for a Boolean), or runs `GridOptions::onActivate` on a + /// read-only one. + /// @param cell The cell. + void activate(CellRef cell); + + /// @brief The cell whose editor is open. Tracked. + /// @return The cell, or none. + [[nodiscard]] std::optional editing() const { return _editing.get(); } + + /// @brief The chords the table declares, what `Table::keyChords` binds. Tracked. + /// @return With an editor open exactly `Enter`, `Tab`, `Shift+Tab`, `Escape` and `Ctrl+Enter`, so every other key + /// reaches the editor; with none, also `F2`, `Space`, `Delete`, `Shift` with an arrow, `Ctrl+A`, `Ctrl+V`, + /// `Ctrl+D`, `Ctrl+Shift+=` and `Ctrl+-`. `Ctrl+C` is the table's own copy key, which copies `copy()`. + [[nodiscard]] std::vector keyChords() const; + + /// @brief A chord pressed while the table has focus. + /// @param chord The chord. + /// @return `FocusNext` or `FocusPrevious` when `Tab` or `Shift+Tab` runs past the last or the first editable cell, + /// `Ignored` for a chord the grid does not take, else `Handled`. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): dispatches one chord across the focus, editing, selection and clipboard states; each branch checks the state the one before left + KeyOutcome press(std::string_view chord); + + /// @brief Printable text: with an editor open, the editor's whole new text, as its input writes it; on a focused + /// cell with none, the cell's draft is kept, @p text written as the draft and the editor opened. A + /// read-only cell refuses it in the status line. + /// @param text The text. + void type(std::string_view text); + + /// @brief Focus left the table: an open editor is committed, and the source hears that focus is on no row. + void leave(); + + /// @brief The latest transient refusal or notice, else the focused cell's error while it has one. Tracked. + /// @return The text; empty for none. + [[nodiscard]] std::string message() const; + + /// @brief How many refusals and notices were given: it moves on each, so one equal to the last is posted again. + /// Tracked. + /// @return The count. + [[nodiscard]] std::uint64_t notices() const { return _notices.get(); } + + /// @brief A click on a cell: focuses it, and flips a Boolean's. + /// @param cell The cell. + void click(CellRef const& cell); + + /// @brief The choices the latest notice offers. Tracked. + /// @return The entries. + [[nodiscard]] std::vector const& messageEntries() const { return _messageEntries.get(); } + + /// @brief A state that lasts while its source holds: `kDeriveFailedText` from a failed round of derived values + /// until + /// a round succeeds, a retry in flight included. Tracked. + /// @return The text; empty for none. + [[nodiscard]] std::string standing() const; + + /// @brief The choices the standing state offers: "Recalculate" (`recalculate`) while a round of derived values + /// failed. Tracked. + /// @return The entries. + [[nodiscard]] std::vector standingEntries() const; + + /// @brief An entry chosen in the status line: `recalculate` makes one more round of derived values, `undo` puts + /// back the rows the last deletion removed (`undo`). + /// @param entryId The entry's id; one the grid does not offer is ignored. + void chooseEntry(std::string_view entryId); + + /// @brief The grid's entries of a cell's menu: "Revert cell", enabled while the cell is modified, and "Revert + /// row", + /// enabled while the row is modified, each restoring the loaded value and then committing once; then, + /// unless the rows are fixed, a separator and the row entries (`rowEntries`). + /// @param row The row's key. + /// @param column The column's id. + /// @return The entries. + [[nodiscard]] std::vector cellEntries(Key const& row, std::string_view column); + + /// @brief The row entries of a row's menus: "Insert row above", "Insert row below" and "Delete row", or "Delete + /// rows" when the cell selection spans more than one row and @p row is among them, deleting every row it + /// spans. An insertion is disabled at `maxItems` and a deletion where it would leave fewer than `minItems`, + /// each with the bound as its description. Each is one change. + /// @param row The row's key. + /// @return The entries; none while the rows are fixed. + [[nodiscard]] std::vector rowEntries(Key const& row); + + /// @brief The cell selection. Tracked. + /// @return The range by its corners; none while no cell range is selected. + [[nodiscard]] std::optional selection() const { return _selection.get(); } + + /// @brief Copies the summary rows a rectangle spans with the data rows (`copy`): the rows the grid is mounted + /// over, + /// and a summary cell's text. + /// @param rows The summary rows over this grid's rows; null copies data rows only. + /// @param text A summary row's cell text, by its record and its column's id. + void copySummaries(std::shared_ptr rows, + std::function text); + + /// @brief Selects a range of cells, or none; focus stays where it is. + /// @param range The range by its corners, or nothing. + void select(std::optional range) { setSelection(std::move(range)); } + + /// @brief The cells of the selection, else the focused cell, as clipboard text. + /// @return Each cell's display text, tab-separated, a line per row in view order and the columns in layout order; + /// a tab or a line break inside a cell written as a space. Empty when no cell is selected or focused. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): builds the clipboard text for the selection or the focus in one walk over the rows and the columns in layout order + [[nodiscard]] std::string copy() const; + + /// @brief Why a copy of the selection, else of the focused cell, is refused: it spans more than + /// `GridOptions::maxCopyRows` rows. + /// @param separator The grouping separator the bound is written with. + /// @return `A copy holds at most {maxCopyRows} rows`; nothing when the copy may go ahead. + [[nodiscard]] std::optional copyRefusal(std::string_view separator = ",") const; + + /// @brief Writes tab-separated text into the grid from the focused cell right and down, the block keeping its + /// shape, as one change; the status line says how many values were written and dropped. + /// + /// Lines split on a line feed, a trailing carriage return removed from each and a final empty line dropped; values + /// split on tabs, each trimmed of spaces. With no focus the block starts at the first row and the first visible + /// column, in a grid with no rows at the first row the paste adds. A line past the last row appends a row while + /// `appendRows` allows and the record holds fewer than `maxItems`, else each of its values is dropped. A value + /// past the last visible column, or on a read-only or covered cell, is dropped. Every other value is written as + /// the cell's draft (`GridSource::write`), all in one batch, then `GridSource::committed` is called once. A block + /// of more than `GridOptions::maxPasteCells` values is refused whole, and nothing is written. + /// @param text The text. + /// @return What the paste did with each value. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): parses the block, writes each value and counts the written and the dropped in one pass; both tallies depend on each cell's outcome + PasteResult paste(std::string_view text); + + /// @brief Copies the first row of the selection, else of the focused cell, into its other rows, editable cells + /// only, as one change. + void fillDown(); + + /// @brief Blanks the editable cells of the selection, else the focused cell, as one change. + void clear(); + + /// @brief Inserts a blank row above or below the focused row, as one change; focus stays where it is. + /// @param below Whether the row goes below the focused one. + void insertRow(bool below); + + /// @brief Deletes the rows the cell selection spans, else the focused row, as one change, at once. When one of + /// them + /// held a value the status line says `Deleted {n} rows` (`Deleted 1 row`) with the entry "Undo" (`undo`). + void deleteRows(); + + /// @brief Puts back the rows the last deletion removed, each where it stood, as one change, while the offer to + /// undo + /// it stands: until the grid's next change, or `GridOptions::undoHold` after the deletion, whichever comes + /// first. Once the offer ends it does nothing. + void undo(); + + /// @brief Which row operations the grid offers now. Tracked. + /// @return Insert and delete of one row, with the bound that stops one; neither while the rows are fixed. + [[nodiscard]] RowOps rowOps() const; + + /// @brief Appends a row and focuses its first editable cell, as one change: what "Add row" under the grid does. + void addRow(); + + /// @brief Calls @p observer with the cell selection after each change of it, whatever made it. + /// @param observer The observer; empty for none. + void onSelectionChange(std::function const&)> observer) { + _selectionObserver = std::move(observer); + } + + /// @brief Gives the grid the clipboard `Ctrl+V` reads. + /// @param read Reads the clipboard's text; nothing when it holds none. + void useClipboard(std::function()> read) { _readClipboard = std::move(read); } + + /// @brief Keeps something alive as long as the controller: what a node it built owns through it. + /// @param kept The thing. + void keepAlive(std::shared_ptr kept) { _kept_alive = std::move(kept); } + + /// @brief The table node over @p columns, wired to this controller: its focus, keys, text, clicks, focus leaving, + /// editor and cell menu. A node built while the controller is owned by a `shared_ptr` keeps it alive. + /// @param columns Every column, hidden ones included, each with its id. + /// @param options The table's other options. Its status is the grid's own messages unless it binds one; its + /// `cellMenu`'s entries are followed by the grid's, before its first separator. + /// @param base A model's table's source, whose rows and cells the grid marks; none for the grid's own rows. + /// @return The node. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one wire per seam of the table. + [[nodiscard]] Node node(std::vector columns, TableOptions options, + std::optional base = std::nullopt); + + /// @brief The status line's refusal of typing on a read-only cell. + static constexpr std::string_view kReadOnlyText = "This cell is read-only"; + /// @brief The standing state while a round of derived values failed. + static constexpr std::string_view kDeriveFailedText = "Derived values could not be recalculated"; + +private: + // The cells a selection, else the focused cell, covers: keys in view order, column ids in layout order. + struct Block { + std::vector keys; + std::vector columns; + }; + + // The selection's rectangle, else the focused cell; nothing when a corner's row is not in the view or its column + // is not visible. Untracked reads of the source. + [[nodiscard]] std::optional block() const; + + // Whether a cell lies in the selection's rectangle. + [[nodiscard]] bool inBlock(CellRef const& cell) const; + + // The rows the selection spans, in view order; none without a selection. + [[nodiscard]] std::vector selectedRows() const; + + // Shift with an arrow: the selection's focus corner moves by a row or a column from where it is, its anchor the + // focused cell when nothing was selected. + void extend(int rows, int columns); + + // Ctrl+A: every cell of the view. + void selectAll(); + + // A paste's lines and values: lines split on LF, a trailing CR removed from each, a final empty line dropped; + // values split on tabs and trimmed of spaces. + [[nodiscard]] static std::vector> pasteLines(std::string_view text); + + // Why no row can be inserted: the record holds `maxItems`. Empty when one can. Tracked. + [[nodiscard]] std::string insertRefusal() const; + + // Why @p count rows cannot be deleted: fewer than `minItems` would be left. Empty when they can. Tracked. + [[nodiscard]] std::string removeRefusal(std::size_t count) const; + + // Inserts a blank row above or below a row, as one change. + void insertAt(Key const& row, bool below); + + // Deletes rows by key, as one change; focus moves to the row now at the focused row's place, and a selection + // whose corner is gone ends. Rows that held a value are said in the status line, with "Undo". + void removeKeys(std::vector const& keys); + + // Focuses the first editable cell of a row in layout order. + void focusFirstEditable(Key const& key); + + // Selects a range, and tells the observer when it changed. + void setSelection(std::optional range); + + // Posts a transient notice, with the choices it offers. One that offers none keeps a live offer to undo a + // deletion: such a notice (a refusal, a paste that wrote nothing) is no change, so the offer still stands. + void notice(std::string text, std::vector entries = {}); + + // A focus move clears a notice, but not one that offers a choice, which lasts until the next change. + void clearNotice(); + + // Ends the offer to undo a deletion, and a notice that offers a choice. + void clearUndo(); + + // A change was made: an earlier deletion is no longer offered for undoing. + void noteChange() { clearUndo(); } + + // Whether no row operation is offered: the rows are fixed, or not the source's to change. + [[nodiscard]] bool fixedRows() const { return _options.rowsFixed || !_source->rowsEditable(); } + + // A row's key changed: the focus and an open editor on it take the new key, at the row's place now. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`from`, `target`): the old key first, which the one call site (the source's move callback) spells out + void keyMoved(Key const& from, Key const& target); + + // Moves the focus, and tells the source when the row it is on changed. + void setPlace(std::optional place); + + // Lets go of the row an editor was open on, once no editor is open: the sort and the filter place it again. + void letGo(); + + // A cell a walk may stop on: editable and not covered. + [[nodiscard]] bool editable(CellRef const& cell) const; + + // Commits an open editor: it closes, and an edit is meant when its draft differs from the one it opened on. + void commit(); + + // Flips a Boolean's cell and commits it. + void toggle(CellRef const& cell); + + // Where a walk lands: an editable cell, a row not fetched yet, or nowhere. + struct Step { + enum class Kind : std::uint8_t { Found, Stop, None } kind = Kind::None; + std::size_t row = 0; + std::string column; + std::optional key; + }; + + // The next editable cell from @p from in the walk's order, by view positions at the moment of the call; a row not + // fetched yet stops the walk. + [[nodiscard]] Step next(std::optional const& from, bool forward) const; + + // Lands on where a walk stopped. + void land(Step const& step); + + // Tab or Shift+Tab: the next editable cell, or out of the table at the ends. Focus on a row not fetched yet moves + // nowhere until the row arrives. + KeyOutcome walkFrom(bool forward); + + // Tab past the last editable cell with `appendRows`: a row is added, as one change, and focus goes to its first + // editable cell. Nothing is added at `maxItems`, or while the rows are fixed. + bool appendOnWalk(); + + // Enter after a commit: down the column, along the row, or nowhere. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the three Enter modes each walk a different axis and share the focus and the editable-cell test + void enterMove(CellRef const& from); + + reactive::Runtime* _rt; + GridSource* _source; + GridOptions _options; + reactive::Signal> _place; + reactive::Signal> _editing; + reactive::Signal _message; + reactive::Signal _notices; + reactive::Signal> _messageEntries; + reactive::Signal _standing; + reactive::Signal> _standingEntries; + reactive::Signal> _selection; + std::function()> _readClipboard; + // The summary rows a copy draws its rows from, and a summary cell's text; empty copies data rows only. + std::shared_ptr _summaries; + std::function _summaryText; + std::function const&)> _selectionObserver; + // Whether the last deletion is offered for undoing, and the timer that ends the offer. + bool _undoOffered = false; + reactive::TimerHandle _undoTimer; + // The draft the open editor's cell held when it opened. + std::string _kept; + // Whether the table has focus: since a click, a key or a move inside it, until focus left it. + bool _hasFocus = false; + // The row the source last heard focus is on. + std::optional _focusedRow; + std::shared_ptr _kept_alive; +}; + +/// @brief A grid of a form, owned whole: the source, the controller, and the node that shows them. +struct FormGrid { + /// @brief The grid's source. + std::shared_ptr source; + /// @brief The grid's controller. + std::shared_ptr grid; + /// @brief The table node; it keeps the controller and the source alive. + Node node; +}; + +/// @brief Builds a grid of a form's collection: the source, the controller over the form's runtime, whose commit of an +/// open editor the form's submit runs first, and the node over one table column per grid column. +/// @param form The form. Borrowed: it must outlive the grid. +/// @param array The collection field. +/// @param columns The grid's columns. +/// @param options The walk and the activation. +/// @param format How values are shown. +/// @param table The table's other options. +/// @param shown The table's columns, one per grid column in its order, each with the grid column's id; empty: each +/// with the grid column's id and label alone. +/// @return The grid. +/// @throws std::invalid_argument when @p array is not a collection of @p form, a column names no member, or @p shown +/// is neither empty nor one per grid column. +[[nodiscard]] MORPH_API FormGrid makeFormGrid(forms::FormSession& form, forms::FieldState const& array, + std::vector columns, GridOptions options, + FormatContext format, TableOptions table = {}, + std::vector shown = {}); + +/// @brief The node of a grid of a form's collection (`makeFormGrid`), for a form's own view. +/// @param form The form. +/// @param array The collection field. +/// @param columns The grid's columns. +/// @param options The walk and the activation. +/// @param format How values are shown. +/// @return The node; it keeps the grid alive. +[[nodiscard]] inline Node formGrid(forms::FormSession& form, forms::FieldState const& array, + std::vector columns, GridOptions options, FormatContext format) { + return makeFormGrid(form, array, std::move(columns), std::move(options), std::move(format)).node; +} + +} // namespace morph::ui diff --git a/include/morph/ui/interpreter.hpp b/include/morph/ui/interpreter.hpp index 99430038f..8d5cd425b 100644 --- a/include/morph/ui/interpreter.hpp +++ b/include/morph/ui/interpreter.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -74,11 +75,25 @@ struct FormSessionOptions; struct FormViewOptions; } // namespace forms +namespace table { +class ITableStateStore; +struct SaveResult; +struct TableColumn; +struct TableDescription; +struct TableStateKey; +} // namespace table + } // namespace morph namespace morph::ui { +class TableStates; + class Mounted; +class GridController; +class ModelGridSource; +struct GridColumn; +struct GridOptions; struct ChartRange; // --------------------------------------------------------------------------------------------------------------- @@ -92,6 +107,11 @@ struct CallOptions { /// @brief The mutation declares `"offline": "queue"`: a dispatcher with an offline queue holds a call that cannot /// reach the server and settles the completion when the replay settles. bool queueOffline = false; + /// @brief The caller's cancel: a stop request sends the wire's `cancel` for the call where the server takes one, + /// and rejects the call with `core::async::OperationCancelled`. A token with no stop state sends nothing. + /// An `evaluate` call ignores it, and so does a call a `QueueingDispatcher` replays. Holding a stop token, + /// `CallOptions` is not a literal type, and a channel built against it before it had one must recompile. + ::core::async::StopToken stop; }; /// @brief What a channel can say about the instance it is bound to. @@ -391,10 +411,64 @@ struct SessionOptions { /// @brief The most bytes a document moves inline in one file (`download` from bytes, `upload` into bytes, a /// field component writing a base64 member); 1 to `kMaxInlineFileBytes`. std::size_t maxInlineFileBytes = kDefaultInlineFileBytes; + /// @brief How long a model-backed table's visible rows must stay within one page before it fetches a page that + /// is not next to one it holds: a scroll that passes over pages fetches none of them. Waited for on + /// `scheduler` and measured on `clock` (`std::chrono::steady_clock` without one), so the two must + /// agree. Without a scheduler every fetch goes at once. + std::chrono::milliseconds tableSettle{80}; + /// @brief While a model-backed table's order waits for a level, the least time between two of its refetches + /// after change events, waited for on `scheduler` and measured on `clock`: the first goes at once, the + /// next no sooner than this after it, whatever the number of events between. + std::chrono::milliseconds tableAwaitedRefetch{250}; + /// @brief Where every table's persisted state is loaded from and saved to; with none, a table keeps its state + /// for as long as it is mounted. `PreferencesTableStateStore` keeps it in the application's preferences + /// store. + std::shared_ptr tableState; + /// @brief How long a table waits for its stored state before its first query; past it the table starts from its + /// defaults. + std::chrono::milliseconds tableStateTimeout{300}; + /// @brief How long a table's arrangement must stay unchanged before its state is saved, waited for on + /// `scheduler`; without one every change saves at once. + std::chrono::milliseconds tableStateDebounce{500}; + /// @brief How long a filter menu waits after the last keystroke of its search, and after the last edit of a + /// condition, before it asks for values or sends the filter, waited for on `scheduler`; without one each + /// goes at once. + std::chrono::milliseconds tableFilterDebounce{250}; + /// @brief The most rows a range selection of a model-backed table resolves; a longer range is refused in the + /// table's status line and selects nothing. + std::size_t maxRangeRows = 10'000; + /// @brief The most rows a table's copy puts on the clipboard; a larger copy is refused in the table's status line. + std::size_t maxCopyRows = 10'000; + /// @brief The most values one paste into a grid writes or drops; a larger block is refused in the grid's status + /// line and nothing is written. + std::size_t maxPasteCells = 10'000; + /// @brief The longest a model-backed table with `retainChanged` holds back the refetches its change events cause + /// while an action of this session that changes it runs, waited for on `scheduler`: within it a row the + /// action changed never leaves the view and comes back, past it other users' changes are not held up. + std::chrono::milliseconds retainHold{2000}; + /// @brief The application's id: the `application` of every table-state key. + std::string application; }; +/// @brief How long a table's status-line message stays, unless the next gesture on the table clears it first. +inline constexpr std::chrono::seconds kStatusMessageHold{6}; + +class Session; + namespace detail { +/// @brief The table states of a session built with @p options: over `tableState`, debounced by `tableStateDebounce` +/// on `scheduler`. A save that does not end `Saved` is said in the status line of every mounted table whose +/// key it names; a `PreferencesTableStateStore` is given the session's scheduler and `tableStateTimeout` to +/// wait on before it sends a save the server refused as busy again. +/// @param session The session the states belong to; its screens hear a failed save. +/// @param runtime The session's runtime, whose owner the states answer on. +/// @param options The session's options. +/// @return They; `nullptr` without a `tableState`. +[[nodiscard]] MORPH_API std::shared_ptr makeTableStates(Session& session, + reactive::Runtime const& runtime, + SessionOptions const& options); + /// @brief The text of a failure. /// @param error The failure. /// @return `what()`, or `unknown error`. @@ -585,6 +659,107 @@ struct HostCommands { /// listed is in scope for every document. using HostScopes = std::map>, std::less<>>; +namespace detail { +struct WatchRegistration; +struct WatchRegistry; +} // namespace detail + +/// @brief A watch of one record that no cache entry holds, made by `Session::watchRecord`. +/// +/// A copyable handle over one registration: the record stays in the session's watch set, and the handler keeps +/// hearing its changes, while any copy lives. When the last copy dies the handler is removed and the record is +/// counted out, which sends an `unwatch` when nothing else needs it. A `Completion` hands its value to a handler as +/// `const&`, so a caller that keeps the watch copies the holder there and lets the completion go. A holder that +/// outlives its session releases nothing. A default-constructed holder holds nothing. The last copy must die on the +/// runtime's owner, since releasing the watch changes the session's watch set. A session destroyed while a +/// `watchRecord` waits for its answer drops that completion unsettled. +class MORPH_API WatchHolder { +public: + /// @brief A holder of nothing. + WatchHolder() = default; + + /// @brief Whether the holder holds a registration. + /// @return `true` for a holder `watchRecord` resolved with, and its copies. + [[nodiscard]] bool holds() const noexcept { return _registration != nullptr; } + +private: + friend class Session; + explicit WatchHolder(std::shared_ptr registration) + : _registration{std::move(registration)} {} + + std::shared_ptr _registration; +}; + +/// @brief A mutation's run as it is sent. +struct RunStarted { + /// @brief The run's id, unique in the session. + std::uint64_t run; + /// @brief The action's id. + // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members): the run's context borrows the action name and body of the call for the call's duration, and the object is built and dropped inside it + std::string const& action; + /// @brief The body sent. + Value const& body; + // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) +}; + +/// @brief A mutation's run as it settles. +struct RunSettled { + /// @brief The run's id, as `RunStarted` gave it. + std::uint64_t run; + /// @brief The action's id. + // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members): the settled-run view borrows the call's action, body, reply and refusal code, and the object lives only inside the observer callback they outlive + std::string const& action; + /// @brief The body sent. + Value const& body; + /// @brief Whether the action replied. + bool succeeded; + /// @brief The reply; null for a run that failed. + Value const& reply; + /// @brief The `ActionRefusal` code of a refused run; empty for none. + std::string const& refusalCode; + // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) + /// @brief Runs the same mutation again, with the run's bindings and another body. + std::function rerun; +}; + +/// @brief Whether an action's input names rows of a table as a selection, as one row, or as the row a cell edit +/// changes. +enum class TableInputKind : std::uint8_t { + Selection, ///< A `table::RowSelection`: its schema property carries `x-selectionOf`. + Row, ///< A `table::RowRef`: its schema property carries `x-rowOf`. + CellEdit, ///< A `table::CellEdit` or `table::RowEdit` action: its schema root carries `x-cellEditOf` or + ///< `x-rowEditOf`, and its member `key` names the row. +}; + +/// @brief A top-level member of an action's input that names rows of a table. +struct TableInput { + /// @brief The member's name. + std::string member; + /// @brief The table's record, as the keyword names it. + std::string record; + /// @brief A selection or one row. + TableInputKind kind = TableInputKind::Selection; +}; + +/// @brief The members of an action's input schema that name rows of a table. +/// @param schemaJson The action's input schema. +/// @return Each top-level property carrying `x-selectionOf` or `x-rowOf`, by member name, and the member `key` of an +/// edit action whose root carries `x-cellEditOf` or `x-rowEditOf`; none for a schema that does not read. +[[nodiscard]] MORPH_API std::vector tableInputsOf(std::string_view schemaJson); + +/// @brief Hears every mutation run of a session: what a model-backed table marks its rows by, and offers again. +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions): an interface; observers are not copied through it. +class RunObserver { +public: + virtual ~RunObserver() = default; + /// @brief A run was sent. + /// @param run The run. + virtual void started(RunStarted const& run) = 0; + /// @brief A run settled. + /// @param run The run. + virtual void settled(RunSettled const& run) = 0; +}; + /// @brief What screens of one client session share (spec 5 §5, §12b): the query cache, the mounted queries, the /// principal's permitted actions, the formatting facts and the client's `env`, `session` and `host` values. /// @@ -592,6 +767,22 @@ using HostScopes = std::map>, std /// principal change. class MORPH_API Session { public: + /// @brief Adds an observer of every mutation run; it must be removed before it goes. + /// @param observer The observer. + void addRunObserver(RunObserver* observer) { _runObservers.push_back(observer); } + + /// @brief Removes an observer added with `addRunObserver`. + /// @param observer The observer. + void removeRunObserver(RunObserver* observer) { std::erase(_runObservers, observer); } + + /// @brief The observers of mutation runs, in the order they were added. + /// @return A copy, so an observer may remove itself while it is told. + [[nodiscard]] std::vector runObservers() const { return _runObservers; } + + /// @brief The next run id: one counter for the whole session, so two mutations never share one. + /// @return The id. + [[nodiscard]] std::uint64_t nextRunId() noexcept { return ++_runIds; } + /// @brief An empty session. /// @param runtime The runtime. Borrowed. /// @param options Timers, clock, catalog and the inline cap. @@ -606,13 +797,14 @@ class MORPH_API Session { _hostValues{runtime}, _hostCommandNames{runtime}, _hostScopesRevision{runtime, 0}, - _contextOffered{runtime, false} {} + _contextOffered{runtime, false}, + _tableStates{detail::makeTableStates(*this, runtime, _options)} {} Session(Session const&) = delete; Session& operator=(Session const&) = delete; Session(Session&&) = delete; Session& operator=(Session&&) = delete; - ~Session() = default; + ~Session(); /// @brief The runtime. /// @return It. @@ -622,6 +814,10 @@ class MORPH_API Session { /// @return They. [[nodiscard]] SessionOptions const& options() const noexcept { return _options; } + /// @brief The table states the session keeps, loads and saves through `SessionOptions::tableState`. + /// @return They; `nullptr` when the session has no store. + [[nodiscard]] TableStates* tableStates() const noexcept { return _tableStates.get(); } + /// @brief Sets the action ids the principal may run, as the catalog reply lists them; `{"can": ...}` follows them. /// @param permitted The ids. void setPermitted(std::set> permitted) { _permitted.set(std::move(permitted)); } @@ -794,6 +990,12 @@ class MORPH_API Session { /// @param screen It. void detachScreen(detail::ScreenCore& screen) { std::erase(_screens, &screen); } + /// @brief Tells every screen of the session that a table state's save did not end `Saved`, so each table + /// mounted with that key says it in its status line. + /// @param key The state's key. + /// @param result What the store answered. + void tableSaveFailed(table::TableStateKey const& key, table::SaveResult const& result); + /// @brief Starts a query's request before its screen mounts, so the screen mounts on a warm cache. /// @param channel The alias's channel. /// @param token The alias's instance token (`Screen::instanceToken`). @@ -899,6 +1101,13 @@ class MORPH_API Session { /// connection was down is read again. void reconnected(); + /// @brief Hears every reconnect and `resync`, after the watch set is sent and the cache marked: what a reader + /// that holds rows outside the cache and watches no record (a page window over an action that holds none) + /// refetches by. + /// @param handler What hears it, on the runtime's owner. + /// @return The holder: the handler is called while a copy of it lives. + [[nodiscard]] std::shared_ptr onReconnected(std::function handler); + /// @brief The topics the cache holds now: every record an entry holds, every extra watch, and the keyed shared /// instance of every entry whose action holds no record. What `reconnected` sends. /// @return The topics, records and instances each in name order; `replace` is false. @@ -945,6 +1154,36 @@ class MORPH_API Session { /// @param entry The entry. static void markStale(detail::CacheEntry& entry); + /// @brief Runs a read action and settles with its reply's JSON text, making no cache entry and reading none. + /// + /// A page window's fetches go through it. The reply is not read into a `Value`: a page's `Number` cells are JSON + /// numbers with fractions or exponents, which a `Value` cannot hold, so the caller decodes the text against the + /// table's description (`table::readGenericPage`). No effects are applied: a read has none, and the caller's own + /// change events reach it as anyone's do. + /// @param channel The alias's channel; `nullptr` fails the read at once. + /// @param actionId The action. + /// @param body The body, sent as its canonical JSON. + /// @param stop The caller's cancel: passed to the channel as `CallOptions::stop`, so the wire's `cancel` goes + /// out where the server takes one; the read then settles cancelled and its reply is dropped. + /// @return The reply's JSON text, byte for byte as the channel returned it, delivered on the runtime's owner; or + /// the call's failure, or `core::async::OperationCancelled` after a stop. + [[nodiscard]] async::Completion read(std::shared_ptr const& channel, + std::string const& actionId, Value const& body, + ::core::async::StopToken const& stop = {}); + + /// @brief Watches a record without a cache entry, for as long as a copy of the returned holder lives. + /// + /// The record is counted in the watch set as an entry's records are, so a count that leaves zero sends a + /// `watch` at once. @p handler hears, on the runtime's owner, each `changes` event that names the record (after + /// the cache's entries are marked), and a whole-type change (`keys` absent) on reconnect and on `resync`. + /// @param record The record's wire name. + /// @param handler What hears its changes. + /// @return The holder, once the server has the watch: when the `watch` this call sent, or the one in flight for + /// the record, is answered (whatever the answer, since a refused topic only sends no events); at once + /// when the record was already watched and answered, or the session has no watcher. + [[nodiscard]] async::Completion watchRecord( + std::string const& record, std::function handler); + private: // A cap of 0 moves nothing inline, and one above the largest would not fit an envelope once encoded. [[nodiscard]] static SessionOptions checkedOptions(SessionOptions options); @@ -970,6 +1209,21 @@ class MORPH_API Session { /// @param delta `+1` when the entry is made, `-1` when it is dropped. void countTopics(detail::CacheEntry const& entry, int delta); + /// @brief Counts one record in or out of the watch set, as `countTopics` counts an entry's. + /// @param record The record. + /// @param delta `+1` or `-1`. + void countRecord(std::string const& record, int delta); + + /// @brief Hands a record change to every watch holder of its record. + /// @param change The change. + void notifyWatchers(effects::RecordChange const& change); + + /// @brief The watch registry, made on first use. + /// @return It. + detail::WatchRegistry& watchRegistry(); + + friend struct detail::WatchRegistration; + /// @brief Sends the queued watch changes, at most one `watch` and one `unwatch`; drops them when there is no /// watcher. void flushWatches(); @@ -1015,6 +1269,8 @@ class MORPH_API Session { SessionOptions _options; reactive::Signal>> _permitted; std::map> _recordRefs; + std::shared_ptr _watchRegistry; + std::vector>> _reconnectListeners; std::map, int> _instanceRefs; std::set> _watchRecords; /// The records watched for something other than the cache (`addExtraWatch`). @@ -1052,6 +1308,10 @@ class MORPH_API Session { int _userDepth = 0; bool _lastWriteUser = false; std::uint64_t _privateTokens = 0; + std::vector _runObservers; + std::uint64_t _runIds = 0; + /// After everything a save or load reaches, so it is destroyed first. + std::shared_ptr _tableStates; }; // --------------------------------------------------------------------------------------------------------------- // Runtime structures @@ -1104,6 +1364,8 @@ struct MountOptions { Screen const* keepStateOf = nullptr; }; +class WindowRows; + namespace detail { /// @brief A name bound for the expressions of one place: a command's `event`, a step's `as`, `result` in a @@ -1124,6 +1386,10 @@ struct ElementState; class MutationRuntime; struct CheckRuntime; struct BoundaryRuntime; +struct ModelTable; +struct RowsTable; +struct GridTable; +struct TableConfig; /// @brief One state declaration at run time. struct StateSlot { @@ -1246,9 +1512,15 @@ struct MORPH_API ElementState { reactive::Computed* rows = nullptr; /// @brief A table's bound `sort`; `nullptr` while the table holds its own. reactive::Computed* sortBound = nullptr; - /// @brief A table's rows as it shows them, made beside `rows` so that every reader of the table's element - /// values, the table's own lowering included, sees one order; `nullptr` for a table without `rows`. + /// @brief A table's rows as it shows them, in its engine's order, and the page of them it shows: what every + /// reader of the table's element values reads; `nullptr` for a table without `rows`. reactive::Computed* view = nullptr; + /// @brief The rows a table's mount reads: a table over `rows` its `EngineRows`, a model-backed table the rows + /// over its window that tell the element of each change and gesture, a collection its engine's rows that + /// tell its table of each change; null for any other element. + std::shared_ptr tableRows; + /// @brief A model-backed table's window over the server's pages; null for any other element. + std::shared_ptr tableWindow; /// @brief A `form`'s session (spec 2), made when the element is wired; null when its schema is unknown. std::unique_ptr form; /// @brief A `collection`'s session (spec 2), made when the element is wired; null when its view document is @@ -1257,6 +1529,21 @@ struct MORPH_API ElementState { /// @brief A `wizard`'s session (spec 2), made when the element is wired; null when its wizard document or a /// step's schema is unknown or does not build. std::unique_ptr wizard; + /// @brief A model-backed table's rows, description, persisted state and status line, made when the element is + /// wired; null for any other element. It outlives every mount of the table. + std::unique_ptr modelTable; + /// @brief A table over `rows`: its source, engine and page, its persisted state and its status line, made when + /// the element is wired; a collection's table: its engine over the session's source, its configuring, + /// persisted state and status line. Null for any other element. It outlives every mount of the table. + std::unique_ptr rowsTable; + /// @brief A grid of a form (a table with `form` and `field`) or a fixed grid (a table with `layoutRows`): its grid + /// and its status line, made when the table is first lowered; null for any other element. It outlives every + /// mount of the table. + std::unique_ptr gridTable; + /// @brief A form's fields drawn as grids through a field overlay's `grid` part, by the field's name: each an + /// element + /// of its own, whose node is the part, holding its grid. Empty for any other element. + std::map, std::less<>> fieldGrids; }; /// @brief One check at run time. @@ -1357,6 +1644,9 @@ class MORPH_API RtScope : public std::enable_shared_from_this { reactive::Signal const* row = nullptr; /// @brief The canonical key of a row scope's row; empty for any other scope. std::string rowKey; + /// @brief For a row scope whose row signal is set to other rows (a pooled table cell): the canonical key of the + /// row it holds now, read in place of `rowKey`; empty for any other scope. + std::function rowKeyNow; /// @brief For a component fallback's scope, the focus key of the `custom` node it is lowered for, so one /// fallback lowered for two uses keys its elements apart; empty for any other scope. std::string usePrefix; @@ -1382,6 +1672,10 @@ class MORPH_API RtScope : public std::enable_shared_from_this { std::vector> mutations; /// @brief Its checks. std::vector> checks; + /// @brief Called with a field a row expression read that the row's record does not hold; set on a server-mode + /// row scope, whose record holds only the columns fetched. Called from inside a binding's evaluation, so + /// it writes no signal. + std::function const* onMissingRowField = nullptr; /// @brief For a locale scope's scope, the formatting facts it writes in; `nullptr` for any other scope. reactive::Computed>* localeFormat = nullptr; /// @brief Whether the scope declares nothing: the elements of its nodes are the enclosing scope's. @@ -1644,6 +1938,8 @@ class MORPH_API MutationRuntime { private: struct Run { std::uint64_t id = 0; + /// The id observers know the run by: `Session::nextRunId`, unique across mutations. + std::uint64_t sessionRun = 0; Value body; std::shared_ptr bindings; RunDone done; @@ -1921,6 +2217,46 @@ class MORPH_API ScreenCore { /// @return The value. [[nodiscard]] Value inputValue(ElementState const& element) const; + /// @brief Shows @p text as the table's status-line message for `kStatusMessageHold`, on the session's scheduler + /// (without one, until the table's next gesture); an empty @p text clears the message and notifies + /// nothing. Under `status: false` a non-empty text goes to `InterpreterHost::notify` as a warning instead. + /// @param table The table's element; one that is neither a model-backed table nor one over `rows` is left alone. + /// @param text The message, or empty. + void tableMessage(ElementState& table, std::string text); + /// @brief Shows @p text as a model-backed table's status-line message, as the overload above does, with the + /// choices it offers after it; choosing one clears the message and runs what it was given with. The + /// choices go with the message: when it is cleared or replaced, or its hold ends. Under `status: false` + /// the text goes to the host and no choice is offered. + /// @param table The table's element; for one that is not a model-backed table the choices are not offered. + /// @param text The message; not empty. + /// @param entries Each choice, by its id and label, with what choosing it runs. + void tableMessage(ElementState& table, std::string text, + std::vector>> entries); + + /// @brief Says a table state's failed save in the status line of every table of the screen mounted with its key. + /// @param key The state's key. + /// @param result What the store answered. + void tableSaveFailed(table::TableStateKey const& key, table::SaveResult const& result); + + /// @brief How many entries a model-backed table's index of row scopes holds, for tests: one per realized row + /// whose scope `onActivate` can run in. + /// @param table The table's element. + /// @return The entries; 0 for an element that is not a model-backed table. + [[nodiscard]] static std::size_t tableRowScopes(ElementState const& table); + + /// @brief Shows a model-backed table's state at the `columns` and `saved` points that name it: a `columns` point + /// reads the column layout (`table::ColumnLayoutValue` as a record), a `saved` point the saved view's name. + /// @param table The table's element. + void tablePoints(ElementState& table); + + /// @brief Writes a choice for a `columns` or `saved` point into the state of the model-backed table it names, + /// which saves it as any change of the table's arrangement is saved. + /// @param point The point. + /// @param value The choice: a layout record for `columns`, a name or `null` for `saved`. + /// @return Nothing when the point names no mounted model-backed table; otherwise whether the choice was taken + /// (a value that does not read as the point's part is refused). + [[nodiscard]] std::optional tablePoint(CustomizePoint const& point, Value const& value); + // --- Commands ---------------------------------------------------------------------------------------------- /// @brief Runs a command list: each command in order in one batch; done when every command in it is. @@ -2027,6 +2363,12 @@ class MORPH_API ScreenCore { /// @brief Moves focus to a mounted element by its id; empty until the screen is mounted, and again once it is /// unmounting. std::function focusElement; + /// @brief Puts text on the clipboard through the backend's `IViewBackend::copyText`, returning whether it did; + /// empty until the screen is mounted, and again once it is unmounting. + std::function clipboard; + /// @brief Reads the clipboard's text through the backend's `IViewBackend::pasteText`; empty until the screen is + /// mounted, and again once it is unmounting. + std::function()> pasteboard; /// @brief The models the opener lends. std::map> borrowed; /// @brief The screen scope's reactive depth. @@ -2076,6 +2418,9 @@ class MORPH_API ScreenCore { std::vector loweredNodes; /// @brief The screen's live scopes, in creation order. std::vector scopes; + /// @brief The elements of the screen's tables that keep a persisted state, model-backed or over `rows`, while + /// each lives: what a failed save of a table state is said in. + std::vector modelTables; /// @brief The latest command lists run, oldest first, at most `kCommandLogSize`. std::deque commandLog; /// @brief Set while the inspector evaluates, so that an expression error it meets is not reported. @@ -2096,15 +2441,23 @@ class MORPH_API ScreenCore { private: void wireElement(ElementState& element); void wireErrors(ElementState& element); - /// A table's rows in the order of its sort, read in the table's scope with @p bindings. A sort that is not a - /// list of the table's sortable columns, or whose values cannot be ordered, is reported and leaves the source - /// order. - void sortedRows(ElementState const& element, Bindings const* bindings, TableView& view); - /// A grouped table's runs of its source rows by its `group`'s `by`: each row's run index and each run's heading - /// entry, into @p view. - static void groupRows(ElementState const& element, Bindings const* bindings, TableView& view); - /// A table's sorted rows and the page of them it shows, by its `pageSize` and `page`. - TableView tableView(ElementState const& element, Bindings const* bindings); + /// A table over `rows`: its rows in its engine's view, each grouped row's run and each run's heading entry, and + /// the page of them it shows, by its `pageSize` and `page`. Nothing while its stored state is read. + TableView tableView(RowsTable const& table); + /// The rows, source, engine and page of a table over `rows`, read in the table's scope with @p bindings; with + /// @p persisted, its stored state is loaded and its changes saved, and it is the element's own. + std::unique_ptr makeRowsTable(ElementState& element, std::shared_ptr bindings, + bool persisted); + /// Brings a table over `rows` to its sort: the columns its keys read are in use, and the engine orders by them, + /// within the groups first when it has any. A sort that is not a list of its sortable columns is reported. + void sortRowsTable(RowsTable& table, Value const& sort); + /// What a table over `rows` does when its engine's view changed: reports an invalid cell of a sort column once, + /// and lets the rows through once the stored order is in place. + void rowsTableChanged(RowsTable& table); + /// Shows @p text in the status line of a table over `rows`, as `tableMessage` does for a table's element. + void rowsTableMessage(RowsTable& rows, std::string text) const; + /// Applies a table over `rows`' stored state once its load completed, or reports why it could not. + void storedRowsState(RowsTable& table, std::optional const& json, std::string const& failure); void collect(DocNode const& node, RtScope& scope, std::vector& commands); /// The readers every kind's lowering shares, bound to one node. class KindKit; @@ -2140,9 +2493,71 @@ class MORPH_API ScreenCore { Node lowerDialog(DocNode const& node, LowerCtx const& ctx, ElementState* element); Node lowerSwitch(DocNode const& node, LowerCtx const& ctx); Node lowerRows(DocNode const& node, LowerCtx const& ctx, ElementState* element); + /// A model-backed table: a list of at most one table, keyed by its description's revision, over its rows. + Node lowerModelTable(DocNode const& node, LowerCtx const& ctx, ElementState* element); + /// A grid of a form: a table over a form node's collection, its rows the field's and its cells its members. + Node lowerFormGrid(DocNode const& node, LowerCtx const& ctx, ElementState* element); + /// The table of a grid of a form, kept in @p element: a `table` node's with `form` and `field`, or a field + /// overlay's `grid` part's. + Node formGridTable(DocNode const& part, LowerCtx const& ctx, ElementState& element, forms::FormSession& form, + forms::FieldState& array); + /// The table node of the grid @p element keeps, made anew by each lowering. + Node gridTableNode(DocNode const& part, LowerCtx const& ctx, ElementState& element); + /// The rows a grid with summaries or a group is mounted over: its summary decorator, each data row's cell as the + /// grid draws it, each summary row's cells its part's expressions, and each run's heading. + TableSource summarySource(DocNode const& part, LowerCtx const& ctx, GridTable& held, + std::vector const& columns); + /// A summary cell's value: the expression the summary row's part gives the column, read with `rows` and `column`; + /// none when the part gives the column none. + std::optional summaryValue(DocNode const& table, Value const& record, std::string const& column, + LowerCtx const& ctx, ValueList rows); + /// A summary row's own parts: the summary flag, and its part's `label` as the row's name. + TableRowLook summaryLook(DocNode const& table, LowerCtx const& ctx, Value const& record); + /// A grid's summary cell text: its value over the data rows in its scope, at the column's member's places. + std::string gridSummaryText(DocNode const& part, LowerCtx const& ctx, GridTable& held, Value const& record, + std::string const& column); + /// What a grid's part (a `table` with a `form`, a field overlay's `grid`) gives beyond its table: its columns and + /// its options. + void gridParts(DocNode const& part, LowerCtx const& ctx, forms::FieldState const& array, + std::vector& columns, GridOptions& options); + /// What any grid's part gives of its walk and its activation. + void gridOptions(DocNode const& part, LowerCtx const& ctx, GridOptions& options); + /// A fixed grid: a table whose rows are its `layoutRows`, each cell a field of the form `form` names, an + /// expression or a text, kept in @p element as a grid of a form is. + Node lowerFixedGrid(DocNode const& node, LowerCtx const& ctx, ElementState* element); + /// The table a model-backed table shows for the description its rows hold, or the status line alone without one. + Node modelTableOf(DocNode const& node, LowerCtx const& ctx, ElementState& element); + /// A model-backed table with a column its description edits, as a grid over its cells: the grid's controller, its + /// rows handed to @p source; null for a table with no editable column. + std::shared_ptr editableModelTable(DocNode const& node, LowerCtx const& ctx, ElementState& element, + table::TableDescription const& description, + std::vector const& shown, + TableSource& source, TableOptions const& options, + std::shared_ptr> const& drafts); + /// Makes a model-backed table's rows, its description query and its persisted state's load. + void wireModelTable(ElementState& element); + /// Takes the description its query holds now: reports the filters a new revision drops, then hands it to the rows. + void describedTable(ElementState& element, Value const& described); + /// Applies the filter a typed list action's table held while its kinds waited for the first reply: a stored + /// one fitted to those kinds, each filter it drops reported; another set, or reported as refused. + void inferredTable(ElementState& element); + /// Applies a model-backed table's stored state once its load completed, or reports why it could not. + void storedTableState(ElementState& element, std::optional const& json, std::string const& failure); + /// A user's gesture on a model-backed table: the stored state no longer replaces the arrangement, and the + /// status-line message goes. + void tableGesture(ElementState& element); + /// Wires a table's header, menus and arrangement to its configuring: sort gestures held to the table's bound, + /// layout gestures to what it allows, each refusal shown in its status line and each change run through its + /// commands; and its copy, of the rows `TableConfig::gather` gives. @p keep is held by every handler, for a table + /// its mount owns. Returns the column chooser and the + /// sort dialog its menu opens, to mount beside the table; null for a table with no menus. + Node configureTable(TableConfig& config, LowerCtx const& ctx, TableOptions& options, + std::shared_ptr const& keep); + /// Takes the columns a model-backed table's layout arranges from the description its rows hold now. + void modelLayoutColumns(ElementState& element) const; /// A grouped table's heading row: its `group`'s `heading`, lowered as one cell in a row scope of its own whose /// row is the group's run record and whose key is `key`, the row's canonical key, as a data row's scope has. - TableRowView headingRow(DocNode const& node, LowerCtx const& ctx, reactive::Signal const& row, + TableRowLook headingRow(DocNode const& node, LowerCtx const& ctx, reactive::Signal const& row, std::string key); /// A `rowTone` value as a tone: `neutral`, `info`, `ok`, `warn`, `err`, or `null` for none. Another value is /// reported, at @p path, while @p noted is still false, and shows no tone. @@ -2201,6 +2616,8 @@ class MORPH_API ScreenCore { Node lowerArrangeEditor(DocNode const& node, LowerCtx const& ctx, std::string const& point, CustomizePoint const& spec, std::function const& choose); void wireForm(ElementState& element); + /// A form's rounds of derived values over its alias: its evaluation and its `derive` action. + void deriveForm(ElementState& element, ModelAlias* alias); Node lowerForm(DocNode const& node, LowerCtx const& ctx, ElementState* element); [[nodiscard]] FormSubmitter aliasCalls(ModelAlias* alias); [[nodiscard]] FormSubmitter aliasSubmits(ModelAlias* alias, std::string read = {}); @@ -2208,6 +2625,15 @@ class MORPH_API ScreenCore { void followFormatting(ElementState& element, RtScope& scope); void wireComposite(ElementState& element); Node lowerComposite(DocNode const& node, LowerCtx const& ctx, ElementState* element); + /// A collection's table, kept in its element as a table over `rows` is: an engine over the session's source, + /// the configuring of every column, and its state persisted under the collection's action. + void wireCollectionTable(ElementState& element, std::string modelType); + /// The rows of a collection, lowered as a table on the engine: sorted, filtered, arranged and copied as any other + /// table, with @p buttons, when set, drawing each row's trailing cell for its key text. + Node lowerCollectionRows(ElementState& element, LowerCtx const& ctx, + std::function const& buttons); + /// Applies a collection's stored state once its load completed, or reports why it could not. + void storedCollectionState(RowsTable& table, std::optional const& json, std::string const& failure); void presentForm(DocNode const& node, LowerCtx const& ctx, forms::FormViewOptions& options); Node lowerTabs(DocNode const& node, LowerCtx const& ctx, ElementState* element); Prop controlledTabSelection(DocNode const& node, LowerCtx const& ctx, ExprPtr const& selected, @@ -2446,6 +2872,11 @@ struct HeadTool { bool operator==(HeadTool const&) const = default; }; +namespace testing { +/// @brief What a test reads of a `Screen` that its interface does not show; the tests define it. +struct ScreenProbe; +} // namespace testing + /// @brief A mounted screen: its scopes, its view mounted through `Mounted`, and what its host asks of it. /// /// Neither copyable nor movable. It belongs to the runtime's owner; the runtime, the session, the dispatcher and @@ -2654,6 +3085,7 @@ class MORPH_API Screen { private: friend class Interpreter; friend class Inspector; + friend struct testing::ScreenProbe; // Out of line: an exported class emits its inline members in every module, and this one destroys a // `std::unique_ptr` on a throw, which needs `Mounted` complete. diff --git a/include/morph/ui/measure.hpp b/include/morph/ui/measure.hpp new file mode 100644 index 000000000..2d957e821 --- /dev/null +++ b/include/morph/ui/measure.hpp @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file ui/measure.hpp +/// @brief What a user types for an amount with a unit, and the operand a filter takes for it. +/// +/// A client parses a measure with the units of the table's description (`TableDescription::units`) and its locale's +/// number, and sends the wire's operand: a decimal with a point, a space and a unit id, whatever the locale. See +/// `docs/spec/table/table.md`, "Filters on values with units". + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +/// @brief An amount a user typed, with the unit it names. +struct TypedMeasure { + /// @brief The amount, exact. + math::Rational amount; + /// @brief The unit's id; empty is the ratio's unit. + std::string unit; + + /// @brief Member-wise equality, the amount by value. + /// @param other The measure to compare with. + /// @return `true` when the amounts are equal and the units are the same id. + [[nodiscard]] bool operator==(TypedMeasure const& other) const = default; +}; + +namespace detail { + +/// @brief Whether two texts are equal with ASCII letters compared without regard to case. +/// @param left One text. +/// @param right The other. +/// @return `true` when they differ only in the case of ASCII letters. +[[nodiscard]] inline bool equalsIgnoringAsciiCase(std::string_view left, std::string_view right) noexcept { + if (left.size() != right.size()) { + return false; + } + auto const lower = [](char character) { + return character >= 'A' && character <= 'Z' ? static_cast(character - 'A' + 'a') : character; + }; + for (std::size_t at = 0; at < left.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `at` is below both sizes, which are equal; `.at()` could throw out of a noexcept function. + if (lower(left[at]) != lower(right[at])) { + return false; + } + } + return true; +} + +} // namespace detail + +/// @brief Reads what a user typed for a measure: the locale's number, optional spaces, then a unit. +/// +/// The number is an optional minus sign (`-` or the locale's), ASCII digits, and at most one decimal separator of +/// the locale followed by digits; a group separator is not read. The unit is the rest of the text, matched against a +/// unit's `symbol` or `id` exactly and then without regard to the case of ASCII letters, the first match in +/// @p units order winning each pass. Text with no unit takes @p chosen, the unit a menu shows as chosen. +/// @param text What the user typed; spaces around it are ignored. +/// @param units The units the user may name: the table's description's. +/// @param locale The locale the user types in. +/// @param chosen The unit's id for text with no unit; empty is the ratio's unit. +/// @return The amount and the unit's id, or `nullopt` when the text is not a number and a unit of @p units. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): reads sign, digits, separator, digits and unit in one left-to-right pass over the text with a running index +[[nodiscard]] inline std::optional parseMeasure(std::string_view text, + std::span units, + LocaleFacts const& locale, + std::string_view chosen = {}) { + auto const first = text.find_first_not_of(' '); + if (first == std::string_view::npos) { + return std::nullopt; + } + text = text.substr(first, text.find_last_not_of(' ') - first + 1); + std::string canonical; + std::size_t index = 0; + auto const negative = locale.numeric.negativeSign.empty() ? std::string_view{"-"} : locale.numeric.negativeSign; + if (text.starts_with('-')) { + canonical += '-'; + index = 1; + } else if (text.starts_with(negative)) { + canonical += '-'; + index = negative.size(); + } + auto const digits = [&] { + auto const from = index; + while (index < text.size() && text.at(index) >= '0' && text.at(index) <= '9') { + canonical += text.at(index++); + } + return index > from; + }; + if (!digits()) { + return std::nullopt; + } + auto const separator = locale.numeric.decimalSeparator; + if (!separator.empty() && text.substr(index).starts_with(separator)) { + index += separator.size(); + canonical += '.'; + if (!digits()) { + return std::nullopt; + } + } + auto const amount = table::parseDecimal(canonical); + if (!amount) { + return std::nullopt; + } + while (index < text.size() && text.at(index) == ' ') { + ++index; + } + auto const named = text.substr(index); + if (named.empty()) { + return TypedMeasure{.amount = *amount, .unit = std::string{chosen}}; + } + for (auto const exact : {true, false}) { + for (auto const& unit : units) { + auto const matches = [&](std::string_view name) { + return !name.empty() && (exact ? name == named : detail::equalsIgnoringAsciiCase(name, named)); + }; + if (matches(unit.symbol) || matches(unit.id)) { + return TypedMeasure{.amount = *amount, .unit = unit.id}; + } + } + } + return std::nullopt; +} + +/// @brief The operand a filter takes for a measure: the wire's form, whatever the user's locale. +/// @param measure The measure. +/// @return The amount as a decimal with a point, then a space and the unit's id: `"0.3 kg"`; the amount alone for +/// the ratio's unit, `"0.003"`. +[[nodiscard]] inline std::string measureOperand(TypedMeasure const& measure) { + auto out = units::detail::formatRationalDecimal(measure.amount); + if (!measure.unit.empty()) { + out += ' '; + out += measure.unit; + } + return out; +} + +} // namespace morph::ui diff --git a/include/morph/ui/mount.hpp b/include/morph/ui/mount.hpp index 9b4e8e0bc..74320b4b8 100644 --- a/include/morph/ui/mount.hpp +++ b/include/morph/ui/mount.hpp @@ -2,14 +2,19 @@ #pragma once #include +#include +#include +#include #include #include #include #include #include +#include #include #include #include +#include #include #include #include @@ -25,12 +30,7 @@ #include #include -#include "../attributes.hpp" -#include "../reactive/runtime.hpp" -#include "../reactive/scope.hpp" -#include "../reactive/signal.hpp" -#include "../ui/backend.hpp" -#include "view.hpp" +#include "table_rows.hpp" /// @file /// @brief `morph::ui::Mounted`: builds a view tree's widgets through a backend once, and keeps them current through @@ -40,14 +40,228 @@ namespace morph::ui { +/// @brief What a mount did to the rows of its tables mounted over a `TableSource`, for tests. +struct MountStats { + /// @brief Sets of a cell's row signal that changed its record; each re-evaluates the cell. + std::size_t cellBinds = 0; + /// @brief Sets of a realized row's own signal that changed its record; each re-evaluates the row's own parts. + std::size_t rowBinds = 0; + /// @brief Cells built, by `TableSource::cellView` or `defaultCellView`. + std::size_t cellsCreated = 0; + /// @brief Cells bound to another row or column: a pooled cell taken, or a cell of a row slot given another row. + std::size_t cellsRebound = 0; + /// @brief Cells a pass left blank for the frame's budget, to be realized in a later turn. + std::size_t placeholders = 0; + /// @brief `TableRows` changes applied to the realized rows. + std::size_t viewChanges = 0; + /// @brief Of `viewChanges`, those that replaced the whole view. + std::size_t viewResets = 0; +}; + +/// @brief Which of a table's dimensions are windowed. +struct Windowing { + /// @brief Only the rows in or near view are realized. + bool rows = false; + /// @brief Only the columns in or near view are realized. + bool columns = false; + + /// @brief Member-wise equality. + /// @param other The windowing to compare with. + /// @return `true` when both members match. + [[nodiscard]] bool operator==(Windowing const& other) const = default; +}; + +/// @brief Which dimensions of a table are windowed: rows from `threshold` rows on, or always in server mode; columns +/// above `columnThreshold` visible columns; both above `cellThreshold` cells. +/// @param virtualization The table's limits. +/// @param rows The rows of the view. +/// @param visibleColumns The columns shown. +/// @param serverMode Whether the rows come from a server's pages. +/// @return What is windowed. +[[nodiscard]] MORPH_API Windowing windowingOf(Virtualization const& virtualization, std::size_t rows, + std::size_t visibleColumns, bool serverMode); + +/// @brief The widths of a table's visible columns, in layout order, and their running offsets. +/// +/// Widths are kept in a Fenwick tree, so a width's change, a column's offset and the columns at a scroll position +/// each read O(log n) nodes; no call reads every column. `columnReads` counts the reads of single columns' widths +/// (`widthOf`), which is what a pass over the window does per column. +class MORPH_API ColumnExtents { +public: + /// @brief Replaces every width. + /// @param widths The visible columns' widths, in layout order; a negative width reads as 0. + void assign(std::span widths); + + /// @brief Grows a column to @p width; a measured width never narrows a column, nor changes one the user set. + /// @param column The column's place in the layout. + /// @param width The width measured. + /// @return Whether the width changed. + bool grow(std::size_t column, int width); + + /// @brief Sets a width the mount computed, which may be narrower than the one before; a width the user set stays. + /// @param column The column's place in the layout. + /// @param width The width; a negative width reads as 0. + /// @return Whether the width changed. + bool fit(std::size_t column, int width); + + /// @brief Sets a width the user chose; measurement no longer changes it. + /// @param column The column's place in the layout. + /// @param width The width. + void set(std::size_t column, int width); + + /// @brief The columns a horizontal viewport shows. + /// @param offset The scroll offset. + /// @param viewport The viewport's width. + /// @return `[first, last)`: the column under @p offset to the one past the last under the viewport's end. + [[nodiscard]] std::pair columnsAt(int offset, int viewport) const; + + /// @brief Where a column starts: the sum of the widths before it. + /// @param column The column's place in the layout; past the last, the total width. + /// @return The offset. + [[nodiscard]] int offsetOf(std::size_t column) const; + + /// @brief A column's width; one counted read. + /// @param column The column's place in the layout. + /// @return The width; 0 past the last column. + [[nodiscard]] int widthOf(std::size_t column) const; + + /// @brief The width of every column together. + /// @return The total. + [[nodiscard]] int totalWidth() const noexcept { return offsetOf(_widths.size()); } + + /// @brief The columns held. + /// @return How many. + [[nodiscard]] std::size_t size() const noexcept { return _widths.size(); } + + /// @brief How many single widths `widthOf` has read. + /// @return The count. + [[nodiscard]] std::size_t columnReads() const noexcept { return _reads; } + +private: + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`column`, `delta`): called from `assign`, `grow`, `fit` and `set`, each passing the column first and the signed width change second + void add(std::size_t column, int delta); + + // How many leading columns end at or before @p offset: the column under @p offset, by descent on the tree. + [[nodiscard]] std::size_t below(int offset) const; + + std::vector _widths; + std::vector _user; + std::vector _tree; // 1-based Fenwick tree over _widths + mutable std::size_t _reads = 0; +}; + +/// @brief The columns a table realizes: the pinned ones, then those in or near the horizontal viewport. +struct ColumnWindow { + /// @brief Places in the layout: the pinned columns first, then the scrolled range, ascending. + std::vector columns; + /// @brief The width before the scrolled range's first column that the window does not cover. + int leading = 0; + /// @brief The width after the window's last column. + int trailing = 0; + + /// @brief Member-wise equality. + /// @param other The window to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(ColumnWindow const& other) const = default; +}; + +/// @brief The column window at a horizontal scroll position: the first @p pinned columns, then the columns under the +/// viewport and @p overscan more on each side. Reads no width. +/// @param extents The visible columns' widths. +/// @param pinned How many leading columns stay in the window. +/// @param scrollX The scroll offset. +/// @param viewport The viewport's width. +/// @param overscan Columns kept beyond the viewport on each side. +/// @return The window. +[[nodiscard]] MORPH_API ColumnWindow columnWindow( + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`pinned`, `scrollX`): a column count then a scroll offset, passed by name from the table state at the one call site + ColumnExtents const& extents, std::size_t pinned, int scrollX, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`viewport`, `overscan`): a width then a column count, passed by name from the table state at the one call site + int viewport, std::size_t overscan); + +namespace detail { + +/// @brief Appends the runs of @p bands, at @p level, and of their children one level down: one run per maximal run of +/// a band's columns that stand together in @p visible, split at the pinned edge. +/// @param bands The bands of one level. +/// @param visible The visible column ids, in layout order. +/// @param pinned How many of the leading visible columns are pinned. +/// @param level The level of @p bands, 0 for the outermost. +/// @param out The runs found so far; the new ones are appended. +// NOLINTNEXTLINE(misc-no-recursion): a band's children are bands one level down. +MORPH_API void appendBandRuns(std::span bands, std::span visible, + std::size_t pinned, std::size_t level, std::vector& out); + +/// @brief Appends the bands that enclose a column, outermost first: the band of @p bands that names it, then the one +/// of that band's children that does, and so on. +/// @param bands The bands of one level. +/// @param columnId The column's id. +/// @param out The bands found so far; the enclosing ones are appended. +// NOLINTNEXTLINE(misc-no-recursion): a band's children are bands one level down. +MORPH_API void enclosingBands(std::span bands, std::string_view columnId, + std::vector& out); + +} // namespace detail + +/// @brief The parts a table's header bands are drawn as over a layout: one run per maximal run of a band's columns +/// that stand together, split at the pinned edge. +/// +/// A band whose columns the layout keeps side by side gives one run; one whose columns were moved apart gives one +/// per run that stands together, so no run covers a column that is not the band's; a band with no visible column +/// gives none. +/// @param bands The bands, outermost first. +/// @param visible The visible column ids, in layout order. +/// @param pinned How many of the leading visible columns are pinned. +/// @return The runs, by level from 0 (the outermost), each level left to right; positions are visible places. +[[nodiscard]] MORPH_API std::vector bandRuns(std::span bands, + std::span visible, std::size_t pinned); + +/// @brief Whether a column's header shows its unit under the bands: not when a band enclosing it shows the same one. +/// @param bands The bands, outermost first. +/// @param columnId The column's id. +/// @param unit The column's unit. +/// @return `false` when @p unit is not empty and an enclosing band's unit equals it; `true` otherwise. +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`columnId`, `unit`): a column id then its unit id, both read from the same TableColumn at every call +[[nodiscard]] MORPH_API bool columnUnitShown(std::span bands, std::string_view columnId, + std::string_view unit); + +/// @brief A column header's accessible name under the bands: each enclosing band's label, outermost first, then the +/// column's, joined by `", "` ("Mass retained, sieve 4 mm"). +/// @param bands The bands, outermost first. +/// @param columnId The column's id. +/// @param label The column's own name. +/// @return The name; @p label alone for a column under no band. +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`columnId`, `unit`): a column id then its unit id, both read from the same TableColumn at every call +[[nodiscard]] MORPH_API std::string bandedHeaderName(std::span bands, std::string_view columnId, + std::string_view label); + +/// @brief A span part as a document or a fixed grid gives it: the cell of `column` covering `rows` rows downwards and +/// `columns` columns to the right in the layout, itself included. +struct CellSpan { + /// @brief The spanning cell's column id. + std::string column; + /// @brief How many rows the cell covers, its own included. + std::size_t rows = 1; + /// @brief How many columns the cell covers, its own included. + std::size_t columns = 1; +}; + +/// @brief How many visible columns a span covers once the layout is applied: its column, then each next visible column +/// while it is the next declared one, up to `CellSpan::columns`. A span across a column the user moved away or +/// hid is cut there. +/// @param span The span. +/// @param declared Every column id, in declared order. +/// @param visible The visible column ids, in layout order. +/// @return The count, from 1; 0 when the span's own column is not visible. +[[nodiscard]] MORPH_API std::size_t cutColumns(CellSpan const& span, std::span declared, + std::span visible); + namespace detail { /// @brief The site names a misuse in this layer is reported under, through the runtime's owner probe. namespace site { /// @brief An exception escaped a widget callback; the mount caught it, so it never reaches the backend. inline constexpr char const* kCallbackThrew = "morph::ui: an exception escaped a widget callback"; -/// @brief A ForEach or Table snapshot repeated a key; the later row is refused and the first one kept. -inline constexpr char const* kDuplicateKey = "morph::ui: duplicate ForEach key"; /// @brief A table row's span names no column, covers no rows, is a heading's, or repeats a column of its row; it is /// refused and its cell stays in its own row. inline constexpr char const* kRowSpanInvalid = "morph::ui: a table row's span is not a span of the table"; @@ -93,52 +307,19 @@ struct SpanRow { /// @brief Resolves the requested spans of a table's rows, top to bottom, one column at a time. /// -/// A span is refused, alone, when it names no column, covers 0 rows, belongs to a heading row, repeats a column of -/// its row, starts in a column an earlier span covers, or runs past the last row or over a heading row. The earlier -/// span wins an overlap. -/// @param rows The rows in order. +/// A span is refused, alone, when it names no column, covers 0 rows or 0 columns, belongs to a heading row, repeats a +/// column of its row, starts in or covers a cell an earlier span covers, or runs past the last row or over a heading +/// row. The earlier span wins an overlap. A span covers `rows` rows from its own and `columns` visible places from its +/// column's, clipped at the last place; a span whose column is hidden covers nothing and is not refused. +/// @param rows The rows in order. /// @param columns How many columns the table has. +/// @param placeOf Each column's visible place, by index into the table's columns, none for a hidden column; empty: +/// every +/// column at the place of its index. /// @return The effective spans per row and the refusals. -[[nodiscard]] inline ResolvedSpans resolveRowSpans(std::vector const& rows, std::size_t columns) { - ResolvedSpans out; - out.effective.resize(rows.size()); - std::vector coveredUntil(columns, 0); - for (std::size_t index = 0; index < rows.size(); ++index) { - SpanRow const& row = rows.at(index); - std::vector named(columns, false); - for (RowSpan const& span : row.requested) { - auto const refuse = [&](char const* const site, std::string_view why) { - out.refused.emplace_back( - site, row.name + ": column " + std::to_string(span.column) + " " + std::string{why}); - }; - if (span.column >= columns || span.rows == 0 || row.heading || named.at(span.column)) { - refuse(site::kRowSpanInvalid, "is not a span of this table"); - continue; - } - named.at(span.column) = true; - if (coveredUntil.at(span.column) > index) { - refuse(site::kRowSpanOverlap, "starts under another span"); - continue; - } - if (span.rows == 1) { - continue; - } - std::size_t const end = index + span.rows; - bool const crossesHeading = - end <= rows.size() && std::any_of(rows.begin() + static_cast(index) + 1, - rows.begin() + static_cast(end), - [](SpanRow const& covered) { return covered.heading; }); - if (end > rows.size() || crossesHeading) { - refuse(site::kRowSpanOverrun, "runs past the last row or over a heading"); - continue; - } - out.effective.at(index).push_back(span); - coveredUntil.at(span.column) = end; - } - std::ranges::sort(out.effective.at(index), {}, &RowSpan::column); - } - return out; -} +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one refusal per rule of a span. +[[nodiscard]] MORPH_API ResolvedSpans resolveRowSpans(std::vector const& rows, std::size_t columns, + std::span const> placeOf = {}); /// @brief Called for each newly mounted row with its widget and key; a Table tells its widget the row's key. using RowHook = std::function; @@ -209,15 +390,11 @@ struct VisibleRange { }; /// @brief The mounted rows of one ForEach or Table, in their container's order. -struct KeyedRows { +struct MORPH_API KeyedRows { KeyedRows() = default; /// @brief Unmounts the rows last first, as a container's children are; a vector's own destruction order differs /// between standard libraries. - ~KeyedRows() { - while (!list.empty()) { - list.pop_back(); - } - } + ~KeyedRows(); KeyedRows(KeyedRows const&) = delete; KeyedRows& operator=(KeyedRows const&) = delete; KeyedRows(KeyedRows&&) = delete; @@ -233,29 +410,7 @@ struct KeyedRows { /// order relative to each other and stay where they are, and every other one is moved once. /// @param sequence A permutation of `0 .. n-1`. /// @return Indexed by target position: whether that widget stays. -[[nodiscard]] inline std::vector stableTargets(std::vector const& sequence) { - constexpr auto kNone = static_cast(-1); - std::vector tails; // tails.at(n - 1): where the smallest tail of a run of length n sits - std::vector previous(sequence.size(), kNone); - for (std::size_t i = 0; i < sequence.size(); ++i) { - auto const place = std::ranges::lower_bound(tails, sequence.at(i), {}, - [&sequence](std::size_t entry) { return sequence.at(entry); }); - auto const length = static_cast(place - tails.begin()); - if (length > 0) { - previous.at(i) = tails.at(length - 1); - } - if (length == tails.size()) { - tails.push_back(i); - } else { - tails.at(length) = i; - } - } - std::vector stable(sequence.size(), false); - for (std::size_t cursor = tails.empty() ? kNone : tails.back(); cursor != kNone; cursor = previous.at(cursor)) { - stable.at(sequence.at(cursor)) = true; - } - return stable; -} +[[nodiscard]] MORPH_API std::vector stableTargets(std::vector const& sequence); /// @brief Brings a container's children from their current order into the target order with `moveChild`, /// moving only the children outside a longest run already in order. @@ -263,42 +418,8 @@ struct KeyedRows { /// @param current Its children, in their current order. Kept equal to the container's order after every move, so /// it is still that order when a move throws. /// @param target The same children, in the order wanted. -inline void reorderChildren(ContainerWidget& container, std::vector& current, - std::vector const& target) { - std::unordered_map targetOf; - for (std::size_t i = 0; i < target.size(); ++i) { - targetOf.emplace(target.at(i), i); - } - std::vector sequence; - sequence.reserve(current.size()); - for (Widget const* const child : current) { - sequence.push_back(targetOf.at(child)); - } - std::vector const stable = stableTargets(sequence); - auto const indexOf = [¤t](Widget const* child) { - return static_cast(std::ranges::find(current, child) - current.begin()); - }; - // From the back: each moved child goes directly before its successor in the target order, which is already - // in place, so one move per unstable child suffices. - for (std::size_t position = target.size(); position-- > 0;) { - if (stable.at(position)) { - continue; - } - Widget* const moving = target.at(position); - std::size_t const from = indexOf(moving); - std::size_t destination = current.size() - 1; - if (position + 1 < target.size()) { - std::size_t const before = indexOf(target.at(position + 1)); - destination = from < before ? before - 1 : before; - } - if (destination == from) { - continue; - } - container.moveChild(*moving, destination); - current.erase(current.begin() + static_cast(from)); - current.insert(current.begin() + static_cast(destination), moving); - } -} +MORPH_API void reorderChildren(ContainerWidget& container, std::vector& current, + std::vector const& target); /// @brief Where one Tabs keeps its pages: a slot per tab, made the first time the tab is selected and kept, hidden, /// after. @@ -317,7 +438,7 @@ struct Pages { /// /// One per `Mounted`. It must outlive every scope it mounted into: a Switch, Tabs, Dialog, ForEach or Table binding /// calls back into it to mount content later. -class Mounter { +class MORPH_API Mounter { public: /// @param runtime The runtime bindings are made in. Borrowed. /// @param backend Makes the widgets. Borrowed. @@ -332,20 +453,22 @@ class Mounter { /// @param node The node; null mounts nothing. /// @param parent The container to append to, or null for a root. /// @return The node's widget, or null for a null node. - Widget* mount(reactive::Scope& scope, Node const& node, ContainerWidget* parent) { - if (!node) { - return nullptr; - } - return std::visit( - [&](auto const& spec) -> Widget* { - if constexpr (requires { spec.common.layout.alignSelf; }) { - checkPlacement(spec.common, parent); - checkShare(spec.common, parent); - } - return &this->mountKind(scope, spec, parent); - }, - node->kind); - } + Widget* mount(reactive::Scope& scope, Node const& node, ContainerWidget* parent); + + /// @brief Moves keyboard focus along the focus chain from the mounted widget whose `focusId` is @p focusId. + /// @param focusId The name. + /// @param forward Whether to the next control, or the previous one. + /// @return Whether a control took focus. + bool focusAlong(std::string_view focusId, bool forward); + + /// @brief Moves keyboard focus along the focus chain from @p from: the mounted widgets that take focus (a text + /// input, a button, a check box, a select, a menu, a date-time input, a slider, a file picker, a table, a + /// tabs, a badge that can be removed), shown and enabled with every container around them, in document + /// order, walked when asked. + /// @param from The widget focus leaves. + /// @param forward Whether to the next control, or the previous one. + /// @return Whether a control took focus; `false` when none lies that way. + bool focusAlong(Widget const& from, bool forward); /// @brief Mounts @p node as `mount` does, as a mount of its own: the first `autofocus` widget it mounts, in /// document order, takes keyboard focus once the whole of it has mounted. @@ -357,25 +480,21 @@ class Mounter { return mountPass([&] { return mount(scope, node, parent); }); } + /// @brief What the mount did to the rows of its source tables. + /// @return The counters. + [[nodiscard]] MountStats const& stats() const noexcept { return _stats; } + + /// @brief The column extents of the table over a `TableSource` mounted last, for tests. + /// @return They, or null when no such table is mounted. + [[nodiscard]] ColumnExtents const* columnExtents() const noexcept { return _extents.lock().get(); } + /// @brief Moves keyboard focus to the mounted widget whose `focusId` is @p focusId. /// /// Of several such widgets (rows of a list), the one mounted first is taken. A backend that cannot move focus /// leaves it where it was; the request was still made. /// @param focusId The name. /// @return Whether a mounted widget has that name. - bool focus(std::string_view focusId) { - // lower_bound, not find: of equal names, find may answer any; lower_bound answers the first inserted. - auto const found = _focusable.lower_bound(focusId); - if (found == _focusable.end() || found->first != focusId) { - return false; - } - try { - found->second->focus(); - } catch (...) { // NOLINT(bugprone-empty-catch) - // Focus is a request: a backend that cannot move it leaves it where it was. - } - return true; - } + bool focus(std::string_view focusId); /// @brief Moves the text cursor of the mounted text input whose `focusId` is @p focusId to @p offset, focuses it /// and asks it to reveal the cursor's line. @@ -385,26 +504,7 @@ class Mounter { /// @param focusId The name. /// @param offset A byte offset into the text it shows. /// @return Whether a mounted text input has that name. - bool placeCursor(std::string_view focusId, std::size_t offset) { - auto const found = _focusable.lower_bound(focusId); - if (found == _focusable.end() || found->first != focusId) { - return false; - } - auto* const field = dynamic_cast(found->second); - if (field == nullptr) { - return false; - } - field->setCursor(offset); - try { - field->focus(); - } catch (...) { // NOLINT(bugprone-empty-catch) - // Focus is a request: a backend that cannot move it leaves it where it was. - } - // After the focus: a scroll that follows focus has moved to the field as a whole by now, and the cursor's - // line is what is then brought into view. - field->revealCursor(); - return true; - } + bool placeCursor(std::string_view focusId, std::size_t offset); private: // Runs @p body with @p overlay as the overlay an ActionBar mounts into the footer of, and puts the previous one @@ -429,15 +529,7 @@ class Mounter { } // The footer of the overlay whose content is being mounted, or null outside any. - [[nodiscard]] ContainerWidget* overlayFooter() const { - if (auto* const dialog = dynamic_cast(_overlay)) { - return &dialog->footer(); - } - if (auto* const drawer = dynamic_cast(_overlay)) { - return &drawer->footer(); - } - return nullptr; - } + [[nodiscard]] ContainerWidget* overlayFooter() const; // One mount: the root, or content, a page or a row a binding mounts later. The outermost pass focuses the first // autofocus widget mounted during it, in document order, after everything in it has mounted; a pass nested in @@ -616,145 +708,115 @@ class Mounter { // The loader's rules for bounds, for a view tree built in C++: no negative bound, no minimum above its maximum, // and no fixed amount outside its bounds, which would leave it no room. - static void checkLayout(Common const& common) { - LayoutHints const& hints = common.layout; - auto const refuse = [&common](std::string const& what) { - throw std::logic_error{"morph::ui::mount: " + what + " on the node" + - (common.testId.empty() ? std::string{} : " `" + common.testId + "`")}; - }; - auto const check = [&refuse](Sizing sizing, std::optional minimum, std::optional maximum, - std::string const& axis) { - if (minimum.value_or(0) < 0 || maximum.value_or(0) < 0) { - refuse("a negative " + axis + " bound"); - } - if (minimum && maximum && *minimum > *maximum) { - refuse("a minimum " + axis + " above its maximum"); - } - if (sizing.kind == Sizing::Kind::Fixed && - (sizing.amount < minimum.value_or(sizing.amount) || sizing.amount > maximum.value_or(sizing.amount))) { - refuse("a fixed " + axis + " outside its bounds"); - } - }; - check(hints.width, hints.minWidth, hints.maxWidth, "width"); - check(hints.height, hints.minHeight, hints.maxHeight, "height"); - if (hints.width.kind == Sizing::Kind::Percent && (hints.width.amount < 1 || hints.width.amount > 100)) { - refuse("a percent width outside 1 to 100"); - } - if (hints.height.kind == Sizing::Kind::Percent) { - refuse("a percent height; a percent sizes a width"); - } - } + static void checkLayout(Common const& common); // The loader's rule for `percent`, for a view tree built in C++: a share of its container's width is a width along // a row that does not wrap, a horizontal `forEach` that does not wrap, or a horizontal splitter's pane. - void checkShare(Common const& common, ContainerWidget const* parent) const { - if (common.layout.width.kind == Sizing::Kind::Percent && !_shareParents.contains(parent)) { - std::string const named = common.testId.empty() ? std::string{} : " (node `" + common.testId + "`)"; - throw std::logic_error{ - "morph::ui::mount: `percent` sizes a width along a row or a horizontal splitter; " - "nothing here takes a share" + - named}; - } - } + void checkShare(Common const& common, ContainerWidget const* parent) const; // A grid track's or a table column's width is no share. - static void checkNoShare(std::span tracks) { - if (std::ranges::any_of(tracks, - [](GridTrack const& track) { return track.width.kind == Sizing::Kind::Percent; })) { - throw std::logic_error{ - "morph::ui::mount: a grid track is sized by the grid; `percent` sizes a width " - "along a row or a horizontal splitter"}; - } - } - static void checkNoShare(std::span columns) { - if (std::ranges::any_of( - columns, [](TableColumn const& column) { return column.width.kind == Sizing::Kind::Percent; })) { - throw std::logic_error{ - "morph::ui::mount: a table column is sized by the table; `percent` sizes a width " - "along a row or a horizontal splitter"}; - } - } + static void checkNoShare(std::span tracks); + static void checkNoShare(std::span columns); // A dialog or a drawer is sized by the frontend, not by its container: Stretch sizing on one would silently // change how every *other* sibling in its own parent layout is justified. Covers both the document path's own // computed (non-literal) `sizing` -- resolved to a Sizing only here, at mount time, since the document-level // checkSizing validates only a literal one -- and a C++ author calling ui::dialog()/ui::drawer() directly, both // of which reach this same mountKind overload before either backend ever sees the result. - static void checkOverlayLayout(Common const& common, std::string_view kind) { - LayoutHints const& hints = common.layout; - auto const refuse = [&common, kind](std::string const& axis) { - throw std::logic_error{"morph::ui::mount: a " + std::string{kind} + - " is sized by the frontend, not by its container; its " + axis + " cannot stretch" + - (common.testId.empty() ? std::string{} : " (node `" + common.testId + "`)")}; - }; - if (hints.width.kind == Sizing::Kind::Stretch) { - refuse("width"); - } - if (hints.width.kind == Sizing::Kind::Percent) { - throw std::logic_error{"morph::ui::mount: a " + std::string{kind} + - " is sized by the frontend, not by its container; its width takes no share"}; - } - if (hints.height.kind == Sizing::Kind::Stretch) { - refuse("height"); - } - } + static void checkOverlayLayout(Common const& common, std::string_view kind); // The loader's rule for `alignSelf`, for a view tree built in C++: only a stack's or a grid's child has a cross // axis to be placed on. - static void checkPlacement(Common const& common, ContainerWidget const* parent) { - if (common.layout.alignSelf && dynamic_cast(parent) == nullptr && - dynamic_cast(parent) == nullptr) { - std::string const named = common.testId.empty() ? std::string{} : " `" + common.testId + "`"; - throw std::logic_error{ - "morph::ui::mount: `alignSelf` places a node in its row, column or grid, and the node" + named + - " is not in one"}; - } - } + static void checkPlacement(Common const& common, ContainerWidget const* parent); - void applyCommon(reactive::Scope& scope, Widget& widget, Common const& common) { - if (common.visible.isBound() || !common.visible.constant()) { - bind(scope, common.visible, [&widget](bool shown) { widget.setVisible(shown); }); - } - if (common.enabled.isBound() || !common.enabled.constant()) { - bind(scope, common.enabled, [&widget](bool enabled) { widget.setEnabled(enabled); }); - } - if (common.layout != LayoutHints{}) { - checkLayout(common); - widget.setLayout(common.layout); - } - if (common.dragKey.isBound() || common.dragKey.constant().has_value()) { - bind(scope, common.dragKey, [&widget](std::optional const& key) { widget.setDragKey(key); }); - } - if (common.onDrop) { - applyDrop(widget, common); - } - if (common.a11y.name.isBound() || !common.a11y.name.constant().empty()) { - bind(scope, common.a11y.name, [&widget](std::string const& name) { widget.setAccessibleName(name); }); - } - if (!common.a11y.role.empty()) { - widget.setAccessibleRole(common.a11y.role); - } - if (!common.testId.empty()) { - widget.setTestId(common.testId); - } - if (common.tooltip.isBound() || !common.tooltip.constant().empty()) { - bind(scope, common.tooltip, [&widget](std::string const& text) { widget.setTooltip(text); }); - } - if (common.surface.isBound() || !common.surface.constant().empty()) { - bind(scope, common.surface, [&widget](std::string const& surface) { widget.setSurface(surface); }); - } - if (!common.keys.empty()) { - applyKeys(widget, common.keys); + // NOLINTNEXTLINE(readability-function-cognitive-complexity): applies each common property (visible, enabled, tooltip, keys and so on) to the widget; each binds against the same scope + void applyCommon(reactive::Scope& scope, Widget& widget, Common const& common); + + using FocusMap = std::multimap>; + + // One widget of the focus chain's tree: the container `mount` appended it to, its children in their order, and + // whether it takes focus. A container a node did not mount (a table's row) has an entry while it has children, + // and no parent: what is inside it is not on the chain. + struct ChainEntry { + Widget const* parent = nullptr; + std::vector children; + bool takesFocus = false; + bool linked = false; + }; + + // Whether a widget is shown and enabled, as its `Common` says now, while it has a bound or non-default one. + struct MORPH_API ChainFlags { + ChainFlags(std::unordered_map>& owner, Widget const* widget) + : flags{&owner}, of{widget} { + flags->insert_or_assign(of, std::pair{true, true}); } - if (common.autofocus && _autofocus == nullptr) { - _autofocus = &widget; + ChainFlags(ChainFlags const&) = delete; + ChainFlags& operator=(ChainFlags const&) = delete; + ChainFlags(ChainFlags&&) = delete; + ChainFlags& operator=(ChainFlags&&) = delete; + ~ChainFlags() { flags->erase(of); } + + void set(bool visible, bool value) const; + + std::unordered_map>* flags; + Widget const* of; + }; + + // A mounted widget's place in the chain's tree, owned by its scope after the widget and its content, so it is let + // go before them. + struct ChainLink { + ChainLink(Mounter& owner, Widget* widget) noexcept : mounter{&owner}, of{widget} {} + ChainLink(ChainLink const&) = delete; + ChainLink& operator=(ChainLink const&) = delete; + ChainLink(ChainLink&&) = delete; + ChainLink& operator=(ChainLink&&) = delete; + ~ChainLink() { mounter->unlink(of); } + + Mounter* mounter; + Widget* of; + }; + + // A container whose content is not on the chain, registered while it is mounted. + struct OffChain { + OffChain(std::unordered_set& owner, Widget const* container) : set{&owner}, of{container} { + set->insert(of); } - if (!common.focusId.empty()) { - scope.make(_focusable, _focusable.emplace(common.focusId, &widget)); + OffChain(OffChain const&) = delete; + OffChain& operator=(OffChain const&) = delete; + OffChain(OffChain&&) = delete; + OffChain& operator=(OffChain&&) = delete; + ~OffChain() { set->erase(of); } + + std::unordered_set* set; + Widget const* of; + }; + + // Which nodes take focus: the controls a user tabs through. + template + [[nodiscard]] static bool takesFocus(Spec const& spec) { + if constexpr (std::is_same_v) { + return static_cast(spec.onRemove); + } else { + return std::is_same_v || std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v || + std::is_same_v; } } - using FocusMap = std::multimap>; + // Records a widget a node mounted as its container's last child. A widget mounted twice over (a cell's content, + // mounted for its accented or marked cell) keeps its first place. + void link(reactive::Scope& scope, Widget& widget, ContainerWidget const* parent, bool focusable); + + void unlink(Widget* widget) noexcept; + + // Brings a container's children in the chain's tree to the order the mount moved them to. + void reorderChain(Widget const& container, std::vector const& order); + + // The widgets that take focus under @p widget, in document order, each with whether it is shown and enabled with + // every container around it. + // NOLINTNEXTLINE(misc-no-recursion): a container's children are walked in turn. + void chainOrder(Widget& widget, bool shown, std::vector>& out) const; // A container whose children may be sized by a share of its width, registered while it is mounted. struct ShareParent { @@ -774,92 +836,35 @@ class Mounter { // A widget's entry in the focus map, owned by the widget's scope after the widget, so it leaves the map before // the widget is destroyed. - struct Focusable { - Focusable(FocusMap& owner, FocusMap::iterator added) noexcept : map{&owner}, entry{added} {} + struct MORPH_API Focusable { + Focusable(FocusMap& owner, std::optional added) noexcept : map{&owner}, entry{added} {} Focusable(Focusable const&) = delete; Focusable& operator=(Focusable const&) = delete; Focusable(Focusable&&) = delete; Focusable& operator=(Focusable&&) = delete; - ~Focusable() { map->erase(entry); } + ~Focusable() { reset(std::nullopt); } + + // Forgets the entry held and holds @p next instead. + void reset(std::optional next) noexcept; FocusMap* map; - FocusMap::iterator entry; + std::optional entry; }; // No predicate accepts every key; a predicate that throws refuses the drop. - void applyDrop(Widget& widget, Common const& common) { - std::function accepts = [](Key const&) { return true; }; - if (common.accepts) { - accepts = [runtime = _rt, predicate = common.accepts](Key const& key) { - bool accepted = false; - static_cast(runCallback(*runtime, [&] { accepted = predicate(key); })); - return accepted; - }; - } - widget.setDropHandler(std::move(accepts), event(common.onDrop)); - } + void applyDrop(Widget& widget, Common const& common); // One setKeys for all the chords; a chord listed twice runs its first binding, as a widget callback. - void applyKeys(Widget& widget, std::vector const& keys) { - std::vector chords; - chords.reserve(keys.size()); - for (KeyBinding const& binding : keys) { - chords.push_back(binding.chord); - } - widget.setKeys(chords, [runtime = _rt, keys](std::string const& chord) { - auto const bound = std::ranges::find(keys, chord, &KeyBinding::chord); - if (bound != keys.end() && bound->onPress) { - static_cast(runCallback(*runtime, bound->onPress)); - } - }); - } + void applyKeys(Widget& widget, std::vector const& keys); - void mountChildren(reactive::Scope& scope, std::vector const& children, ContainerWidget& container) { - for (Node const& child : children) { - static_cast(mount(scope, child, &container)); - } - } + void mountChildren(reactive::Scope& scope, std::vector const& children, ContainerWidget& container); // The alignment only when it is not the default, as for a button's emphasis, so a stack that says nothing more // costs no call. Widget& mountStack(reactive::Scope& scope, Axis axis, std::vector const& children, int gap, Common const& common, ContainerWidget* parent, Align align = Align::Stretch, Justify justify = Justify::Start, bool wrap = false, bool divided = false, Padding padding = {}, - std::optional> const& selected = std::nullopt, bool holder = false) { - StackWidget& widget = scope.adopt(_backend->createStack(parent, axis)); - if (holder) { - widget.setPassesBleed(true); - } - if (axis == Axis::Horizontal && !wrap && dynamic_cast(parent) == nullptr) { - scope.make(_shareParents, &widget); - } - if (wrap) { - widget.setWrap(true); - } - if (divided) { - widget.setDivided(true); - } - if (Padding const inset = clampedPadding(padding); inset != Padding{}) { - widget.setPadding(inset); - } - applyCommon(scope, widget, common); - if (selected) { - bind(scope, *selected, [&widget](bool chosen) { widget.setSelected(chosen); }); - } - widget.setGap(spacingStep(gap)); - if (align != Align::Stretch) { - widget.setAlign(align); - } - if (justify != Justify::Start) { - widget.setJustify(justify); - } - if (startsHidden(common) && dynamic_cast(parent) == nullptr) { - mountWhenShown(scope, children, widget, common.visible); - } else { - mountChildren(scope, children, widget); - } - return widget; - } + std::optional> const& selected = std::nullopt, bool holder = false); // Whether a node's `visible` is false as it mounts. static bool startsHidden(Common const& common) { @@ -870,25 +875,7 @@ class Mounter { // becomes true, into a scope of their own one level deeper than the stack's. They stay mounted after that, and // hiding the stack again only hides it. A `visible` that is a constant `false` never shows, so they never mount. void mountWhenShown(reactive::Scope& scope, std::vector const& children, ContainerWidget& container, - Prop const& visible) { - if (!visible.isBound()) { - return; - } - reactive::Scope& content = scope.child(); - bool& mounted = scope.make(false); - bind(scope, visible, [this, &content, &container, &mounted, children](bool shown) { - if (!shown || mounted) { - return; - } - mounted = true; - _rt->untracked([&] { - mountPass([&] { - mountChildren(content, children, container); - return 0; - }); - }); - }); - } + Prop const& visible); // A path through a menu tree: an index at each level from the top. using MenuPath = std::vector; @@ -914,54 +901,10 @@ class Mounter { // NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. [[nodiscard]] static std::vector shownLevel(std::vector const& items, MenuLevelAt const& where, - std::map& sources) { - std::vector entries; - auto const record = [&](std::size_t source) { - MenuPath shownPath = where.shown; - shownPath.push_back(entries.size() - 1); - MenuPath sourcePath = where.source; - sourcePath.push_back(source); - sources.insert_or_assign(std::move(shownPath), std::move(sourcePath)); - }; - for (std::size_t source = 0; source < items.size(); ++source) { - MenuItem const& item = items.at(source); - if (item.separator) { - if (!entries.empty() && !entries.back().separator) { - entries.push_back(MenuEntry{.separator = true}); - record(source); - } - continue; - } - if (!item.visible.evaluate()) { - continue; - } - MenuLevelAt child = where; - child.shown.push_back(entries.size()); - child.source.push_back(source); - entries.push_back(MenuEntry{.label = item.label.evaluate(), - .icon = item.icon, - .keys = item.keys, - .checked = item.checked.evaluate(), - .enabled = item.enabled.evaluate(), - .items = shownLevel(item.items, child, sources), - .description = item.description.evaluate()}); - record(source); - } - if (!entries.empty() && entries.back().separator) { - MenuPath last = where.shown; - last.push_back(entries.size() - 1); - sources.erase(last); - entries.pop_back(); - } - return entries; - } + std::map& sources); // The visible entries as the widget shows them; called inside the menu's one binding. - [[nodiscard]] static ShownMenu shownOf(std::vector const& items) { - ShownMenu shown; - shown.entries = shownLevel(items, MenuLevelAt{}, shown.sources); - return shown; - } + [[nodiscard]] static ShownMenu shownOf(std::vector const& items); // Whether any entry, at any depth, has a bound label, description, check mark, enablement or visibility. // NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. @@ -972,29 +915,11 @@ class Mounter { // Whether this entry, or one in its submenu, has a bound label, description, check mark, enablement or // visibility. // NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. - [[nodiscard]] static bool entryBound(MenuItem const& item) { - return item.label.isBound() || item.description.isBound() || item.checked.isBound() || - item.enabled.isBound() || item.visible.isBound() || anyBound(item.items); - } + [[nodiscard]] static bool entryBound(MenuItem const& item); // The item a path through the shown entries names, or null when it names none or a separator. [[nodiscard]] static MenuItem const* itemAt(std::vector const& items, - std::map const& sources, MenuPath const& path) { - auto const found = sources.find(path); - if (found == sources.end()) { - return nullptr; - } - std::vector const* level = &items; - MenuItem const* item = nullptr; - for (std::size_t const index : found->second) { - if (index >= level->size()) { - return nullptr; - } - item = &level->at(index); - level = &item->items; - } - return item == nullptr || item->separator ? nullptr : item; - } + std::map const& sources, MenuPath const& path); /// An input's label and whether it shows it: only when it has a label or shows one, so an input without a label /// is told nothing. @@ -1012,302 +937,43 @@ class Mounter { } // Like applyCommon, a constant default calls no setter. - void applyField(reactive::Scope& scope, FieldWidget& widget, FieldState const& field) { - if (field.readonly.isBound() || field.readonly.constant()) { - bind(scope, field.readonly, [&widget](bool readonly) { widget.setReadOnly(readonly); }); - } - if (field.required.isBound() || field.required.constant()) { - bind(scope, field.required, [&widget](bool required) { widget.setRequired(required); }); - } - if (field.errors.isBound() || !field.errors.constant().empty()) { - bind(scope, field.errors, [&widget](std::vector const& errors) { widget.setErrors(errors); }); - } - if (field.stale.isBound() || field.stale.constant()) { - bind(scope, field.stale, [&widget](bool stale) { widget.setStale(stale); }); - } - if (field.description.isBound() || !field.description.constant().empty()) { - bind(scope, field.description, - [&widget](std::string const& description) { widget.setDescription(description); }); - } - if (field.labelHint.isBound() || !field.labelHint.constant().empty()) { - bind(scope, field.labelHint, [&widget](std::string const& hint) { widget.setCaptionHint(hint); }); - } - if (field.tone.isBound() || field.tone.constant() != Tone::Neutral) { - bind(scope, field.tone, [&widget](Tone tone) { widget.setTone(tone); }); - } - } + void applyField(reactive::Scope& scope, FieldWidget& widget, FieldState const& field); - Widget& mountKind(reactive::Scope& scope, Text const& spec, ContainerWidget* parent) { - if (spec.field.description.isBound() || !spec.field.description.constant().empty()) { - throw std::logic_error{"morph::ui: a text is not described; put the line in the text"}; - } - if (spec.field.labelHint.isBound() || !spec.field.labelHint.constant().empty()) { - throw std::logic_error{"morph::ui: a text has no caption to hint after; put the hint in the text"}; - } - TextWidget& widget = scope.adopt(_backend->createText(parent)); - applyCommon(scope, widget, spec.common); - applyField(scope, widget, spec.field); - // Spans replace the text, so a text that has them is never told its plain text. - if (hasSpans(spec.spans)) { - bind(scope, spec.spans, [&widget](std::vector const& spans) { widget.setSpans(spans); }); - } else { - bind(scope, spec.text, [&widget](std::string const& text) { widget.setText(text); }); - } - bind(scope, spec.role, [&widget](TextRole role) { widget.setRole(role); }); - if (spec.align) { - widget.setAlign(*spec.align); - } - return widget; - } + Widget& mountKind(reactive::Scope& scope, Text const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Button const& spec, ContainerWidget* parent) { - if (spec.style == ButtonStyle::Push && spec.child != nullptr) { - throw std::logic_error{"morph::ui: only a list entry holds content; a push button has a label"}; - } - ButtonWidget& widget = scope.adopt(_backend->createButton(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.label, [&widget](std::string const& label) { widget.setLabel(label); }); - if (spec.emphasis != ButtonEmphasis::Normal) { - widget.setEmphasis(spec.emphasis); - } - if (!spec.icon.empty()) { - widget.setIcon(spec.icon); - } - if (spec.style == ButtonStyle::Item) { - widget.setStyle(spec.style); - } - if (spec.shape != ControlShape::Default) { - widget.setShape(spec.shape); - } - if (spec.size != ButtonSize::Normal) { - widget.setSize(spec.size); - } - if (spec.mono) { - widget.setMono(true); - } - if (spec.weight != 0) { - widget.setWeight(spec.weight); - } - if (spec.selected.isBound() || spec.selected.constant()) { - bind(scope, spec.selected, [&widget](bool selected) { widget.setSelected(selected); }); - } - widget.setOnClick(event(spec.onClick)); - if (spec.child != nullptr) { - static_cast(mount(scope, spec.child, &widget.content())); - } - return widget; - } + Widget& mountKind(reactive::Scope& scope, Button const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, TextInput const& spec, ContainerWidget* parent) { - bool const hasUnit = spec.unit.isBound() || !spec.unit.constant().empty(); - bool const hasPrefix = spec.prefix.isBound() || !spec.prefix.constant().empty(); - bool const hasDecimals = spec.decimals.isBound() || spec.decimals.constant() >= 0; - if ((hasUnit || hasPrefix || hasDecimals || !spec.icon.empty()) && spec.mode == TextInputMode::Multiline) { - throw std::logic_error{ - "morph::ui: a multiline text input holds no number, so it takes no unit, prefix, places or icon"}; - } - if (spec.align != Align::Start && spec.mode == TextInputMode::Multiline) { - throw std::logic_error{"morph::ui: a multiline text input's text starts at the leading edge"}; - } - if (spec.emphasis != InputEmphasis::Normal && spec.mode == TextInputMode::Multiline) { - throw std::logic_error{"morph::ui: a multiline text input's size is its own; it takes no emphasis"}; - } - TextInputWidget& widget = scope.adopt(_backend->createTextInput(parent, spec.mode)); - applyCommon(scope, widget, spec.common); - applyField(scope, widget, spec.field); - auto reassert = controlled(scope, spec.value, [&widget](std::string const& value) { widget.setText(value); }); - bind(scope, spec.placeholder, [&widget](std::string const& text) { widget.setPlaceholder(text); }); - // An input without a unit or places is not told any, so a backend sees only what a field declares. - if (hasUnit) { - bind(scope, spec.unit, [&widget](std::string const& unit) { widget.setUnit(unit); }); - } - if (hasPrefix) { - bind(scope, spec.prefix, [&widget](std::string const& prefix) { widget.setPrefix(prefix); }); - } - if (hasDecimals) { - bind(scope, spec.decimals, [&widget](int decimals) { widget.setDecimals(decimals); }); - } - if (!spec.icon.empty()) { - widget.setIcon(spec.icon); - } - if (spec.emphasis != InputEmphasis::Normal) { - widget.setEmphasis(spec.emphasis); - } - if (spec.mono) { - widget.setMono(true); - } - if (!spec.wrap) { - widget.setWrap(false); - } - if (spec.align != Align::Start) { - widget.setAlign(spec.align); - } - applyCaption(scope, widget, spec.label, spec.showLabel); - widget.setOnChange(inputEvent(spec.onChange, reassert)); - // An empty submit handler tells the backend the field does not submit, so Enter goes on to its ancestors' - // chords (a dialog's default) once the field has committed. - widget.setOnSubmit(spec.onSubmit ? inputEvent(spec.onSubmit, std::move(reassert)) - : std::function{}); - widget.setOnCommit(event(spec.onCommit)); - return widget; - } + Widget& mountKind(reactive::Scope& scope, TextInput const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Checkbox const& spec, ContainerWidget* parent) { - CheckboxWidget& widget = scope.adopt(_backend->createCheckbox(parent)); - applyCommon(scope, widget, spec.common); - applyField(scope, widget, spec.field); - bind(scope, spec.label, [&widget](std::string const& label) { widget.setLabel(label); }); - widget.setOnToggle(inputEvent( - spec.onToggle, controlled(scope, spec.checked, [&widget](bool checked) { widget.setChecked(checked); }))); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Checkbox const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Select const& spec, ContainerWidget* parent) { - SelectWidget& widget = scope.adopt(_backend->createSelect(parent, spec.style)); - applyCommon(scope, widget, spec.common); - applyField(scope, widget, spec.field); - bind(scope, spec.options, [&widget](std::vector const& options) { widget.setOptions(options); }); - widget.setOnSelect(inputEvent( - spec.onSelect, - controlled(scope, spec.selected, [&widget](std::optional const& key) { widget.setSelected(key); }))); - widget.setOnOpen(event(spec.onOpen)); - applyCaption(scope, widget, spec.label, spec.showLabel); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Select const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Menu const& spec, ContainerWidget* parent) { - MenuWidget& widget = scope.adopt(_backend->createMenu(parent, spec.style)); - applyCommon(scope, widget, spec.common); - if (spec.style == MenuStyle::Button) { - bind(scope, spec.label, [&widget, icon = spec.icon, emphasis = spec.emphasis](std::string const& label) { - widget.setTrigger(MenuTrigger{.label = label, .icon = icon, .emphasis = emphasis}); - }); - } - std::vector const& items = spec.items; - // One prop for the whole tree: a bound label, description, mark, enablement or visibility anywhere re-sends - // every entry, which keeps setItems the one setter. A reported path is read against what was last sent. - auto sent = std::make_shared>(); - Prop const shown = anyBound(items) ? Prop([items = items] { return shownOf(items); }) - : Prop(shownOf(items)); - bind(scope, shown, [&widget, sent](ShownMenu const& menu) { - *sent = menu.sources; - widget.setItems(menu.entries); - }); - widget.setOnActivate(event( - std::function)>{[items = items, sent](std::vector const& path) { - MenuItem const* const item = itemAt(items, *sent, path); - if (item != nullptr && item->onSelect) { - item->onSelect(); - } - }})); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Menu const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Column const& spec, ContainerWidget* parent) { - return mountStack(scope, Axis::Vertical, spec.children, spec.gap, spec.common, parent, spec.align, - spec.justify, false, spec.divided, spec.padding, spec.selected, spec.holder); - } + Widget& mountKind(reactive::Scope& scope, Column const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Row const& spec, ContainerWidget* parent) { - if ((spec.tone || spec.label || spec.heading || spec.spans) && dynamic_cast(parent) == nullptr) { - throw std::logic_error{ - "morph::ui: a row's tone, label, heading and spans are a table row's; this row is not in a table"}; - } - if (spec.selected && dynamic_cast(parent) != nullptr) { - throw std::logic_error{"morph::ui: a table row's selection is the table's; this row gives its own"}; - } - return mountStack(scope, Axis::Horizontal, spec.children, spec.gap, spec.common, parent, spec.align, - spec.justify, spec.wrap, spec.divided && !spec.wrap, spec.padding, spec.selected); - } + Widget& mountKind(reactive::Scope& scope, Row const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Grid const& spec, ContainerWidget* parent) { - GridWidget& widget = scope.adopt(_backend->createGrid(parent)); - applyCommon(scope, widget, spec.common); - checkNoShare(spec.tracks); - if (spec.tracks.empty()) { - widget.setColumns(spec.columns); - } else { - widget.setTracks(spec.tracks); - } - if (spec.minColumnWidth > 0 && spec.tracks.empty()) { - widget.setMinColumnWidth(spec.minColumnWidth); - } - widget.setGap(spacingStep(spec.gap)); - if (spec.align != Align::Stretch) { - widget.setAlign(spec.align); - } - for (GridCell const& cell : spec.cells) { - Widget* const child = mount(scope, cell.node, &widget); - if (child != nullptr && cell.span != 1) { - widget.setSpan(*child, cell.span); - } - } - return widget; - } + Widget& mountKind(reactive::Scope& scope, Grid const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Spacer const& spec, ContainerWidget* parent) { - SpacerWidget& widget = scope.adopt(_backend->createSpacer(parent)); - applyCommon(scope, widget, spec.common); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Spacer const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Panel const& spec, ContainerWidget* parent) { - PanelWidget& widget = scope.adopt(_backend->createPanel(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.title, [&widget](std::string const& title) { widget.setTitle(title); }); - if (Widget* const header = mount(scope, spec.header, &widget); header != nullptr) { - widget.setHeader(*header); - } - widget.setPadding(spacingStep(spec.padding)); - widget.setCollapsible(spec.collapsible); - if (spec.collapsible) { - widget.setOnToggle(inputEvent(spec.onToggle, controlled(scope, spec.collapsed, [&widget](bool collapsed) { - widget.setCollapsed(collapsed); - }))); - } - static_cast(mount(scope, spec.child, &widget)); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Panel const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Scroll const& spec, ContainerWidget* parent) { - ScrollWidget& widget = scope.adopt(_backend->createScroll(parent, spec.axis)); - applyCommon(scope, widget, spec.common); - static_cast(mount(scope, spec.child, &widget)); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Scroll const& spec, ContainerWidget* parent); // Content a binding mounts (a Switch case, Dialog content), all or nothing: it is built in a scope of its own, // which the caller takes only once the mount completed, so content that throws partway leaves nothing behind. // Built untracked, so the binding's Effect depends on its own prop alone. The scope is one level deeper than the // one that owns the binding, so the owner's Effects run before the content's. [[nodiscard]] std::unique_ptr mountContent(std::size_t depth, Node const& node, - ContainerWidget& host) { - return mountPass([&] { - auto content = std::make_unique(*_rt, depth); - _rt->untracked([&] { static_cast(mount(*content, node, &host)); }); - return content; - }); - } + ContainerWidget& host); // reset() tears the old case down, newest first, before the new one is built. The Computed behind a bound // selector is equality-gated, so an unchanged key never gets here. A case that fails to mount leaves nothing for // its key; the next change of the key mounts again. - Widget& mountKind(reactive::Scope& scope, Switch const& spec, ContainerWidget* parent) { - SlotWidget& widget = scope.adopt(_backend->createSlot(parent)); - applyCommon(scope, widget, spec.common); - auto& content = scope.make>(); - bind(scope, spec.selector, - [this, &widget, &content, depth = scope.depth() + 1, cases = spec.cases, fallback = spec.fallback, - overlay = _overlay](Key const& key) { - content.reset(); - auto const chosen = std::ranges::find(cases, key, &SwitchCase::key); - Node const& node = chosen == cases.end() ? fallback : chosen->node; - if (node) { - content = underOverlay(overlay, [&] { return mountContent(depth, node, widget); }); - } - }); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Switch const& spec, ContainerWidget* parent); // Every page is owned by `pageScope`, a child scope made before the binding, so pages are destroyed newest first, // after the binding that shows them and before the tab bar. A scope fixes that order; a vector's element @@ -1319,64 +985,7 @@ class Mounter { // signals sees it as the change it is. The cost is that showPage also runs when something the binding reads // changes but the index does not: for a page that is mounted it only re-sends the highlight, and for a page that // failed it tries the mount again, once per run. - Widget& mountKind(reactive::Scope& scope, Tabs const& spec, ContainerWidget* parent) { - TabsWidget& widget = scope.adopt(_backend->createTabs(parent)); - applyCommon(scope, widget, spec.common); - if (spacingStep(spec.inset) != 0) { - widget.setInset(spacingStep(spec.inset)); - } - if (spec.pageInset) { - widget.setPageInset(spacingStep(*spec.pageInset)); - } - if (!spec.stripSurface.empty()) { - widget.setStripSurface(spec.stripSurface); - } - // One prop over every caption, as a menu's entries: a bound caption re-sends them all. The count never - // changes, so the widget keeps its highlight, the shown page and the focus across a relabel. - std::vector> captions; - captions.reserve(spec.tabs.size()); - for (Tab const& tab : spec.tabs) { - captions.push_back(tab.label); - } - auto labelsOf = [captions] { - std::vector labels; - labels.reserve(captions.size()); - for (Prop const& caption : captions) { - labels.push_back(caption.evaluate()); - } - return labels; - }; - Prop> const labels = std::ranges::any_of(captions, &Prop::isBound) - ? Prop>(std::move(labelsOf)) - : Prop>(labelsOf()); - bind(scope, labels, [&widget](std::vector const& shown) { widget.setTabs(shown); }); - if (spec.moreLabel.isBound() || spec.moreLabel.constant() != "More") { - bind(scope, spec.moreLabel, [&widget](std::string const& label) { widget.setMoreLabel(label); }); - } - auto& pageScope = scope.child(); - auto& pages = scope.make(); - pages.pageSlots.resize(spec.tabs.size(), nullptr); - // A bound index is controlled: after a pick, the bar highlights the page that is shown, so a pick the - // document refuses moves the highlight back. A constant index is not a slot, and the bar keeps the pick. - std::function reassert; - if (spec.selected.isBound()) { - reassert = reasserter( - scope, pages.highlighted, - [&pages] { return pages.shown.value_or(std::numeric_limits::max()); }, - [&widget, &pages](std::size_t index) { highlight(widget, pages, index); }); - } - widget.setOnSelect(inputEvent(spec.onSelect, reassert)); - pages.onSelect = inputEvent(spec.onSelect, std::move(reassert)); - auto show = [this, &widget, &pageScope, &pages, pageSpecs = spec.tabs, overlay = _overlay](std::size_t index) { - _rt->untracked([&] { showPage(widget, pageScope, pages, pageSpecs, index, overlay); }); - }; - if (!spec.selected.isBound()) { - show(spec.selected.constant()); - } else { - scope.effect([binding = spec.selected.binding(), show = std::move(show)] { show(binding()); }); - } - return widget; - } + Widget& mountKind(reactive::Scope& scope, Tabs const& spec, ContainerWidget* parent); // A page is mounted the first time its tab is selected and only hidden afterwards, so its widgets keep their // state (focus, scroll position, half-typed text) across tab switches. A new page is complete before anything @@ -1386,38 +995,10 @@ class Mounter { // Only the mount runs under the tabs' overlay, and that overlay is put back before a failure is reported: // reporting it may destroy the Mounted, and with it this Mounter. void showPage(TabsWidget& widget, reactive::Scope& pageScope, Pages& pages, std::vector const& pageSpecs, - std::size_t index, ContainerWidget* overlay) { - bool const exists = index < pageSpecs.size(); - bool const isNew = exists && pages.pageSlots.at(index) == nullptr; - if (isNew) { - try { - underOverlay(overlay, [&] { mountPage(widget, pageScope, pages, pageSpecs.at(index).node, index); }); - } catch (...) { - if (pages.shown.has_value()) { - restoreSelection(widget, pages, *pages.shown); - } - throw; - } - } - if (pages.shown != index) { - if (pages.shown.has_value() && *pages.shown < pages.pageSlots.size()) { - if (SlotWidget* const previous = pages.pageSlots.at(*pages.shown); previous != nullptr) { - previous->setVisible(false); - } - } - if (exists && !isNew) { - pages.pageSlots.at(index)->setVisible(true); - } - } - pages.shown = index; - highlight(widget, pages, index); - } + std::size_t index, ContainerWidget* overlay); // Moves the bar's highlight, and records it. - static void highlight(TabsWidget& widget, Pages& pages, std::size_t index) { - widget.setSelected(index); - pages.highlighted = index; - } + static void highlight(TabsWidget& widget, Pages& pages, std::size_t index); // After a page failed to mount: puts the bar's highlight back on the page still shown, and tells the application // through `onSelect`, so its index matches the widget and selecting the failed tab again is a change that mounts @@ -1428,38 +1009,11 @@ class Mounter { // // Nothing here may replace the failure being reported: the callback's wrapper reports what the callback throws, // and anything else thrown here is dropped. - static void restoreSelection(TabsWidget& widget, Pages& pages, std::size_t shown) noexcept { - try { - highlight(widget, pages, shown); - } catch (...) { // NOLINT(bugprone-empty-catch) - // The page's failure is the one reported; the bar keeps whatever highlight it had. - } - try { - std::function const onSelect = pages.onSelect; - if (onSelect) { - onSelect(shown); - } - } catch (...) { // NOLINT(bugprone-empty-catch) - // Only copying the wrapper can throw here; the application then keeps the failed index. - } - } + static void restoreSelection(TabsWidget& widget, Pages& pages, std::size_t shown) noexcept; // The page is built in a scope of its own and handed to `pageScope` once complete, so one that fails to mount // leaves nothing behind. - void mountPage(TabsWidget& widget, reactive::Scope& pageScope, Pages& pages, Node const& node, std::size_t index) { - auto page = mountPass([&] { - auto built = std::make_unique(*_rt, pageScope.depth()); - SlotWidget& slot = built->adopt(_backend->createSlot(&widget)); - // A page fills the area under the strip, pads itself by the node's `pageInset` and scrolls itself while - // its content overflows, as a workspace's page does. - slot.setLayout({.width = Sizing::stretch(), .height = Sizing::stretch()}); - slot.setScrollable(true); - static_cast(mount(*built, node, &slot)); - return std::pair{std::move(built), &slot}; - }); - pageScope.adopt(std::move(page.first)); - pages.pageSlots.at(index) = page.second; - } + void mountPage(TabsWidget& widget, reactive::Scope& pageScope, Pages& pages, Node const& node, std::size_t index); // The content is built before the overlay opens and torn down before it closes. Content that fails to mount // under a bound `open` leaves the dialog closed and calls `onDismiss`, so the application's `open` follows the @@ -1469,22 +1023,9 @@ class Mounter { // Effect's own run, which a Computed would miss, and then find the next opening unchanged. An Effect that runs // with `open` unchanged re-sends `setOpen`, and mounts content only if none is mounted: once per run while `open` // stays true over content that failed. - Widget& mountKind(reactive::Scope& scope, Dialog const& spec, ContainerWidget* parent) { - checkOverlayLayout(spec.common, "dialog"); - DialogWidget& widget = scope.adopt(_backend->createDialog(parent)); - applyCommon(scope, widget, spec.common); - if (spec.sheet.isBound() || spec.sheet.constant()) { - bind(scope, spec.sheet, [&widget](bool sheet) { widget.setSheet(sheet); }); - } - return mountOverlay(scope, spec, widget); - } + Widget& mountKind(reactive::Scope& scope, Dialog const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Drawer const& spec, ContainerWidget* parent) { - checkOverlayLayout(spec.common, "drawer"); - DrawerWidget& widget = scope.adopt(_backend->createDrawer(parent, spec.side)); - applyCommon(scope, widget, spec.common); - return mountOverlay(scope, spec, widget); - } + Widget& mountKind(reactive::Scope& scope, Drawer const& spec, ContainerWidget* parent); // A Dialog or a Drawer: the title, the dismissal, and content that exists only while open. template @@ -1568,39 +1109,9 @@ class Mounter { // It runs last, from a copy: it is a widget callback, which may destroy the Mounted and with it the dialog and // the Effect that called this; the caller only rethrows after it. Nothing thrown here may replace the failure // being reported. - static void dismissFailed(std::function const& onDismiss) noexcept { - try { - std::function const dismiss = onDismiss; - if (dismiss) { - dismiss(); - } - } catch (...) { // NOLINT(bugprone-empty-catch) - // Only copying the wrapper can throw here; the application then keeps `open` true. - } - } + static void dismissFailed(std::function const& onDismiss) noexcept; - Widget& mountKind(reactive::Scope& scope, ForEach const& spec, ContainerWidget* parent) { - StackWidget& widget = scope.adopt(_backend->createStack(parent, spec.axis)); - // A horizontal ForEach directly in an action bar is part of the row of actions, so its rows are the action - // gap apart, whatever gap the ForEach says. - bool const actionRow = spec.axis == Axis::Horizontal && _actionBar != nullptr && parent == _actionBar; - if (actionRow) { - widget.setActionRow(); - } - if (spec.axis == Axis::Horizontal && !spec.wrap) { - scope.make(_shareParents, &widget); - } - if (spec.wrap && spec.axis == Axis::Horizontal) { - widget.setWrap(true); - } - if (spec.divided && spec.axis == Axis::Vertical) { - widget.setDivided(true); - } - applyCommon(scope, widget, spec.common); - widget.setGap(spacingStep(actionRow ? 2 : spec.gap)); - mountRows(scope, spec.model, widget, {}, nullptr); - return widget; - } + Widget& mountKind(reactive::Scope& scope, ForEach const& spec, ContainerWidget* parent); // What a table remembers to resolve its rows' spans: each row's request, the rows in order, and the table's // conditions. The resolve runs after a reconcile has brought the rows into order and when one row's spans or the @@ -1614,165 +1125,66 @@ class Mounter { std::vector order; std::size_t columns = 0; std::size_t threshold = 0; + // Each column's visible place, from the arrangement; empty before the first. + std::vector> placeOf; std::size_t reconciling = 0; bool sorted = false; bool anyAsked = false; + // Whether the table is windowed whatever its realized rows count: a table over a source above its threshold. + bool windowed = false; std::set lastRefused; }; // The resolve of a table's spans: what the widget is told, by the difference from what it last was, and the // refusals, reported when their set changes. - void resolveSpans(TableWidget& widget, SpanTable& table) { - if (table.reconciling != 0 || !table.anyAsked) { - return; - } - std::vector rows; - rows.reserve(table.order.size()); - for (SpanTable::Placed const& placed : table.order) { - auto const found = table.rows.find(placed.key); - SpanRow row{.name = - "row " + std::visit([](auto const& key) { return std::format("{}", key); }, placed.key)}; - if (found != table.rows.end()) { - row.heading = found->second.heading; - row.requested = found->second.requested; - } - rows.push_back(std::move(row)); - } - bool const virtualized = table.order.size() >= table.threshold; - ResolvedSpans resolved; - if (table.sorted) { - resolved.effective.resize(rows.size()); - } else if (virtualized) { - resolved.effective.resize(rows.size()); - if (std::ranges::any_of(rows, [](SpanRow const& row) { - return std::ranges::any_of(row.requested, [](RowSpan const& span) { return span.rows >= 2; }); - })) { - resolved.refused.emplace_back(site::kRowSpanVirtualized, "the table is virtualized"); - } - } else { - resolved = resolveRowSpans(rows, table.columns); - } - std::set refused; - for (auto const& [reason, text] : resolved.refused) { - refused.insert(std::string{reason} + " | " + text); - } - if (refused != table.lastRefused) { - std::set sites; - for (auto const& [reason, text] : resolved.refused) { - sites.insert(reason); - } - for (char const* const reason : sites) { - _rt->core()->report(reason); - } - table.lastRefused = std::move(refused); - } - for (std::size_t index = 0; index < table.order.size(); ++index) { - SpanTable::Placed const& placed = table.order.at(index); - auto const found = table.rows.find(placed.key); - if (placed.widget == nullptr || found == table.rows.end()) { - continue; - } - RowSpanEntry& entry = found->second; - if (entry.told != placed.widget) { - entry.told = placed.widget; - entry.sent.clear(); - } - if (resolved.effective.at(index) != entry.sent) { - entry.sent = resolved.effective.at(index); - widget.setRowSpans(*placed.widget, entry.sent); - } - } - } + // NOLINTNEXTLINE(readability-function-cognitive-complexity): resolves spans against the table's rows in one pass: what the widget is told depends on the difference from the previous resolve, and refusals report when their set changes + void resolveSpans(TableWidget& widget, SpanTable& table); + + // A caller's menu entry as a menu that is open holds it: what choosing it runs, and its submenu's entries. + struct OpenItem { + Action onSelect; + std::vector items; + }; + + // Reads @p items once, as a `Menu` shows them: a hidden entry is left out, and so is a separator it leaves at + // either end of its level or next to another. Each entry shown is appended to @p shown, and what it runs to @p + // kept at the same place. + // NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. + static void readMenuItems(std::vector const& items, std::vector& shown, + std::vector& kept); + + // The entry a path names among @p kept; null when the path leaves them. + [[nodiscard]] static OpenItem const* openItemAt(std::vector const& kept, + std::span path); + + // The menus a table has open, as last read: a header's, with the caller's entries after the built-in ones, and a + // cell's. A choice is routed by what the menu held when it opened. + struct OpenMenus { + std::optional headerColumn; + // Where the caller's entries start in the header's menu, past the built-in entries and their separator. + std::size_t headerOffset = 0; + std::size_t builtIn = 0; + std::vector header; + std::optional> cell; + std::vector cellItems; + }; + + // What a user configures a table with, whatever its rows come from: menus, moves, resizes, filters, groups and + // copy. A value left at its empty constant is not told, so a table that configures nothing is told nothing. + // @p focusCell focuses a cell whose menu opens; empty for a table whose focus the mount does not keep. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one seam per configuring callback. + void bindTableConfig(reactive::Scope& scope, Table const& spec, TableWidget& widget, + std::function focusCell = {}); + + // A selection of the view and the status line's entries. While `selectionView` is engaged the backend marks every + // row but its keys; when it disengages the selection is given again, since the one the backend showed before the + // view may equal the one it ends on, which would not be sent again. + void bindSelectionView(reactive::Scope& scope, Table const& spec, TableWidget& widget, bool& viewing); // Rows first, then the selection. The widget marks a selected key whenever its row arrives, so the order only // shapes the log: the first setSelection comes after the rows and already marks them. - Widget& mountKind(reactive::Scope& scope, Table const& spec, ContainerWidget* parent) { - TableWidget& widget = scope.adopt(_backend->createTable(parent)); - applyCommon(scope, widget, spec.common); - checkNoShare(spec.columns); - widget.setColumns(spec.columns); - widget.setShowHeader(spec.showHeader); - widget.setSelectionMode(spec.selectionMode); - if (spec.selectColumn) { - widget.setSelectColumn(true); - bind(scope, spec.selectAllLabel, [&widget](std::string const& label) { widget.setSelectAllLabel(label); }); - } - widget.setOnActivate(event(spec.onActivate)); - bool const sortable = std::ranges::any_of(spec.columns, &TableColumn::sortable); - reactive::Computed>* sortValue = nullptr; - if (sortable) { - sortValue = - bind(scope, spec.sort, [&widget](std::optional const& sort) { widget.setSort(sort); }); - widget.setOnSort(event(spec.onSort)); - } - auto& spans = scope.make(); - spans.columns = spec.columns.size(); - spans.threshold = spec.virtualize.threshold; - // The sort counts where it is wired: a table with no sortable column shows no sort. It is read inside the - // rows Effect, not in an Effect of its own, so that two Effects cannot resolve the spans in either order, - // one of them against the wrong rows. A sort bound to a server query can still clear before the rows reorder. - spans.sorted = sortable && sortValue == nullptr && spec.sort.constant().has_value(); - mountRows( - scope, spec.rows, widget, - [this, &widget, &spans](reactive::Scope& rowScope, Node const& node, Widget& rowWidget, Key const& key) { - widget.setRowKey(rowWidget, key); - // A row's tone binds in the row's scope, after its key and whether it is a heading. - Row const* const view = node ? std::get_if(&node->kind) : nullptr; - if (view != nullptr && view->heading) { - widget.setRowHeading(rowWidget); - } - if (view != nullptr && (view->heading || view->spans)) { - spans.rows[key].heading = view->heading; - if (view->spans) { - bind(rowScope, *view->spans, [this, &widget, &spans, key](std::vector const& asked) { - spans.rows[key].requested = asked; - spans.anyAsked = spans.anyAsked || !asked.empty(); - resolveSpans(widget, spans); - }); - } - } - if (view != nullptr && view->tone) { - bind(rowScope, *view->tone, [&widget, &rowWidget](std::optional const& tone) { - widget.setRowTone(rowWidget, tone); - }); - } - if (view != nullptr && view->label) { - bind(rowScope, *view->label, - [&widget, &rowWidget](std::string const& label) { widget.setRowLabel(rowWidget, label); }); - } - }, - &spec.virtualize, - RowsObserver{ - .track = - [&spans, sortValue] { - if (sortValue != nullptr) { - spans.sorted = sortValue->get().has_value(); - } - }, - .begin = [&spans] { ++spans.reconciling; }, - .end = - [this, &widget, &spans](std::vector const& rows) { - --spans.reconciling; - spans.order.clear(); - for (KeyedRow const& row : rows) { - spans.order.push_back( - {.key = row.key, - .widget = row.widgetState == RowWidgetState::Realized ? row.widget : nullptr}); - } - std::unordered_set present; - for (KeyedRow const& row : rows) { - present.insert(row.key); - } - std::erase_if(spans.rows, - [&present](auto const& entry) { return !present.contains(entry.first); }); - resolveSpans(widget, spans); - }}); - widget.setOnSelectionChange(inputEvent( - spec.onSelectionChange, controlled(scope, spec.selection, [&widget](std::vector const& keys) { - widget.setSelection(keys); - }))); - return widget; - } + // NOLINTNEXTLINE(readability-function-cognitive-complexity): mounts each table spec kind (rows, source, model) against one widget, in the order the rows then the selection must bind + Widget& mountKind(reactive::Scope& scope, Table const& spec, ContainerWidget* parent); // Runs a pass that changes @p rows inside the observer's begin and end. The end runs also when the pass throws, so // a failed row never leaves the table counting a pass that is over. @@ -1799,41 +1211,429 @@ class Mounter { // rows in @p window and its overscan are. void reconcileWindowed(std::size_t depth, ForEachSession& session, KeyedRows& rows, ContainerWidget& container, TableWidget& table, std::vector const& keys, RowHook const& onRow, - VisibleRange const& window, Virtualization const& setting, bool windowed) { - if (keys.size() < setting.threshold) { - reconcile(depth, session, rows.list, container, keys, onRow); - if (windowed) { - // Rows released while the table was windowed come back: below the threshold every row is realized. - applyWindow(depth, rows.list, container, {.first = 0, .count = rows.list.size()}, 0, onRow); - } - return; - } - std::pair const windowAndOverscan{window, setting.overscan}; - reconcile(depth, session, rows.list, container, keys, onRow, &windowAndOverscan); - // The kept rows have new view positions, and reconcile realizes only new keys: apply the window again so the - // realized rows are the ones now at the window's view positions. - applyWindow(depth, rows.list, container, window, setting.overscan, onRow); - // Only above threshold: a backend's own selection-filtering logic may need to know a key still exists even - // without a realized row for it right now (backend.hpp's setExistingKeys). Below threshold every key already - // has a realized row, so this would add nothing. - table.setExistingKeys(keys); - } + VisibleRange const& window, Virtualization const& setting, bool windowed); // Tells the backend which rows are realized once @p keyCount is at or above the threshold, and that the window is // over once the count has fallen back below it; @p windowed is whether the backend was last told the rows are // windowed, and is updated. static void publishRealizedWindow(TableWidget& table, KeyedRows const& rows, std::size_t keyCount, - Virtualization const& setting, bool& windowed) { - if (keyCount >= setting.threshold) { - auto const [first, count] = realizedExtent(rows.list); - table.setRealizedWindow(first, count, rows.list.size()); - windowed = true; - } else if (windowed) { - table.setRealizedWindow(0, rows.list.size(), rows.list.size()); - windowed = false; - } + Virtualization const& setting, bool& windowed); + + // A table over a `TableSource`: the rows in and near view, each built from the source's view index, and in each + // row the cells of the columns in or near view. + // NOLINTNEXTLINE(clang-analyzer-optin.performance.Padding): the fields are grouped and commented by role, and the realized rows are declared to go last first, as their comment says; a size-ordered layout would break both + struct MORPH_API SourceTable { + // Which pool a cell goes back to: the default cell's pool of one role, or a column's own pool. + using PoolKey = std::pair; + + // Where an accented cell's accent is told: the row widget and the column it is attached at (no row while it is + // pooled or being moved), and the accent last evaluated, sent again whenever it is attached. + struct Accent { + Widget* row = nullptr; + std::size_t column = 0; + CellAccent last; + }; + + // Where a marked cell's marks are told, as for an accent. + struct Marks { + Widget* row = nullptr; + std::size_t column = 0; + CellMarks last; + }; + + // One cell: its scope owns its view, its bindings and its widget; its signals are the record it shows and, + // for the default cell, the column it shows. + struct Cell { + std::unique_ptr scope; + reactive::Signal* row = nullptr; + reactive::Signal* column = nullptr; + // Engaged for a cell whose view is an `AccentedCell`; owned by `scope`. + Accent* accent = nullptr; + // Engaged for a cell whose view is a `MarkedCell`; owned by `scope`. + Marks* marks = nullptr; + Widget* widget = nullptr; + PoolKey pool; + }; + // A cell in a column of its row: `fresh` once bound to the row the slot now shows. + struct Placed { + Cell cell; + bool fresh = false; + }; + // A realized row: a keyed row, or a placeholder for a row not fetched yet. Members go in reverse: the pooled + // and placed cells, then the row's look, then the stack and the row's signal. + struct Realized { + std::unique_ptr scope; + std::unique_ptr look; + std::int64_t index = 0; + // The index the backend was last told (`setRowIndex`); -1 before. + std::int64_t toldIndex = -1; + std::optional key; + Widget* widget = nullptr; + reactive::Signal* row = nullptr; + bool heading = false; + // Whether the row is a summary row (`TableRowLook::summary`). + bool summary = false; + Widget* headingWidget = nullptr; + // The stack's children in their order, so a reorder knows where each is. + std::vector children; + std::map loads; + std::map cells; + std::map> pool; + // An open cell editor, a child of this row drawn over the cell at `editorColumn`: last, so it goes first. + std::unique_ptr editor; + Widget* editorWidget = nullptr; + std::size_t editorColumn = 0; + }; + + SourceTable() = default; + // The rows go last first, as a container's children do. + ~SourceTable(); + SourceTable(SourceTable const&) = delete; + SourceTable& operator=(SourceTable const&) = delete; + SourceTable(SourceTable&&) = delete; + SourceTable& operator=(SourceTable&&) = delete; + + TableSource source; + TableWidget* widget = nullptr; + std::vector columns; + Virtualization virtualize; + std::size_t depth = 0; + // The rows' spans, resolved over the realized rows; drawn only while every row is realized. + SpanTable* spans = nullptr; + // The header bands, and the runs the backend was last told of them. + std::vector bands; + std::optional> bandsTold; + // The rows the backend last reported in view; a count of 0 until it reports. + VisibleRange range; + // In view order; each widget is the container's child at its place. + std::vector realized; + + // The arrangement, the visible columns in layout order, and each column's place among them. + TableArrangement arrangement; + std::vector visible; + // Whether the backend was told the visible columns: once at mount, then on every change. + bool visibleTold = false; + std::vector> placeOf; + std::shared_ptr extents = std::make_shared(); + // What the backend measured of each column (an index into `columns`), the largest of each width reported; it + // outlives an arrangement, so a column laid out again starts from it. + std::vector measures; + // The places of the visible stretch columns whose width the user did not set, and whether the widths they get + // are owed a recomputation: the room, a measure or another column's width changed. + std::vector stretchPlaces; + bool stretchDirty = true; + // The backend's measure of the table, as of the last arrangement. + TableMeasure measure; + // The horizontal viewport, once the backend reported one. + bool horizontal = false; + int scrollX = 0; + int viewport = 0; + // The column window: indices into `columns`, the pinned ones first; what the backend was last told of it. + std::vector window; + std::size_t pinnedShown = 0; + bool windowDirty = true; + bool windowedColumns = false; + std::vector fetched; + std::optional, std::size_t>> counts; + + // Focus: a row key and a column, held here, and the view row it is at; a key not known yet while the row + // is not fetched. + bool focused = false; + std::optional focusKey; + std::int64_t focusIndex = 0; + // The focused row left the view: focus goes to the row now at its index. `focusWas` keeps the key it left, + // so a key move from it that arrives after the row left still takes focus to the row's new key. + bool focusLeft = false; + std::optional focusWas; + // The focused index came from the rows' answer to where the key is, which is of the view as it is now, while + // the rows held may not have taken in the change that put the key there yet: the index is trusted only once a + // realized row holds the key, and the backend is never told an index whose row holds another key. + bool focusUnconfirmed = false; + // The latest `KeyMoves` generation applied. + std::uint64_t keyMovesApplied = 0; + // A reset moved the focused or highlighted key where no realized row has it yet: each pass looks for it + // until a row has it, or the user moves focus or the highlight changes. Focus also asks the rows where its + // key is, an ask `focusLocate` stops, and their answer ends its search. + bool focusSearching = false; + bool highlightSearching = false; + ::core::async::StopSource focusLocate; + // The rows answered where the focused key is, and the backend is not told yet: it is told once the view's + // count is known and holds the index, which a server's rows learn only from the first page after a reset. + bool focusUntold = false; + // The view's row count at the end of the last pass: an index at or past it names no row a change can move. + std::size_t lastCount = 0; + std::size_t focusColumn = 0; + std::function)> onFocusCell; + // A grid's focus (`Table::gridFocus`): the user's moves go to `onGridFocus`, and focus is shown where the + // grid says. + bool grid = false; + std::function onGridFocus; + // The cell `Table::editing` names, and the editor's builder; the editor is open on a realized row of its key. + std::optional editWanted; + std::function editor; + // A table that selects cells (`Table::cellSelection`): the range by its corners, and the rectangle the backend + // was last told, so a pass that leaves it where it was tells nothing. + bool cells = false; + std::optional cellRange; + std::optional> cellRect; + bool cellRectTold = false; + // The highlighted row, followed by key. + std::optional highlightKey; + std::int64_t highlightIndex = 0; + + bool mounted = false; + bool continuing = false; + // Whether the table is being destroyed. + bool closing = false; + // Whether a window pass is running, and whether a call came in during it. + bool realizing = false; + bool realizeAgain = false; + // Expires with the table, so a change the rows deliver after it is gone does nothing. + std::shared_ptr alive = std::make_shared(true); + }; + + // A cell's load state: from the row's unloaded and failed levels and the level of the cell's column. + [[nodiscard]] static CellLoad cellLoadOf(SourceTable const& table, table::UnloadedLevels const& levels, + std::size_t column); + + [[nodiscard]] static SourceTable::PoolKey poolOf(SourceTable const& table, std::size_t column); + + // Whether the columns are laid out by the mount: told to the backend by `setColumnWindow`, and each cell placed + // by `setCellColumn`. + [[nodiscard]] static bool arranged(SourceTable const& table) { + return table.horizontal || table.arrangement != TableArrangement{}; + } + + // A content column's width: its widest cell and its header once either is measured, the backend's estimate before. + [[nodiscard]] static int contentWidthOf(ColumnMeasure const& known, TableMeasure const& measure); + + // Takes a new arrangement: the visible columns, their places, and their widths, the declared ones and the user's. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): takes a new arrangement: the visible columns, their places and their widths, declared and user's, each step reading the previous one's result + static void arrange(SourceTable& table, TableArrangement arrangement); + + // The ids every `visible` call names: the always-fetched ones, then each window column's id and what its cell + // reads. + [[nodiscard]] static std::vector fetchedOf(SourceTable const& table); + + // The rows `visible` is told: the reported range. Before any report, a window over a server's rows shows its + // first `overscan` rows, and one over a document's rows the empty view a keyed list starts from. + [[nodiscard]] static VisibleRange shownOf(SourceTable const& table); + + // The rows focus takes as in view: the reported range, or the first `overscan` rows before any report, whatever + // the rows, so a page moves by the rows a view would show and a row past them is scrolled to. + [[nodiscard]] static VisibleRange focusRangeOf(SourceTable const& table) { + return table.range.count > 0 ? table.range : VisibleRange{.first = 0, .count = table.virtualize.overscan}; } + static void tellVisible(SourceTable& table); + + // Brings the column window up to date with the scroll, the arrangement, the widths and the rows' count, and tells + // the backend and the rows what changed. Reads one width per column of the window, and none outside it. + static void refreshColumns(SourceTable& table, std::size_t rows); + + // The place of the first column fully in view, past the pinned ones: a width change left of it moves the scroll + // offset by as much, so the columns in view stay where they are. + [[nodiscard]] static std::size_t firstFullPlace(SourceTable const& table); + + // Gives the stretch columns the width the other columns leave, by the rules of `stretchWidths`: each column's + // natural width is the larger of its header and its widest cell measured so far, so a table over rows it has not + // realized fits the rows it has seen. A table whose viewport the backend has not reported keeps the estimate. + static void fitStretch(SourceTable& table); + + // The band runs over the visible columns, cut to the column window's places: a band exists for the columns in the + // window. The backend is told only when they change. + static void tellBands(SourceTable& table, std::vector const& places, std::size_t pinned); + + // Builds a cell for @p column of @p row, showing @p record. All or nothing. + [[nodiscard]] SourceTable::Cell makeCell(SourceTable& table, SourceTable::Realized& row, std::size_t column, + Value const& record); + + // Sets a cell's record, counting a set that changed it. + void setRecord(reactive::Signal& signal, Value const& record); + + // Gives a slot the row @p ref: its key, its record, its look. Its cells still show the row they showed, until + // each is rebound; the cells of a row-scoped column (`TableSource::rowScopedCells`) of another key are dropped, + // to be built for this one. + void assignRow(SourceTable& table, SourceTable::Realized& slot, std::int64_t index, TableRowRef const& ref); + + // Unmounts a row's open cell editor, and draws the cell again. + static void closeEditor(SourceTable& table, SourceTable::Realized& slot); + + // Brings the open editor to the cell `Table::editing` names: the one open on another cell is closed, and the + // wanted one is opened once a realized row holds its key, built once, drawn over the cell and focused. + void syncEditor(SourceTable& table); + + // A new slot at @p index: a stack, and the row if the rows hold it. All or nothing. + [[nodiscard]] SourceTable::Realized makeRow(SourceTable& table, std::int64_t index); + + // Parks a placed cell in its row's pool: it leaves the row's layout, keeping its widget and its record. + static void park(SourceTable& table, SourceTable::Realized& slot, std::size_t column); + + // One cell's work in a pass: binding a cell to another row or column, or building one. + struct CellWork { + std::size_t slot = 0; + std::size_t column = 0; + std::size_t distance = 0; + }; + + // Puts a cell at @p column of a slot: a stale placed cell is rebound, a pooled one taken and rebound, and only + // an empty pool builds one. + void realizeCell(SourceTable& table, SourceTable::Realized& slot, std::size_t column, Value const& record); + + // Tells the widget each placed cell's load state that changed. + static void tellLoads(SourceTable& table, SourceTable::Realized& slot); + + // Brings the realized rows to the window around the rows in view, and their cells to the column window. + // + // A row the rows still hold keeps its slot, wherever it moved; one at an index @p updated names has its record + // set again. A row that enters takes the slot of one that left, and only when none left is a slot built. Within a + // row, a cell whose column left the window goes to the row's pool, and a column that enters takes a pooled cell + // of its pool. Binding a cell to another row or column, and building one, are counted against + // `realizePerFrame`, nearest the viewport's centre first; the rest wait, drawn blank, for the next turn. + // + // The backend measures a table while its cells mount, which asks for the window again from inside the pass that + // is mounting them, and a second pass would move the rows and slots the first is still walking. A call that comes + // in during a pass is answered when it ends, over every row with its record set again (an equality-gated set), + // since the rows the call names are not known once it returns. + void realizeWindow(SourceTable& table, std::function const& updated); + + // One pass of `realizeWindow`. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): rows, cells, the budget, focus and the reports. + void realizeWindowPass(SourceTable& table, std::function const& updated); + + // The cells of the realized rows: columns that left the window are pooled, and the cells the window lacks are + // bound or built within the frame's budget, nearest the centre first. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): pooling, the budget, and the order in each row. + void realizeCells(SourceTable& table, VisibleRange const& shown); + + // Whether a column's cells each show one row only. + [[nodiscard]] static bool rowScoped(SourceTable const& table, std::size_t column) { + return column < table.source.rowScopedCells.size() && table.source.rowScopedCells.at(column); + } + + // Destroys a row's placed and pooled cells of the row-scoped columns, and forgets their widgets among its + // children. A default cell is never row-scoped: it reads its row's record alone. + static void dropRowScoped(SourceTable const& table, SourceTable::Realized& slot); + + // Destroys a row's pooled cells, and forgets their widgets among its children. + static void dropPools(SourceTable::Realized& slot); + + // A row's children in the window's order, then its pooled cells, for a backend that places cells by their order + // rather than by `setCellColumn`. + static void orderCells(SourceTable const& table, SourceTable::Realized& slot); + + // Posts the next turn's realization, once. + void continueLater(SourceTable& table); + + // After a pass: the counts, the focused cell and the highlighted row. + // NOLINTNEXTLINE(readability-function-cognitive-complexity, readability-convert-member-functions-to-static): the pass's reports (counts, focused cell, highlighted row) each read the same table state in turn + void afterPass(SourceTable& table, TableTotal const& total); + + // Asks the rows where the focused key is now, stopping an earlier ask. + void locateFocus(SourceTable& table); + + // The rows' answer to where the focused key is. A key in the view takes focus at its index, its row kept + // realized wherever it is; a key the view lacks has left it, and focus goes to the row now at its index, or the + // last, as for a removed row. An answer the rows could not give leaves focus looking among the realized rows. + // The backend is told after the pass, once the view's count is known (`focusUntold`): the last row of a count + // not known yet is no row. + void focusLocated(SourceTable& table, RowLocation const& found); + + // Tells the backend the focused cell the rows located. A row they do not hold, outside the rows in view, is + // scrolled to, so the window fetches it, as for a move onto a row not fetched; a held row is left where it is. + static void tellLocatedFocus(SourceTable& table); + + static void reportFocus(SourceTable const& table); + + // Where a view row is after a change: moved with the rows around it, or nothing when the change removed it. A + // reset keeps the index. + [[nodiscard]] static std::optional followIndex(table::ViewChange const& change, std::int64_t index); + + // Moves focus as a key asks: by rows or columns, to an end of the row, or to the first or last row of the view. + // A row not fetched takes focus as a placeholder, and the view scrolls to it. + void moveFocus(SourceTable& table, FocusMove move); + + // The view position of a key, scanning the view: a table selects cells only while its rows are all on the client. + [[nodiscard]] static std::optional viewRowOf(SourceTable const& table, Key const& key); + + // Shows a cell range at its corners' view rows and visible places now: a sort or a column move redraws the + // rectangle the same corners span. A corner whose row is not in the view, or whose column is hidden, shows none. + static void showCells(SourceTable& table); + + // A rectangle the backend reports, by view rows and visible places, as a range by keys and column ids; a corner + // outside the view or the visible columns reports nothing. + [[nodiscard]] static std::optional cellsAt( + SourceTable const& table, std::size_t anchorRow, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`anchorPlace`, `focusRow`): the selection's anchor then its focus, passed in that order by the one caller + std::size_t anchorPlace, std::size_t focusRow, std::size_t focusPlace); + + // A grid's focus moves where the grid says: a gesture is handed to it as a cell, a row not fetched yet by its view + // position alone. + static void handFocus(SourceTable const& table, std::int64_t index, std::size_t column); + + // Shows the focus a grid holds: its key's row where a realized row holds it, else the view position it gives, and + // its column by id. + void gridFocusFrom(SourceTable& table, std::optional const& focus); + + // Puts focus on a cell by view row and column: the row is kept realized, scrolled to when it is outside the rows + // in view, and the backend shows it. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`index`, `column`): row index then column, the order every focus seam in this file uses + void placeFocus(SourceTable& table, std::int64_t index, std::size_t column); + + // Takes focus from `Table::focus`: the cell's row by key among the realized rows, and its column by id. + void focusFrom(SourceTable& table, std::optional const& cell); + + // Focuses a realized row's cell, as a cell menu opening on it does, and reports it as a key's move is reported. + void focusAt(SourceTable& table, Key const& key, std::size_t column); + + // Moves focus and the highlight from a row's old key to its new one, for each new generation of moves. Focus on + // the old key, or left by it when its row went, goes to the new key: at once when a realized row holds it, else + // the rows are asked where it is, as after a reset, and the change that removes the old row moves it nowhere + // meanwhile; an answer that the view lacks the new key hands focus to the row at its index. + void applyKeyMoves(SourceTable& table, KeyMoves const& moves); + + // Takes a highlight: the rows fetch around it, the view scrolls to it and marks it, and its key is followed. + static void highlightFrom(SourceTable& table, std::optional const& highlight); + + // Where a key is among the realized rows' places in the view the rows now hold, or nothing. + [[nodiscard]] static std::optional placeOfKey(SourceTable const& table, Key const& key, + std::int64_t also); + + // Follows the focused and the highlighted rows through a change of the rows. A reset (a new sort, filter or + // description) gives no places, and the rows may come back later (a server's pages are dropped first), so a key + // no realized row has is looked for after each pass until one has it; meanwhile the highlight shows no mark and + // focus stays on its key. Focus also asks the rows where its key is, since a new order can move it far from the + // rows realized; only their answer that the view lacks it moves focus to another row. An index at or past the + // row count before the change names no row, so nothing moves it; after a reset no row is counted until the next + // pass, so a first page that arrives before it moves nothing either. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): follows the focused and the highlighted rows through each operation of a change, which shifts both by the operation kind + void follow(SourceTable& table, table::ViewChange const& change); + + // Whether a change names the view index @p index as updated: a reset names every row, and a row inserted, + // changed or moved to the index is named. + [[nodiscard]] static bool namesUpdated(table::ViewChange const& change, std::int64_t index); + + // What an editable table adds: its focus held by a grid, a click on a cell, typed text, its own keys, and focus + // leaving it. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): binds what an editable table adds (focus, click, typed text, keys, focus loss), each handler capturing the same table state + void bindGrid(reactive::Scope& scope, Table const& spec, TableWidget& widget, SourceTable& table); + + // A table over a `TableSource`. Rows are windowed, except a table over a document's rows below its threshold, + // which realizes every row: the mount realizes the rows the backend reports in view and `overscan` rows either + // side; before any report, the first `overscan` rows of a server's rows, and none of a document's (`shownOf`). + // Columns are windowed once the backend reports its horizontal viewport and `windowingOf` says so; until then + // every visible column is in the window. The mount tells the rows which rows and columns are in view, and applies + // each `ViewChange` to the realized rows by key. Rows first, then the selection, as for a table over `rows`. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one handler per table seam. + Widget& mountSourceTable(reactive::Scope& scope, Table const& spec, ContainerWidget* parent); + + // What the backend measured of @p column: a content column is as wide as its widest cell and its header, which + // only grow once measured, and a change left of the first column fully in view moves the scroll offset by as much, + // so the columns in view stay where they are. A + // stretch column's measure feeds the fit of every stretch column to the table, which may narrow as well as widen + // them. A fixed column keeps its width. + void measured(SourceTable& table, std::size_t column, ColumnMeasure const& reported); + // The model, then the session, then the rows, then the Effect(s): destroyed in reverse, so an Effect stops // first, the rows (whose slots point into the session's snapshot) go next, and the model outlives its session. // @p virtualize is null for a ForEach (no backend seam exists yet to dewindow a bare keyed stack); when @@ -1842,90 +1642,10 @@ class Mounter { // virtualization is silently not wired, same as if it were null. void mountRows(reactive::Scope& scope, std::shared_ptr const& model, ContainerWidget& container, RowHook onRow, Virtualization const* virtualize, - RowsObserver observer = {}) { - if (!model) { - return; - } - scope.make>(model); - ForEachSession& session = scope.adopt(model->open(*_rt)); - auto& rows = scope.make(); - TableWidget* const table = virtualize != nullptr ? dynamic_cast(&container) : nullptr; - if (table == nullptr) { - scope.effect([this, &session, &rows, &container, depth = scope.depth() + 1, onRow, overlay = _overlay] { - std::vector const keys = session.pull(); // tracked: the rows are this Effect's only source - // Untracked: what a row view reads while it is built, or what a kept row's update touches, must - // not become a dependency of the whole list. - underOverlay(overlay, [&] { - _rt->untracked([&] { reconcile(depth, session, rows.list, container, keys, onRow); }); - }); - }); - return; - } - // The windowing state: written by the backend's own scroll callback (via widgetEvent, so this is never - // written from inside a flush this Effect caused), read by both Effects below -- the rows Effect, so a - // brand-new row's very first mount already respects the window instead of needing a later windowing pass - // to correct it; the windowing Effect, so a scroll alone realizes/releases without re-running reconcile. - auto& range = scope.make>(*_rt, VisibleRange{}); - table->setOnVisibleRangeChanged([this, &range](std::size_t first, std::size_t count) { - runCallback(*_rt, [&] { range.set({.first = first, .count = count}); }); - }); - // The observer sees every pass that changes the rows, the windowing one included. - auto const observerTrack = observer.track; - auto const around = observedPass(std::move(observer), rows); - // Whether the backend was last told the rows are windowed: a count that falls back below the threshold then - // owes it the end of the window. - auto& windowed = scope.make(false); - scope.effect([this, &session, &rows, &container, &range, &windowed, setting = *virtualize, - depth = scope.depth() + 1, onRow, table, overlay = _overlay, around, track = observerTrack] { - // tracked: the rows are one source, and the sort that `track` reads is the other - std::vector const keys = session.pull(); - if (track) { - track(); - } - VisibleRange const window = range.peek(); // untracked: a scroll alone must not re-run this Effect - around([&] { - underOverlay(overlay, [&] { - _rt->untracked([&] { - reconcileWindowed(depth, session, rows, container, *table, keys, onRow, window, setting, - windowed); - }); - }); - }); - publishRealizedWindow(*table, rows, keys.size(), setting, windowed); - }); - scope.effect([this, &rows, &container, &range, setting = *virtualize, depth = scope.depth() + 1, onRow, table, - overlay = _overlay, around] { - VisibleRange const window = range.get(); // tracked: this Effect's own trigger - // Below threshold, every row is already realized (reconcile's own unconditional path, §4.4), and - // setRealizedWindow is not called at all -- not even once with "everything realized" -- so a table - // that never crosses its threshold is indistinguishable, on the backend, from one with no - // virtualization machinery at all. - if (rows.list.size() < setting.threshold) { - return; - } - around([&] { - underOverlay(overlay, - [&] { applyWindow(depth, rows.list, container, window, setting.overscan, onRow); }); - }); - auto const [first, count] = realizedExtent(rows.list); - table->setRealizedWindow(first, count, rows.list.size()); - }); - } + RowsObserver observer = {}); // The snapshot index of each key's first occurrence, in order; every later duplicate is reported. - [[nodiscard]] std::vector firstOccurrences(std::vector const& keys) { - std::unordered_set seen; - std::vector order; - order.reserve(keys.size()); - for (std::size_t index = 0; index < keys.size(); ++index) { - if (seen.insert(keys.at(index)).second) { - order.push_back(index); - } else { - _rt->core()->report(site::kDuplicateKey); - } - } - return order; - } + [[nodiscard]] std::vector firstOccurrences(std::vector const& keys); // All or nothing: the row's state and its widget are each built in a scope of their own, one level deeper than // the ForEach's, which the caller takes only once the mount completed. A new row's widget is realized in the @@ -1933,19 +1653,7 @@ class Mounter { // realized later, on a row whose state already exists, goes through `realizeRowWidget` instead, which is not // its own `mountPass` -- see that function's own comment for why. [[nodiscard]] KeyedRow mountRow(std::size_t depth, ForEachSession& session, ContainerWidget& container, - Key const& key, std::size_t index, RowHook const& onRow) { - return mountPass([&] { - KeyedRow row{.key = key, .stateScope = std::make_unique(*_rt, depth)}; - row.slot = &row.stateScope->adopt(session.makeRow(index)); - row.widgetScope = std::make_unique(*_rt, depth); - row.widget = mount(*row.widgetScope, row.slot->view(), &container); - row.widgetState = row.widget != nullptr ? RowWidgetState::Realized : RowWidgetState::NullView; - if (row.widget != nullptr && onRow) { - onRow(*row.widgetScope, row.slot->view(), *row.widget, key); - } - return row; - }); - } + Key const& key, std::size_t index, RowHook const& onRow); // Realizes a widget for a row whose state (`stateScope`/`slot`) already exists -- a row re-entering the // visible range after being dewindowed. Deliberately not a `mountPass` of its own: `mountPass` gives the first @@ -1953,81 +1661,24 @@ class Mounter { // time (`mountRow`, inside the ForEach's own outer pass) but wrong here -- a row that already existed and // simply scrolled back into view must not steal focus back from wherever the user's focus already is. `mount` // itself carries no such behavior; only `mountPass` does, so simply not using it is what suppresses it. - void realizeRowWidget(std::size_t depth, KeyedRow& row, ContainerWidget& container, RowHook const& onRow) { - row.widgetScope = std::make_unique(*_rt, depth); - row.widget = mount(*row.widgetScope, row.slot->view(), &container); - row.widgetState = row.widget != nullptr ? RowWidgetState::Realized : RowWidgetState::NullView; - if (row.widget != nullptr && onRow) { - onRow(*row.widgetScope, row.slot->view(), *row.widget, row.key); - } - } + void realizeRowWidget(std::size_t depth, KeyedRow& row, ContainerWidget& container, RowHook const& onRow); // Releases a row's widget, keeping its state: the container sees an ordinary removal (`releasing` fires exactly // as it does for a real removal), but `stateScope`/`slot` are untouched, so the row's signal keeps tracking the // snapshot and is ready for `realizeRowWidget` to mount a fresh widget against it later. - static void dewindowRowWidget(KeyedRow& row) { - row.widgetScope.reset(); - row.widget = nullptr; - row.widgetState = RowWidgetState::Dewindowed; - } + static void dewindowRowWidget(KeyedRow& row); // Builds only a new key's state -- no widget, no mount, no onRow call -- for a row `reconcile` decides is // outside the current window on its very first appearance (a virtualized table above its threshold). The row // starts `Dewindowed`, exactly as if it had been realized once and then released, so `realizeRowWidget` can // bring it in later with no special case for "never had a widget" versus "had one and lost it." [[nodiscard]] KeyedRow mountRowState(std::size_t depth, ForEachSession& session, Key const& key, - std::size_t index) { - KeyedRow row{.key = key, .stateScope = std::make_unique(*_rt, depth)}; - row.slot = &row.stateScope->adopt(session.makeRow(index)); - row.widgetState = RowWidgetState::Dewindowed; - return row; - } + std::size_t index); // Moves the widgets into the snapshot's order, and `rows` with them. A move that throws is recorded in `failure` // when it is the first failure, and leaves `rows` mirroring the container as it stands. - static void reorder(std::vector& rows, ContainerWidget& container, std::vector const& keys, - std::vector const& order, std::exception_ptr& failure) { - std::unordered_map position; // key -> index in `rows` - std::unordered_map rowOf; - std::vector present; - for (std::size_t i = 0; i < rows.size(); ++i) { - KeyedRow const& row = rows.at(i); - position.emplace(row.key, i); - if (row.widget != nullptr) { - rowOf.emplace(row.widget, i); - present.push_back(row.widget); - } - } - std::vector target; - target.reserve(present.size()); - for (std::size_t const index : order) { - if (auto const found = position.find(keys.at(index)); found != position.end()) { - if (KeyedRow const& row = rows.at(found->second); row.widget != nullptr) { - target.push_back(row.widget); - } - } - } - std::vector ordered; - ordered.reserve(rows.size()); - try { - reorderChildren(container, present, target); - } catch (...) { - if (!failure) { - failure = std::current_exception(); - } - } - // `present` is the container's order now: the snapshot's, unless a move threw. Rows without a widget have - // no place in the container and go last. - for (Widget const* const widget : present) { - ordered.push_back(std::move(rows.at(rowOf.at(widget)))); - } - for (KeyedRow& row : rows) { - if (row.widget == nullptr) { - ordered.push_back(std::move(row)); - } - } - rows = std::move(ordered); - } + void reorder(std::vector& rows, ContainerWidget& container, std::vector const& keys, + std::vector const& order, std::exception_ptr& failure); // Brings `rows` to the snapshot `keys`. `rows` mirrors the container's order on entry and on exit, also when // something throws, so a failure costs this run's remaining work and never the bookkeeping of the next one. @@ -2040,67 +1691,7 @@ class Mounter { // for the windowing Effect to realize later if it ever enters the visible range. void reconcile(std::size_t depth, ForEachSession& session, std::vector& rows, ContainerWidget& container, std::vector const& keys, RowHook const& onRow, - std::pair const* windowAndOverscan = nullptr) { - std::vector const order = firstOccurrences(keys); - std::unordered_map wanted; // key -> snapshot index - std::unordered_map viewPositionOf; // key -> position in view order (order's own index) - for (std::size_t viewPos = 0; viewPos < order.size(); ++viewPos) { - wanted.emplace(keys.at(order.at(viewPos)), order.at(viewPos)); - viewPositionOf.emplace(keys.at(order.at(viewPos)), viewPos); - } - - // Unmount the gone keys, last first as KeyedRows does, then update the kept ones in place, which keeps - // their widgets. A gone key's widget goes first (the Effect stops first within each row, mirroring the - // order mountRow itself builds the two scopes in: state first, then widget), then its state. - for (KeyedRow& row : std::views::reverse(rows)) { - if (!wanted.contains(row.key)) { - row.widgetScope.reset(); - row.stateScope.reset(); - } - } - std::erase_if(rows, [](KeyedRow const& row) { return row.stateScope == nullptr; }); - std::unordered_set kept; - for (KeyedRow& row : rows) { - kept.insert(row.key); - row.slot->assign(wanted.at(row.key)); - row.viewPosition = viewPositionOf.at(row.key); - } - - std::size_t const bootstrapFirst = 0; - std::size_t const bootstrapCount = windowAndOverscan != nullptr ? windowAndOverscan->second : 0; - VisibleRange const window = windowAndOverscan != nullptr && windowAndOverscan->first.count > 0 - ? windowAndOverscan->first - : VisibleRange{.first = bootstrapFirst, .count = bootstrapCount}; - - // Mount the new keys; each realized widget is appended to the container, and every new row (realized or - // state-only) to `rows`. `viewPos` is the row's position in view order -- order's own index -- which is - // what the window means positions in, not `index` (a position in the raw, possibly-reordered `keys`). - std::exception_ptr failure; - rows.reserve(order.size()); - for (std::size_t viewPos = 0; viewPos < order.size(); ++viewPos) { - std::size_t const index = order.at(viewPos); - if (kept.contains(keys.at(index))) { - continue; - } - bool const inWindow = - windowAndOverscan == nullptr || (viewPos >= window.first && viewPos < window.first + window.count); - try { - KeyedRow row = inWindow ? mountRow(depth, session, container, keys.at(index), index, onRow) - : mountRowState(depth, session, keys.at(index), index); - row.viewPosition = viewPos; - rows.push_back(std::move(row)); - } catch (...) { - if (!failure) { - failure = std::current_exception(); - } - } - } - - reorder(rows, container, keys, order, failure); - if (failure) { - std::rethrow_exception(failure); - } - } + std::pair const* windowAndOverscan = nullptr); // Realizes a widget for every row within `window` (± `overscan`) that does not already have one, and releases // every realized widget outside it. A row's position in view order is its own `viewPosition`, set by the most @@ -2110,236 +1701,44 @@ class Mounter { // own Signal, never from reconcile, so a scroll alone costs O(rows) to scan, not the full // reconciliation pass. void applyWindow(std::size_t depth, std::vector& rows, ContainerWidget& container, - VisibleRange const& window, std::size_t overscan, RowHook const& onRow) { - std::size_t const lo = window.first > overscan ? window.first - overscan : 0; - std::size_t const hi = - window.first + window.count + overscan; // exclusive; saturates harmlessly past rows.size() - std::exception_ptr failure; - for (KeyedRow& row : rows) { - bool const shouldBeRealized = row.viewPosition >= lo && row.viewPosition < hi; - if (shouldBeRealized && row.widgetState != RowWidgetState::Realized && - row.widgetState != RowWidgetState::NullView) { - try { - realizeRowWidget(depth, row, container, onRow); - } catch (...) { - if (!failure) { - failure = std::current_exception(); - } - } - } else if (!shouldBeRealized && row.widgetState == RowWidgetState::Realized) { - dewindowRowWidget(row); - } - } - // Realized widgets may now be a different subset of `rows` than before; bring the container back to the - // rows' own view order (`viewPosition`), restricted to what is realized -- `reorder` needs `order` as - // positions into `keys` in the target (view) order, not `rows`' own current array order, which groups - // realized ahead of dewindowed and so is not view order once any row is dewindowed. - std::vector const keys = [&] { - std::vector out; - out.reserve(rows.size()); - for (KeyedRow const& row : rows) { - out.push_back(row.key); - } - return out; - }(); - std::vector order(rows.size()); - std::iota(order.begin(), order.end(), std::size_t{0}); - std::ranges::sort(order, {}, [&rows](std::size_t index) { return rows.at(index).viewPosition; }); - reorder(rows, container, keys, order, failure); - if (failure) { - std::rethrow_exception(failure); - } - } + VisibleRange const& window, std::size_t overscan, RowHook const& onRow); // The realized subset's extent in view order: the first realized row's view position and how many rows from // there are realized. Used only to tell the backend what to size a scrollbar against // (`TableWidget::setRealizedWindow`); a gap of dewindowed rows between two realized ones (the overscan margin // straddling a scroll position mid-transition) is not expected in steady state, so this reports the outermost // realized view positions, not a strict contiguous run. - [[nodiscard]] static std::pair realizedExtent(std::vector const& rows) { - std::optional first; - std::size_t last = 0; - for (KeyedRow const& row : rows) { - if (row.widgetState == RowWidgetState::Realized) { - first = first ? std::min(*first, row.viewPosition) : row.viewPosition; - last = std::max(last, row.viewPosition); - } - } - return first ? std::pair{*first, last - *first + 1} : std::pair{std::size_t{0}, std::size_t{0}}; - } + [[nodiscard]] static std::pair realizedExtent(std::vector const& rows); - Widget& mountKind(reactive::Scope& scope, Busy const& spec, ContainerWidget* parent) { - BusyWidget& widget = scope.adopt(_backend->createBusy(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.active, [&widget](bool active) { widget.setActive(active); }); - bind(scope, spec.label, [&widget](std::string const& label) { widget.setLabel(label); }); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Busy const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Banner const& spec, ContainerWidget* parent) { - BannerWidget& widget = scope.adopt(_backend->createBanner(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.tone, [&widget](Tone tone) { widget.setTone(tone); }); - if (hasSpans(spec.spans)) { - bind(scope, spec.spans, [&widget](std::vector const& spans) { widget.setSpans(spans); }); - } else { - bind(scope, spec.text, [&widget](std::string const& text) { widget.setText(text); }); - } - bind(scope, spec.action.label, [&widget](std::string const& label) { widget.setActionLabel(label); }); - widget.setOnAction(event(spec.action.onClick)); - widget.setDismissible(spec.dismissible); - widget.setOnDismiss(event(spec.onDismiss)); - if (spec.actionStyle != BannerActionStyle::Ghost || spec.actionStretch) { - widget.setActionStyle(spec.actionStyle, spec.actionStretch); - } - return widget; - } + Widget& mountKind(reactive::Scope& scope, Banner const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Badge const& spec, ContainerWidget* parent) { - BadgeWidget& widget = scope.adopt(_backend->createBadge(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.tone, [&widget](Tone tone) { widget.setTone(tone); }); - bind(scope, spec.text, [&widget](std::string const& text) { widget.setText(text); }); - widget.setIcon(spec.icon); - if (spec.style != BadgeStyle::Filled) { - widget.setStyle(spec.style); - } - if (spec.shape != ControlShape::Default) { - widget.setShape(spec.shape); - } - if (spec.mono) { - widget.setMono(true); - } - if (spec.onRemove) { - // An empty label names the control after the badge's text, which may be bound as well. - auto const labelOf = [removeLabel = spec.removeLabel, text = spec.text] { - std::string const label = removeLabel.evaluate(); - return label.empty() ? "Remove " + text.evaluate() : label; - }; - Prop const label = spec.removeLabel.isBound() || spec.text.isBound() - ? Prop(labelOf) - : Prop(labelOf()); - bind(scope, label, [&widget, onRemove = event(spec.onRemove)](std::string const& shown) { - widget.setOnRemove(onRemove, shown); - }); - } - return widget; - } + Widget& mountKind(reactive::Scope& scope, Badge const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Progress const& spec, ContainerWidget* parent) { - ProgressWidget& widget = scope.adopt(_backend->createProgress(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.value, [&widget](std::optional value) { widget.setValue(value); }); - bind(scope, spec.label, [&widget](std::string const& label) { widget.setLabel(label); }); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Progress const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Steps const& spec, ContainerWidget* parent) { - StepsWidget& widget = scope.adopt(_backend->createSteps(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.items, [&widget](std::vector const& steps) { widget.setSteps(steps); }); - bind(scope, spec.current, [&widget](std::optional index) { widget.setCurrent(index); }); - if (spec.labelled.isBound() || !spec.labelled.constant()) { - bind(scope, spec.labelled, [&widget](bool labelled) { widget.setLabelled(labelled); }); - } - return widget; - } + Widget& mountKind(reactive::Scope& scope, Steps const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Chart const& spec, ContainerWidget* parent) { - ChartWidget& widget = scope.adopt(_backend->createChart(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.data, [&widget](ChartData const& data) { widget.setData(data); }); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Chart const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, KeyValue const& spec, ContainerWidget* parent) { - KeyValueWidget& widget = scope.adopt(_backend->createKeyValue(parent)); - applyCommon(scope, widget, spec.common); - if (spec.captions != CaptionPlacement::Beside) { - widget.setCaptionPlacement(spec.captions); - } - if (spec.captionWidth) { - if (*spec.captionWidth < 1) { - throw std::invalid_argument{"morph::ui::mount: `captionWidth` is at least 1 unit"}; - } - if (spec.captions == CaptionPlacement::Above) { - throw std::invalid_argument{"morph::ui::mount: `captionWidth` needs the captions beside their values"}; - } - widget.setCaptionWidth(*spec.captionWidth); - } - bind(scope, spec.items, [&widget](std::vector const& items) { widget.setItems(items); }); - return widget; - } + Widget& mountKind(reactive::Scope& scope, KeyValue const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, EmptyState const& spec, ContainerWidget* parent) { - EmptyStateWidget& widget = scope.adopt(_backend->createEmptyState(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.title, [&widget](std::string const& title) { widget.setTitle(title); }); - bind(scope, spec.text, [&widget](std::string const& text) { widget.setText(text); }); - widget.setIcon(spec.icon); - bind(scope, spec.action.label, [&widget](std::string const& label) { widget.setActionLabel(label); }); - widget.setOnAction(event(spec.action.onClick)); - return widget; - } + Widget& mountKind(reactive::Scope& scope, EmptyState const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Splitter const& spec, ContainerWidget* parent) { - SplitterWidget& widget = scope.adopt(_backend->createSplitter(parent, spec.orientation)); - if (spec.orientation == Axis::Horizontal) { - scope.make(_shareParents, &widget); - } - applyCommon(scope, widget, spec.common); - mountChildren(scope, spec.children, widget); - widget.setOnResize(inputEvent( - spec.onResize, - controlled(scope, spec.sizes, [&widget](std::vector const& sizes) { widget.setSizes(sizes); }))); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Splitter const& spec, ContainerWidget* parent); // The header is mounted first, so it is the first child; the content follows it. - Widget& mountKind(reactive::Scope& scope, Collapsible const& spec, ContainerWidget* parent) { - CollapsibleWidget& widget = scope.adopt(_backend->createCollapsible(parent)); - applyCommon(scope, widget, spec.common); - bind(scope, spec.title, [&widget](std::string const& title) { widget.setTitle(title); }); - if (Widget* const header = mount(scope, spec.header, &widget); header != nullptr) { - widget.setHeader(*header); - } - static_cast(mount(scope, spec.child, &widget)); - widget.setOnToggle( - inputEvent(spec.onToggle, controlled(scope, spec.open, [&widget](bool open) { widget.setOpen(open); }))); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Collapsible const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, DropZone const& spec, ContainerWidget* parent) { - DropZoneWidget& widget = scope.adopt(_backend->createDropZone(parent)); - applyCommon(scope, widget, spec.common); - widget.setAccept(spec.accept); - widget.setMultiple(spec.multiple); - widget.setOnDrop(event(spec.onDrop)); - static_cast(mount(scope, spec.child, &widget)); - return widget; - } + Widget& mountKind(reactive::Scope& scope, DropZone const& spec, ContainerWidget* parent); // The refusal text of a page node, naming its test id the way every layout refusal does. - [[nodiscard]] static std::logic_error pageRefusal(Common const& common, std::string const& what) { - return std::logic_error{"morph::ui::mount: " + what + - (common.testId.empty() ? std::string{} : " (node `" + common.testId + "`)")}; - } + [[nodiscard]] static std::logic_error pageRefusal(Common const& common, std::string const& what); // A page sizes itself: it takes `alignSelf` (not `Stretch`) and no other layout hint. A region is sized by its // geometry and takes none. - static void checkPageLayout(Common const& common, bool isPage) { - LayoutHints hints = common.layout; - if (isPage) { - if (hints.alignSelf && *hints.alignSelf == Align::Stretch) { - throw pageRefusal(common, "a page is never stretched; `alignSelf` places the sheet"); - } - hints.alignSelf.reset(); - } - if (hints != LayoutHints{}) { - throw pageRefusal(common, isPage ? "a page is sized by its sheet; its layout hints are refused" - : "a page region is sized by its geometry; its layout hints are refused"); - } - } + static void checkPageLayout(Common const& common, bool isPage); // The geometry of the page whose regions are being mounted, restored when they are done. class PageGuard { @@ -2356,163 +1755,36 @@ class Mounter { PageGeometry const* _saved; }; - Widget& mountKind(reactive::Scope& scope, Page const& spec, ContainerWidget* parent) { - checkPageLayout(spec.common, true); - if (std::optional const problem = spec.geometry.problem()) { - throw pageRefusal(spec.common, *problem); - } - for (Node const& child : spec.children) { - if (child && !std::holds_alternative(child->kind)) { - throw pageRefusal(spec.common, "a page holds page regions and nothing else"); - } - } - PageWidget& widget = scope.adopt(_backend->createPage(parent, spec.geometry)); - applyCommon(scope, widget, spec.common); - if (spec.common.a11y.role.empty()) { - widget.setAccessibleRole("document"); - } - if (!spec.common.surface.isBound() && spec.common.surface.constant().empty()) { - widget.setSurface("paper"); - } - PageGuard const guard{*this, &spec.geometry}; - mountChildren(scope, spec.children, widget); - return widget; + Widget& mountKind(reactive::Scope& scope, Page const& spec, ContainerWidget* parent); + + // An accented cell anywhere but a source table's cell: its content, with the accent not read. + Widget& mountKind(reactive::Scope& scope, AccentedCell const& spec, ContainerWidget* parent) { + return *mount(scope, spec.content, parent); } - Widget& mountKind(reactive::Scope& scope, PageRegion const& spec, ContainerWidget* parent) { - auto* const page = dynamic_cast(parent); - if (page == nullptr || _page == nullptr) { - throw pageRefusal(spec.common, "a page region belongs in a page"); - } - checkPageLayout(spec.common, false); - if (std::optional const problem = spec.geometry.problem(*_page)) { - throw pageRefusal(spec.common, *problem); - } - PageRegionWidget& widget = scope.adopt(_backend->createPageRegion(page, spec.geometry)); - applyCommon(scope, widget, spec.common); - mountChildren(scope, spec.children, widget); - return widget; + // A marked cell anywhere but a source table's cell: its content, with the marks not read. + Widget& mountKind(reactive::Scope& scope, MarkedCell const& spec, ContainerWidget* parent) { + return *mount(scope, spec.content, parent); } + Widget& mountKind(reactive::Scope& scope, PageRegion const& spec, ContainerWidget* parent); + // One prop of a loaded component, bound to the setter its kind crosses by. - void bindCustomProp(reactive::Scope& scope, CustomWidget& widget, CustomProp const& prop) { - std::string const& name = prop.name; - if (auto const* const text = std::get_if>(&prop.value)) { - bind(scope, *text, [&widget, name](std::string const& value) { widget.setTextProp(name, value); }); - } else if (auto const* const flag = std::get_if>(&prop.value)) { - bind(scope, *flag, [&widget, name](bool value) { widget.setBoolProp(name, value); }); - } else if (auto const* const number = std::get_if>(&prop.value)) { - bind(scope, *number, [&widget, name](double value) { widget.setNumberProp(name, value); }); - } - } + void bindCustomProp(reactive::Scope& scope, CustomWidget& widget, CustomProp const& prop); // The component the backend loads in the custom node's place, or the fallback when it loads none. // An ActionBar holds the actions of what holds it: the footer of the overlay whose content it is in, else the // place it is written. It is a horizontal stack either way, marked as a row of actions so the backend spaces its // children by the theme's action gap. - Widget& mountKind(reactive::Scope& scope, ActionBar const& spec, ContainerWidget* parent) { - ContainerWidget* const footer = overlayFooter(); - if (spec.wrap && footer != nullptr) { - throw std::invalid_argument{ - "morph::ui::Mounted: an overlay's footer is one row of actions; `wrap` is for an action bar in place"}; - } - StackWidget& widget = - scope.adopt(_backend->createStack(footer != nullptr ? footer : parent, Axis::Horizontal)); - // A wrapping row shares no width with its parent, as a wrapping ForEach does. - if (footer == nullptr && !spec.wrap) { - scope.make(_shareParents, &widget); - } - widget.setActionRow(); - if (spec.wrap) { - widget.setWrap(true); - } - applyCommon(scope, widget, spec.common); - widget.setGap(spacingStep(2)); - if (spec.align != Align::Stretch) { - widget.setAlign(spec.align); - } - if (spec.justify != Justify::Start) { - widget.setJustify(spec.justify); - } - // While the children mount, a horizontal ForEach whose parent is this bar is part of its row. - class Restore { - public: - Restore(Mounter& self, StackWidget* bar) : _self{&self}, _saved{std::exchange(self._actionBar, bar)} {} - Restore(Restore const&) = delete; - Restore& operator=(Restore const&) = delete; - Restore(Restore&&) = delete; - Restore& operator=(Restore&&) = delete; - ~Restore() { _self->_actionBar = _saved; } + Widget& mountKind(reactive::Scope& scope, ActionBar const& spec, ContainerWidget* parent); - private: - Mounter* _self; - StackWidget* _saved; - }; - Restore const restore{*this, &widget}; - for (Node const& child : spec.children) { - static_cast(mount(scope, child, &widget)); - } - return widget; - } + Widget& mountKind(reactive::Scope& scope, Custom const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, Custom const& spec, ContainerWidget* parent) { - CustomRequest request{.name = spec.name, .props = {}, .minVersion = spec.minVersion}; - request.props.reserve(spec.props.size()); - for (CustomProp const& prop : spec.props) { - request.props.push_back(prop.name); - } - if (std::unique_ptr loaded = _backend->createCustom(parent, request)) { - CustomWidget& widget = scope.adopt(std::move(loaded)); - for (CustomProp const& prop : spec.props) { - bindCustomProp(scope, widget, prop); - } - widget.setOnEvent(spec.onEvent); - return widget; - } - Widget* const fallback = mount(scope, spec.fallback, parent); - if (fallback == nullptr) { - throw std::invalid_argument{"morph::ui::Mounted: the custom node " + spec.name + " has no fallback"}; - } - return *fallback; - } + Widget& mountKind(reactive::Scope& scope, DateTimeInput const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, DateTimeInput const& spec, ContainerWidget* parent) { - DateTimeInputWidget& widget = - scope.adopt(_backend->createDateTimeInput(parent, spec.mode, spec.offsetMinutes)); - applyCommon(scope, widget, spec.common); - applyField(scope, widget, spec.field); - // Before the value, which is then shown in it; an input with no pattern is told none. - if (spec.pattern.isBound() || !spec.pattern.constant().empty()) { - bind(scope, spec.pattern, [&widget](std::string const& pattern) { widget.setPattern(pattern); }); - } - widget.setOnChange(inputEvent( - spec.onChange, - controlled(scope, spec.value, - [&widget](std::optional const& value) { widget.setValue(value); }))); - applyCaption(scope, widget, spec.label, spec.showLabel); - return widget; - } - - Widget& mountKind(reactive::Scope& scope, Slider const& spec, ContainerWidget* parent) { - SliderWidget& widget = scope.adopt(_backend->createSlider(parent)); - applyCommon(scope, widget, spec.common); - applyField(scope, widget, spec.field); - widget.setRange(spec.minimum, spec.maximum, spec.step); - widget.setOnChange(inputEvent( - spec.onChange, controlled(scope, spec.value, [&widget](std::int64_t value) { widget.setValue(value); }))); - widget.setOnCommit(event(spec.onCommit)); - return widget; - } + Widget& mountKind(reactive::Scope& scope, Slider const& spec, ContainerWidget* parent); - Widget& mountKind(reactive::Scope& scope, FilePicker const& spec, ContainerWidget* parent) { - FilePickerWidget& widget = scope.adopt(_backend->createFilePicker(parent, spec.mode)); - applyCommon(scope, widget, spec.common); - applyField(scope, widget, spec.field); - widget.setOnPicked(inputEvent(spec.onPicked, controlled(scope, spec.path, [&widget](std::string const& path) { - widget.setPath(path); - }))); - return widget; - } + Widget& mountKind(reactive::Scope& scope, FilePicker const& spec, ContainerWidget* parent); reactive::Runtime* _rt; IViewBackend* _backend; @@ -2530,8 +1802,18 @@ class Mounter { // The mounted widgets with a focus name. A multimap keeps equal names in insertion order, so the first mounted // is found first. FocusMap _focusable; + // The focus chain's tree: every widget a node mounted, by its container, and the roots in the order mounted. + std::unordered_map _chain; + std::vector _chainRoots; + std::unordered_map> _chainFlags; + // The rows of source tables: what is mounted in them is not on the chain. + std::unordered_set _offChain; // The mounted containers that take a share of their width for a child's. std::set _shareParents; + // What the mount did to the rows of its source tables. + MountStats _stats; + // The column extents of the source table mounted last, for tests. + std::weak_ptr _extents; }; } // namespace detail @@ -2580,7 +1862,7 @@ class Mounter { /// /// A mount must run to completion: nothing it calls, a backend factory or setter or a binding's evaluation, may /// destroy this object, its runtime or its backend. Widget callbacks are events, not part of a mount, and may. -class Mounted { +class MORPH_API Mounted { public: /// @param runtime The runtime the bindings are made in. Borrowed. /// @param backend Makes the widgets. Borrowed. @@ -2627,13 +1909,30 @@ class Mounted { /// @return Whether a mounted text input has that name. bool placeCursor(std::string_view focusId, std::size_t offset) { return _mounter.placeCursor(focusId, offset); } + /// @brief Moves keyboard focus to the control after the mounted widget whose `Common::focusId` is @p focusId on + /// the focus chain: the mounted widgets that take focus (a text input, a button, a check box, a select, a + /// menu, a date-time input, a slider, a file picker, a table, a tabs, a badge with `onRemove`), shown and + /// enabled with every container around them, in document order. + /// @param focusId The name. + /// @return Whether a control took focus: `false` when no widget has the name, or none comes after it. + bool focusNext(std::string_view focusId) { return _mounter.focusAlong(focusId, true); } + + /// @brief Moves keyboard focus to the control before the mounted widget whose `Common::focusId` is @p focusId on + /// the focus chain (`focusNext`). + /// @param focusId The name. + /// @return Whether a control took focus: `false` when no widget has the name, or none comes before it. + bool focusPrevious(std::string_view focusId) { return _mounter.focusAlong(focusId, false); } + + /// @brief What the mount did to the rows of its tables mounted over a `TableSource`, the whole mount's. + /// @return The counters; valid as long as this object. + [[nodiscard]] MountStats const& stats() const noexcept { return _mounter.stats(); } + + /// @brief The column extents of the table over a `TableSource` mounted last, for tests. + /// @return They, or null when no such table is mounted. + [[nodiscard]] ColumnExtents const* columnExtents() const noexcept { return _mounter.columnExtents(); } + private: - [[nodiscard]] static Node nonNull(Node root) { - if (!root) { - throw std::invalid_argument{"morph::ui::Mounted: the root node is null"}; - } - return root; - } + [[nodiscard]] static Node nonNull(Node root); Node _root; detail::Mounter _mounter; diff --git a/include/morph/ui/preferences.hpp b/include/morph/ui/preferences.hpp index 376a6d6c7..871df3103 100644 --- a/include/morph/ui/preferences.hpp +++ b/include/morph/ui/preferences.hpp @@ -143,6 +143,14 @@ inline constexpr std::size_t kMaxPrefNameBytes = 256; /// @brief The most points one `load` may ask for. inline constexpr std::size_t kMaxPrefPoints = 256; +/// @brief The type id the table-state model is registered under, and the application of the entry that keeps each +/// person's table-state quota. The preferences model refuses it as an `app`. +inline constexpr std::string_view kTableStateModel = "morph.tableState"; + +/// @brief The start of every scope table state writes under. The preferences model refuses a scope that starts with +/// it. +inline constexpr std::string_view kTableStateScopePrefix = "morph.table"; + /// @brief `load`: the stored choices of a screen's points. A request carries no person. struct PrefLoad { /// @brief The application. @@ -219,6 +227,7 @@ class PreferencesModel { ::core::async::Task execute(PrefLoad request) { checkName(request.app, "app"); checkName(request.scope, "scope"); + checkUnreserved(request.app, request.scope); if (request.points.size() > kMaxPrefPoints) { throw std::invalid_argument{"a load names more than " + std::to_string(kMaxPrefPoints) + " points"}; } @@ -285,6 +294,7 @@ class PreferencesModel { checkName(app, "app"); checkName(scope, "scope"); checkName(point, "point"); + checkUnreserved(app, scope); std::string person = verifiedPerson(); if (person.empty()) { throw std::runtime_error{"preferences are stored for a signed-in person"}; @@ -302,6 +312,19 @@ class PreferencesModel { } } + /// @brief Refuses the names table state writes under in the same store, so no preference can overwrite a table's + /// stored state or a person's table-state quota. + /// @param app The application. + /// @param scope The scope. + static void checkUnreserved(std::string const& app, std::string const& scope) { + if (app == kTableStateModel) { + throw std::invalid_argument{"`" + app + "` is kept for table state"}; + } + if (scope.starts_with(kTableStateScopePrefix)) { + throw std::invalid_argument{"`" + scope + "` is kept for table state"}; + } + } + std::shared_ptr _store; PreferencesOptions _options; }; diff --git a/include/morph/ui/stretch_columns.hpp b/include/morph/ui/stretch_columns.hpp new file mode 100644 index 000000000..b04cca308 --- /dev/null +++ b/include/morph/ui/stretch_columns.hpp @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once +#include +#include +#include +#include +#include +#include + +/// @file +/// @brief How a table's stretch columns share the width left to them. +/// +/// Specified in `docs/spec/ui/backend_contract.md`, "Table cells". The solver is backend-independent: the caller gives +/// each column's natural width, least width and floor in its backend's measure, and the room left after the fixed and +/// content columns. + +namespace morph::ui { + +/// @brief One stretch column's widths and weight, for `stretchWidths`. +struct StretchColumn { + /// @brief The width the column asks for: the larger of its header and its widest shown cell. + int natural = 0; + /// @brief The narrowest it is laid out without losing content; `natural` for a column that does not wrap. + int least = 0; + /// @brief The narrowest it goes before the table is short of room. + int floor = 0; + /// @brief The share of the spare width, from 1. + int weight = 1; + /// @brief Whether it gives up width before the other stretch columns. + bool shrink = false; +}; + +/// @brief The widths of a table's stretch columns in @p room. +/// +/// Each column is clamped so that `floor <= least <= natural`. With `sum` over the columns: +/// 1. `room >= sum(natural)`: each is its natural width plus its weighted share of the spare. +/// 2. `sum(least) <= room < sum(natural)`: each is its least width plus the share +/// `(natural - least) * (room - sum(least)) / (sum(natural) - sum(least))` of the room between its widths. +/// 3. `sum(floor) <= room < sum(least)`: each starts at its least width and the deficit is taken from the columns +/// that +/// shrink, last first, each down to its floor, then from the others in the same order. +/// 4. `room < sum(floor)`: each is its floor. +/// +/// In steps 1 to 3 the widths add up to @p room exactly: what a division leaves over goes one unit each to the first +/// columns that can take it. +/// @param columns The stretch columns, in layout order. +/// @param room The width left after the columns that do not stretch; a negative room is 0. +/// @return One width per column. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): the steps share the columns' working vectors, and each reads against the sums the one before computed +[[nodiscard]] inline std::vector stretchWidths(std::span columns, int room) { + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): every index runs below `count`, the + // size of `columns` and of each vector sized from it. + using Wide = std::int64_t; + std::size_t const count = columns.size(); + std::vector natural(count); + std::vector least(count); + std::vector floor(count); + std::vector weight(count); + for (std::size_t at = 0; at < count; ++at) { + floor[at] = std::max(0, columns[at].floor); + natural[at] = std::max(floor[at], columns[at].natural); + least[at] = std::clamp(columns[at].least, floor[at], natural[at]); + weight[at] = std::max(1, columns[at].weight); + } + Wide const sumNatural = std::accumulate(natural.begin(), natural.end(), Wide{0}); + Wide const sumLeast = std::accumulate(least.begin(), least.end(), Wide{0}); + Wide const sumFloor = std::accumulate(floor.begin(), floor.end(), Wide{0}); + Wide const weights = std::accumulate(weight.begin(), weight.end(), Wide{0}); + Wide const left = std::max(room, 0); + std::vector sizes(count, 0); + if (count == 0) { + return sizes; + } + if (left >= sumNatural) { + Wide const spare = left - sumNatural; + Wide given = 0; + for (std::size_t at = 0; at < count; ++at) { + Wide const share = spare * weight[at] / weights; + sizes[at] = static_cast(natural[at] + share); + given += share; + } + for (std::size_t at = 0; at < count && given < spare; ++at, ++given) { + ++sizes[at]; + } + } else if (left >= sumLeast) { + // Here `sumNatural > left >= sumLeast`, so the divisor is positive. + Wide given = 0; + for (std::size_t at = 0; at < count; ++at) { + Wide const share = Wide{natural[at] - least[at]} * (left - sumLeast) / (sumNatural - sumLeast); + sizes[at] = static_cast(least[at] + share); + given += share; + } + Wide remainder = left - sumLeast - given; + for (std::size_t at = 0; at < count && remainder > 0; ++at) { + if (natural[at] > least[at]) { + ++sizes[at]; + --remainder; + } + } + } else if (left >= sumFloor) { + sizes = least; + Wide deficit = sumLeast - left; + for (bool const shrinking : {true, false}) { + for (std::size_t at = count; at-- > 0 && deficit > 0;) { + if (columns[at].shrink == shrinking) { + Wide const take = std::min(sizes[at] - floor[at], deficit); + sizes[at] -= static_cast(take); + deficit -= take; + } + } + } + } else { + sizes = std::move(floor); + } + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + return sizes; +} + +} // namespace morph::ui diff --git a/include/morph/ui/table_config.hpp b/include/morph/ui/table_config.hpp new file mode 100644 index 000000000..5398ea44d --- /dev/null +++ b/include/morph/ui/table_config.hpp @@ -0,0 +1,845 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file ui/table_config.hpp +/// @brief How a user configures a table, as pure functions: sort gestures, layout gestures, the header and table +/// menus, value filters, conditions, copy text and the status line's messages. +/// +/// Nothing here holds state or talks to a backend: the lowering of a table node calls these with what it holds +/// and applies what they return. See `docs/spec/table/table.md`, "Configuring a table". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +/// @brief A group's column bound, `QueryLimits::maxGroupColumns`. +inline constexpr std::size_t kMaxGroupColumns = 16; + +/// @brief A table's sort chain, most significant key first. +using SortChain = table::SortChain; + +// --------------------------------------------------------------------------------------------------------------- +// The status line's messages +// --------------------------------------------------------------------------------------------------------------- + +/// @brief Writes a count with its digits grouped by three. +/// @param n The count. +/// @param separator The grouping separator: the session's numeric one (`","` in English). +/// @return The digits, a leading `-` for a negative count, grouped from the right (`10,000`). +[[nodiscard]] MORPH_API std::string groupedCount(std::int64_t n, std::string_view separator = ","); + +/// @brief What a table can let its user change about its columns, as `configurable` lists it. +enum class Configure : std::uint8_t { + None = 0, ///< Nothing. + Reorder = 1, ///< Moving columns. + Hide = 2, ///< Hiding and showing columns. + Pin = 4, ///< Pinning and unpinning columns. + Resize = 8, ///< Setting and clearing widths. + All = 15, ///< Everything. +}; + +/// @brief The union of two capability sets. +/// @param lhs One set. +/// @param rhs The other. +/// @return Every capability either holds. +[[nodiscard]] constexpr Configure operator|(Configure lhs, Configure rhs) noexcept { + return static_cast(static_cast(lhs) | static_cast(rhs)); +} + +/// @brief The intersection of two capability sets. +/// @param lhs One set. +/// @param rhs The other. +/// @return The capabilities both hold. +[[nodiscard]] constexpr Configure operator&(Configure lhs, Configure rhs) noexcept { + return static_cast(static_cast(lhs) & static_cast(rhs)); +} + +/// @brief Whether a capability set allows something. +/// @param set What the table allows. +/// @param what The capabilities asked for. +/// @return `true` when @p set holds every capability of @p what. +[[nodiscard]] constexpr bool allows(Configure set, Configure what) noexcept { return (set & what) == what; } + +/// @brief The status line's and the menus' messages, in exact English copy. +namespace tableText { + +/// @brief The refusal of a sort, filter or arrangement gesture while the table's header is disabled. +inline constexpr std::string_view kHeaderBusy = "Sorting, filtering and arranging are unavailable right now"; + +/// @brief The refusal of a sort key past the bound. +/// @param maxSortKeys The table's bound. +/// @return `A table sorts by at most {n} columns`. +[[nodiscard]] inline std::string sortBound(std::size_t maxSortKeys) { + return "A table sorts by at most " + groupedCount(static_cast(maxSortKeys)) + " columns"; +} + +/// @brief The refusal of a range over the bound. +/// @param maxRows The bound. +/// @param separator The grouping separator. +/// @return `A range selects at most {n} rows`. +[[nodiscard]] inline std::string rangeBound(std::size_t maxRows, std::string_view separator = ",") { + return "A range selects at most " + groupedCount(static_cast(maxRows), separator) + " rows"; +} + +/// @brief The refusal of a copy over the bound. +/// @param maxRows The bound. +/// @param separator The grouping separator. +/// @return `A copy holds at most {n} rows`. +[[nodiscard]] inline std::string copyBound(std::size_t maxRows, std::string_view separator = ",") { + return "A copy holds at most " + groupedCount(static_cast(maxRows), separator) + " rows"; +} + +/// @brief The notice after a copy. +/// @param rows The rows copied. +/// @param unloaded The cells copied as empty because they were not loaded. +/// @param separator The grouping separator. +/// @return `Copied {n} rows` (`Copied 1 row`), and with unloaded cells `, {m} cells were not loaded` +/// (`, 1 cell was not loaded`). +[[nodiscard]] MORPH_API std::string copied(std::size_t rows, std::size_t unloaded, std::string_view separator = ","); + +/// @brief The refusal of a gesture on a locked column. +/// @param label The column's label. +/// @return `{label} is locked`. +[[nodiscard]] inline std::string locked(std::string_view label) { return std::string{label} + " is locked"; } + +/// @brief The refusal of a gesture the table does not allow. +/// @param what The capability lacking; with several, the first of reorder, hide, pin and resize names it, and +/// with none, reorder does. +/// @return `This table's columns cannot be moved` (`hidden`, `pinned`, `resized`). +[[nodiscard]] MORPH_API std::string notConfigurable(Configure what); + +/// @brief The refusal of a group of too few or too many columns. +/// @return `A group has 2 to 16 columns`. +[[nodiscard]] inline std::string groupSize() { return "A group has 2 to 16 columns"; } + +/// @brief The refusal of a group of columns of different kinds. +/// @return `A group's columns hold one kind of value`. +[[nodiscard]] inline std::string groupKind() { return "A group's columns hold one kind of value"; } + +/// @brief The refusal of a group that takes a column another user-formed group holds. +/// @param label The column's label. +/// @param group The other group's label. +/// @return `{label} is already in {group}`. +[[nodiscard]] inline std::string alreadyGrouped(std::string_view label, std::string_view group) { + return std::string{label} + " is already in " + std::string{group}; +} + +/// @brief The refusal of hiding the last visible column. +/// @return `At least one column stays visible`. +[[nodiscard]] inline std::string lastVisible() { return "At least one column stays visible"; } + +/// @brief Why a values list is disabled: both sides are over `QueryLimits::maxSetValues`. +/// @return `Too many values to list; filter with a condition`. +[[nodiscard]] inline std::string tooManyValues() { return "Too many values to list; filter with a condition"; } + +/// @brief Why a date tree applies nothing: its buckets are over `QueryLimits::maxEntries`. +/// @return `Too many dates to list; filter with a condition`. +[[nodiscard]] inline std::string tooManyDates() { return "Too many dates to list; filter with a condition"; } + +/// @brief The note under a values list some rows were left out of while their cells load. +/// @return `The list may grow while data loads`. +[[nodiscard]] inline std::string mayGrow() { return "The list may grow while data loads"; } + +/// @brief The note under a values list about invalid cells. +/// @param cells How many cells could not be read. +/// @param separator The grouping separator. +/// @return `{n} cells could not be read` (`1 cell could not be read`). +[[nodiscard]] MORPH_API std::string unreadable(std::size_t cells, std::string_view separator = ","); + +} // namespace tableText + +// --------------------------------------------------------------------------------------------------------------- +// Sort chains +// --------------------------------------------------------------------------------------------------------------- + +/// @brief A user's gesture on a column's place in the sort chain. +enum class SortGesture : std::uint8_t { + Click, ///< A plain click: by this column alone, ascending, or descending when it is the first key ascending. + Extend, ///< `Shift`+click: flips the column's key in place, or appends it ascending. + Ascending, ///< "Sort ascending": by this column alone, ascending. + Descending, ///< "Sort descending": by this column alone, descending. + Add, ///< "Add to sort": appends the column ascending when the chain does not hold it. + Remove, ///< "Remove from sort": removes the column's key. +}; + +/// @brief What a sort gesture makes of a chain. +struct SortChange { + /// @brief The new chain; the old one when the gesture was refused. + SortChain chain; + /// @brief The status line's refusal, when the gesture was refused. + std::optional refusal; +}; + +/// @brief Applies a sort gesture to a chain. +/// +/// A gesture on a column the chain holds is decided before the bound, so at the bound a key in the chain still +/// flips; a new key past the bound is refused and the chain is unchanged, never shortened. +/// @param chain The current chain. +/// @param column The column's id. +/// @param gesture The gesture. +/// @param maxSortKeys The table's bound on the chain. +/// @return The new chain, or the old one with `tableText::sortBound(maxSortKeys)`. +[[nodiscard]] MORPH_API SortChange applySortGesture(SortChain const& chain, std::string const& column, + SortGesture gesture, std::size_t maxSortKeys); + +// --------------------------------------------------------------------------------------------------------------- +// Layout gestures +// --------------------------------------------------------------------------------------------------------------- + +/// @brief What a layout gesture needs to know of a column. +struct LayoutColumn { + /// @brief The column's id. + std::string id; + /// @brief The column's label, which a refusal names. + std::string label; + /// @brief The user cannot move, hide, pin, unpin or resize it. + bool locked = false; + /// @brief What the column holds; a user-formed group's columns are of one kind. + table::ColumnKind kind = table::ColumnKind::Text; +}; + +/// @brief Moves a column among the visible columns by `by` places (negative: towards the leading edge). +struct MoveColumn { + /// @brief The column's id. + std::string id; + /// @brief The places to move, clamped to the visible columns. + int by = 0; +}; + +/// @brief Moves a column to a place among the visible columns, as a drag drops it. +struct MoveColumnTo { + /// @brief The column's id. + std::string id; + /// @brief Its index among the visible columns after the move, clamped to the last. + std::size_t position = 0; +}; + +/// @brief Hides a column. +struct HideColumn { + /// @brief The column's id. + std::string id; +}; + +/// @brief Shows a hidden column. +struct ShowColumn { + /// @brief The column's id. + std::string id; +}; + +/// @brief Pins a column: it moves right after the pinned columns, and the pinned count grows by one. +struct PinColumn { + /// @brief The column's id. + std::string id; +}; + +/// @brief Unpins a column: it moves to the first place after the pinned columns, which shrink by one. +struct UnpinColumn { + /// @brief The column's id. + std::string id; +}; + +/// @brief Sets or clears a column's width. +struct ResizeColumn { + /// @brief The column's id. + std::string id; + /// @brief The width in units, above zero; `nullopt` clears it, and the column takes its declared width. + std::optional units; +}; + +/// @brief Restores the declared order, visibility, pinning and widths. +struct ResetColumns {}; + +/// @brief Sets or clears the unit a column shows one of its dimensions in. +struct SetDisplayUnit { + /// @brief The column's id. + std::string id; + /// @brief The dimension, such as `mass`. + std::string dimension; + /// @brief The unit's id; `nullopt`: the cells show their own units. + std::optional unit; +}; + +/// @brief Forms a group of columns of one kind under a label. +struct FormGroup { + /// @brief The group's label. + std::string label; + /// @brief The columns' ids, 2 to 16. + std::vector columns; +}; + +/// @brief Removes a user-formed group. +struct RemoveGroup { + /// @brief The group's id. + std::string id; +}; + +/// @brief Any gesture on a table's layout. +using LayoutGesture = std::variant; + +/// @brief What a layout gesture did. +struct LayoutResult { + /// @brief Whether the layout's stored value changed. + bool changed = false; + /// @brief The status line's refusal, when the gesture was refused. + std::optional refusal; +}; + +namespace detail { + +/// @brief What a layout gesture needs before it applies. +struct GestureNeeds { + /// @brief The capability the table must allow; `None` for a gesture that needs none. + Configure capability = Configure::None; + /// @brief Whether a locked column refuses the gesture. + bool lockable = false; + /// @brief The column the gesture acts on; empty for none. + std::string_view column; +}; + +/// @brief What a layout gesture needs. +/// @param gesture The gesture; the result views its column id. +/// @return Its capability, whether `locked` refuses it, and its column. +[[nodiscard]] MORPH_API GestureNeeds needsOf(LayoutGesture const& gesture); + +/// @brief Moves a column next to another in a layout's order. +/// @param layout The layout. +/// @param columnId The column to move. +/// @param anchor The column it moves beside; @p id itself leaves the order as it is. +/// @param after `true` to place it right after @p anchor, `false` right before. +MORPH_API void placeBeside(table::ColumnLayout& layout, std::string const& columnId, std::string const& anchor, + bool after); + +/// @brief A column's index among the visible columns. +/// @param visible The visible columns. +/// @param columnId The column. +/// @return The index; `visible.size()` when the column is not visible. +[[nodiscard]] inline std::size_t visibleIndex(std::vector const& visible, std::string const& columnId) { + return static_cast(std::ranges::find(visible, columnId) - visible.begin()); +} + +} // namespace detail + +/// @brief Applies a user's gesture to a table's layout. +/// +/// A move, hide, pin, unpin or resize of a locked column is refused with `tableText::locked(label)` before anything +/// else; then a gesture whose capability @p allowed lacks with `tableText::notConfigurable`. A reset is allowed while +/// any capability is; forming or removing a group while `reorder` or `hide` is, as the column chooser offers it. +/// Display units need no capability: they change what a column shows, not how the columns are arranged. Hiding the +/// last visible column is refused with `tableText::lastVisible()`. A gesture on a column @p columns does not list +/// changes nothing. +/// +/// The set of pinned columns changes only by `PinColumn` and `UnpinColumn`, and by `MoveColumnTo`, which pins a +/// column dropped among the pinned ones and unpins one dropped past them: `MoveColumn` stays on its side of the pin +/// boundary, and hiding a pinned column or showing one among the pinned columns adjusts the count. +/// @param layout The layout, changed in place. +/// @param columns The table's columns. +/// @param allowed What the table lets its user change. +/// @param gesture The gesture. +/// @return Whether the stored layout changed, or the refusal. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one visit over every gesture kind. +[[nodiscard]] MORPH_API LayoutResult applyLayoutGesture(table::ColumnLayout& layout, + std::span columns, Configure allowed, + LayoutGesture const& gesture); + +// --------------------------------------------------------------------------------------------------------------- +// Value filters +// --------------------------------------------------------------------------------------------------------------- + +/// @brief One tick in a values list, recorded as an operation and resolved at Apply. +/// +/// Under a search, "(Select all)" means the values the search shows, which the menu does not hold when they pass +/// a page; so a tick is kept as what the user did, not as the values it reached. +struct TickOp { + /// @brief The search the list showed; empty for none. + std::string search; + /// @brief Set: one value's box, by operand. Unset: "(Select all)" under `search`. + std::optional operand; + /// @brief The box's new state. + bool ticked = true; +}; + +/// @brief A values list's ticks, as operations. +struct ValueTicks { + /// @brief Every value's state before the first operation (true with no filter on the column). + bool ticked = true; + /// @brief The operations in order; a later one wins. + std::vector ops; + /// @brief "(Blanks)": `true` ticked, `false` unticked, `nullopt` when the list does not show it. + std::optional blanks; +}; + +/// @brief A values list's ticks, resolved to values. +struct ResolvedTicks { + /// @brief The state of every value no operation reached. + bool ticked = true; + /// @brief The final state of every value an operation reached, by operand. + std::map covered; + /// @brief "(Blanks)", as `ValueTicks::blanks`. + std::optional blanks; +}; + +/// @brief Resolves tick operations to the values they reached. +/// +/// The menu first gathers, for each distinct non-empty search among the operand-less operations, every value the +/// search shows (every page of `distinctValues`), and reads them back here through @p valuesUnder. +/// @param ticks The operations. +/// @param valuesUnder The operands a search shows; called only for a non-empty search of an operand-less operation. +/// @return The state every reached value ended in; an operation with no search and no operand clears what the +/// earlier ones reached and sets every value's state. +[[nodiscard]] MORPH_API ResolvedTicks resolveTicks( + ValueTicks const& ticks, std::function(std::string const& search)> const& valuesUnder); + +/// @brief Which side of a values list a filter sends, and how many values it names. +struct ValueFilterPlan { + /// @brief The side. + enum class Side : std::uint8_t { + All, ///< Every value ticked, "(Blanks)" not unticked: no values filter. + Include, ///< The ticked values, the smaller side. + Exclude, ///< The unticked values, the smaller side or a tie. + Nothing, ///< No value ticked, "(Blanks)" not ticked: no row passes, and the menu does not apply. + Disabled, ///< Both sides over the bound: the list is disabled, and the user narrows with a condition. + }; + /// @brief The side. + Side side = Side::All; + /// @brief How many values the side names. + std::size_t members = 0; + /// @brief The side names values no operation reached, so the menu pages every value to name them. + bool needsComplement = false; +}; + +/// @brief Decides which side of a values list to send. +/// +/// With D = @p distinct, C = `ticks.covered`, T the ticked values (every value outside C when `ticks.ticked`, plus +/// those C marks ticked) and U = D − T: `All` when T = D and "(Blanks)" is not unticked; `Nothing` when T = 0 and +/// "(Blanks)" is not ticked; otherwise `Include` when T < U, else `Exclude`, so a tie sends the unticked side. +/// @param distinct The column's distinct values, blanks not counted. +/// @param ticks The resolved ticks. +/// @param maxSetValues The bound on one `oneOf` entry (`QueryLimits::maxSetValues`). +/// @return The side, with `members = min(T, U)`; `Disabled` when that exceeds @p maxSetValues. +[[nodiscard]] MORPH_API ValueFilterPlan planValueFilter(std::int64_t distinct, ResolvedTicks const& ticks, + std::size_t maxSetValues); + +/// @brief How a values list's members are written. +enum class ValueForm : std::uint8_t { + Set, ///< One `oneOf` entry. + Ranges, ///< One `between` entry a member: date buckets, whose operand is `a..b`. +}; + +/// @brief Writes a values list's choice as a column filter. +/// +/// `Include` is `include = [oneOf members] + [isEmpty]` when "(Blanks)" is ticked, `Exclude` is +/// `exclude = [oneOf members] + [isEmpty]` when it is unticked, both under `combine: any`. The `oneOf` entry is left +/// out when there are no members, so ticking only "(Blanks)" is `include = [isEmpty]`. `Ranges` writes one +/// `between` a member in place of the `oneOf`. +/// @param side The side `planValueFilter` chose. +/// @param members The values on that side, as operands. +/// @param blanks "(Blanks)", as `ValueTicks::blanks`. +/// @param form How the members are written. +/// @return The filter; `nullopt` for `All`, `Nothing` and `Disabled`, and for a side left with no entry. +[[nodiscard]] MORPH_API std::optional valueFilter(ValueFilterPlan::Side side, + std::vector members, + std::optional blanks, + ValueForm form = ValueForm::Set); + +/// @brief Which part of a column's filter menu a filter belongs to. A column has one or the other, never both: +/// one `ColumnFilter` has one `combine`. +enum class FilterPart : std::uint8_t { + None, ///< No filter. + Values, ///< A values list's shape. + Conditions, ///< Anything else. +}; + +namespace detail { + +/// @brief How many operators an entry sets. +/// @param entry The entry. +/// @return The count; `caseSensitive` is a modifier and is not counted. +[[nodiscard]] MORPH_API std::size_t operatorCount(table::FilterEntry const& entry); + +/// @brief Whether entries are one side of a values list. +/// @param entries The side's entries. +/// @param kind The column's kind. +/// @return `true` for `{oneOf}`, `{oneOf, isEmpty}`, a date column's `between` buckets with or without `isEmpty`, or +/// a lone `isEmpty` on a column that has a values list (not `Custom`). +[[nodiscard]] MORPH_API bool valuesShape(std::span entries, table::ColumnKind kind); + +} // namespace detail + +/// @brief Tells whether a column's filter is a values list's or a set of conditions. +/// @param filter The column's filter. +/// @param kind The column's kind; a `Custom` column has no values list, so its lone `isEmpty` is a condition. +/// @return `None` with no entry; `Values` under `combine: any` with one side empty and the other a values list's +/// shape (`{oneOf}`, `{oneOf, isEmpty}`, a date column's `between` buckets with or without `isEmpty`, or a +/// lone `isEmpty`); `Conditions` otherwise. +[[nodiscard]] MORPH_API FilterPart classifyFilter(table::ColumnFilter const& filter, table::ColumnKind kind); + +// Every switch over `ColumnKind` here names each kind and has no `default`, so a kind added to the enum fails to +// compile until it is handled: clang and gcc warn through -Wswitch, and MSVC, whose C4062 is off by default, is told +// to treat it as an error. +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(push) +#pragma warning(error : 4062) +#endif + +/// @brief The wire form of an operand the user typed into a condition. +/// +/// A number in the locale's form becomes a decimal with a point and no grouping (`"1.234,5"` under a comma locale +/// is `"1234.5"`), read with the locale's own separators; an `Integer` or `Key` operand has no fraction. A `Measure` +/// operand is read by `parseMeasure` with the column's units and written by `measureOperand` (`"0,3 kg"` under a +/// comma locale is `"0.3 kg"`). A date is the picker's ISO text and, as text and every other kind, passes unchanged. +/// @param typed What the user typed. +/// @param kind The column's kind. +/// @param locale The locale the user types in. +/// @param units A `Measure` column's units: the table's description's. +/// @param chosenUnit A `Measure` operand's unit when the user typed none: the one the menu shows as chosen. +/// @return The operand, or `nullopt` when it does not read as the kind. +[[nodiscard]] MORPH_API std::optional canonicalOperand(std::string_view typed, table::ColumnKind kind, + LocaleFacts const& locale, + std::span units = {}, + std::string_view chosenUnit = {}); + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(pop) +#endif + +/// @brief How a column group's ticked values must be found among its columns. +enum class GroupMatch : std::uint8_t { + AnyColumn, ///< "in any column". + EveryColumn, ///< "in every column". + AtLeast, ///< "in at least N columns". + Exactly, ///< "in exactly N columns". + Together, ///< "all of them, each in a column". +}; + +/// @brief Writes a column group's values list as a group filter. +/// @param group The group's id. +/// @param groupColumns How many columns the group has. +/// @param ticked The ticked values, as operands. +/// @param blanks "(Blanks)"; ticked, it adds an `isEmpty` entry under `AnyColumn` only. +/// @param match How the values must be found. +/// @param n N, for `AtLeast` (1 to @p groupColumns) and `Exactly` (0 to @p groupColumns). +/// @return One `oneOf` entry with the quantifier `match` names; for `Together`, one `eq` a value in `together` mode, +/// refused unless 2 to @p groupColumns values are ticked. Refused, with why, when nothing is ticked or N is +/// out of range. +[[nodiscard]] MORPH_API std::expected groupValueFilter( + std::string group, std::size_t groupColumns, std::vector ticked, std::optional blanks, + GroupMatch match, std::int64_t n); + +// --------------------------------------------------------------------------------------------------------------- +// Conditions +// --------------------------------------------------------------------------------------------------------------- + +/// @brief One condition of a column's filter menu. +enum class ConditionOp : std::uint8_t { + Equals, ///< `eq`. + NotEquals, ///< `ne`. + Contains, ///< `contains`. + BeginsWith, ///< `startsWith`. + EndsWith, ///< `endsWith`. + Less, ///< `lt`. + LessOrEqual, ///< `le`. + Greater, ///< `gt`. + GreaterOrEqual, ///< `ge`. + Between, ///< `between`. + IsEmpty, ///< `isEmpty`. + IsNotEmpty, ///< `notEmpty`. +}; + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(push) +#pragma warning(error : 4062) +#endif + +/// @brief The conditions a column's kind offers. +/// @param kind The column's kind. +/// @return Text: equals, does not equal, contains, begins with, ends with. Numbers, measures and dates: =, ≠, <, ≤, +/// >, ≥, between. `Bool`: none (the values list alone). `Custom`: is empty, is not empty. +[[nodiscard]] MORPH_API std::vector conditionOps(table::ColumnKind kind); + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(pop) +#endif + +/// @brief A condition's label in the menu. +/// @param op The condition. +/// @param kind The column's kind: a text column's conditions are words, a number's and a date's symbols. +/// @return The label, such as `does not equal` or `≠`. +[[nodiscard]] MORPH_API std::string_view conditionLabel(ConditionOp op, table::ColumnKind kind); + +/// @brief Writes a condition as a filter entry. +/// @param op The condition. +/// @param operand Its operand, in wire form (`canonicalOperand`); unused by `IsEmpty` and `IsNotEmpty`. +/// @param second `Between`'s upper end; unused otherwise. +/// @param matchCase "match case": sets `caseSensitive` on a text condition. +/// @return The entry, with exactly one operator. +[[nodiscard]] MORPH_API table::FilterEntry conditionEntry(ConditionOp op, std::string operand, std::string second, + bool matchCase); + +// --------------------------------------------------------------------------------------------------------------- +// Menus +// --------------------------------------------------------------------------------------------------------------- + +/// @brief What a table menu's entry does when chosen. +enum class MenuCommand : std::uint8_t { + SortAscending, ///< "Sort ascending". + SortDescending, ///< "Sort descending". + AddToSort, ///< "Add to sort". + RemoveFromSort, ///< "Remove from sort". + Filter, ///< "Filter…": the column's filter menu. + FilterGroup, ///< "Filter {group}, {k} columns…": the group's filter menu; the argument is the group's id. + MoveLeft, ///< "Move left". + MoveRight, ///< "Move right". + PinColumn, ///< "Pin column". + UnpinColumn, ///< "Unpin". + HideColumn, ///< "Hide column". + DisplayUnit, ///< "Display unit": the argument is the dimension and the unit, joined by U+001F. + Columns, ///< "Columns…": the column chooser. + SortDialog, ///< "Sort…": the sort dialog. + ClearAllFilters, ///< "Clear all filters". + ResetColumns, ///< "Reset columns". + Copy, ///< "Copy". + CopyWithHeaders, ///< "Copy with headers". + ApplyView, ///< One of the user's views in "Views": the argument is the view's name. + SaveView, ///< "Save view…": the name dialog; a name the user already has replaces that view. + RenameView, ///< "Rename view…": the name dialog, for the view applied. + RemoveView, ///< "Remove view": the view applied. + SetDefaultView, ///< "Set as default": the view applied becomes the default. + DefaultOnMount, ///< "Start from the default view", checkable. + ApplySharedView, ///< One of the shared views: the argument is the view's name. + PublishView, ///< "Publish view…": the arrangement published to the shared views. + SaveAsMyView, ///< A shared view saved among the user's own: the argument is the view's name. + None, ///< Nothing: an entry that opens a submenu, or a heading. +}; + +/// @brief One entry of a table's menu: what it shows and what it does. +// NOLINTNEXTLINE(misc-no-recursion): a submenu is a vector of entries, so copying an entry copies its submenu. +struct TableMenuEntry { + /// @brief What a backend shows; its own `items` stay empty, and `menuEntries` fills them from this entry's. + MenuEntry entry; + /// @brief What choosing it does; not read on a separator or an entry with a submenu. + MenuCommand command = MenuCommand::SortAscending; + /// @brief The command's argument: a group's id for `FilterGroup`, the dimension and the unit joined by + /// U+001F for a display unit, else empty. + std::string argument; + /// @brief The submenu. + std::vector items; +}; + +/// @brief A column group as a menu names it. +struct MenuGroup { + /// @brief The group's id. + std::string id; + /// @brief The group's label. + std::string label; + /// @brief How many columns it has. + std::size_t columns = 0; +}; + +/// @brief One dimension a column's values have, and the units it can show them in. +struct MenuDimension { + /// @brief The dimension, such as `mass`. + std::string dimension; + /// @brief Unit ids, in the description's order. + std::vector units; + /// @brief The layout's display unit for the dimension; empty when the cells show their own. + std::string chosen; +}; + +/// @brief What a column's header menu is built from. +struct HeaderMenuInput { + /// @brief The column. + LayoutColumn column; + /// @brief Whether it can be sorted by. + bool sortable = false; + /// @brief Whether it can be filtered. + bool filterable = false; + /// @brief Its place in the sort chain; `nullopt` when the chain does not hold it. + std::optional sortPlace; + /// @brief The chain's length. + std::size_t chainSize = 0; + /// @brief The table's bound on the chain. + std::size_t maxSortKeys = 8; + /// @brief Its index among the visible columns. + std::size_t visibleIndex = 0; + /// @brief How many columns are visible. + std::size_t visibleCount = 0; + /// @brief How many of the first visible columns are pinned. + std::size_t pinned = 0; + /// @brief The dimensions its values have; non-empty adds "Display unit". + std::vector dimensions; + /// @brief The groups it is in. + std::vector groups; + /// @brief What the table lets its user change. + Configure allowed = Configure::All; +}; + +/// @brief What a table's "Views" submenu is built from. +struct ViewsMenuInput { + /// @brief The names of the user's own views, in their document's order. + std::vector own; + /// @brief The names of the shared views, in their document's order; empty when the store does not share. + std::vector shared; + /// @brief The view the arrangement was taken from: the state's `view`; none when it names none. + std::optional current; + /// @brief Whether `current` is a shared view, applied from "Shared views", rather than one of the user's own. + bool currentShared = false; + /// @brief Whether the arrangement differs from `current` as fitted to the table. + bool modified = false; + /// @brief Whether the default view's sort and filters apply at every mount. + bool defaultOnMount = false; + /// @brief Whether the store keeps the shared views for everyone, which offers "Publish view…". + bool shares = false; +}; + +/// @brief What a table's own menu is built from. +struct TableMenuInput { + /// @brief Whether any column or group has a filter. + bool anyFilter = false; + /// @brief The table's groups, declared and user-formed. + std::vector groups; + /// @brief What the table lets its user change. + Configure allowed = Configure::All; + /// @brief The saved views; none for a table that keeps no state, which has no "Views". + std::optional views; +}; + +namespace detail { + +/// @brief A menu entry that runs a command. +/// @param label The caption. +/// @param command The command. +/// @param enabled Whether it can be chosen. +/// @param keys The chord shown beside it; empty for none. +/// @param argument The command's argument. +/// @return The entry, with no submenu. +[[nodiscard]] MORPH_API TableMenuEntry command(std::string label, MenuCommand command, bool enabled = true, + std::string keys = {}, std::string argument = {}); + +/// @brief Joins menu sections. +/// @param sections The sections; an empty one is left out. +/// @return Their entries, with a separator between each two. +[[nodiscard]] MORPH_API std::vector joinSections(std::vector> sections); + +/// @brief A group's filter entry's caption. +/// @param group The group. +/// @return `Filter {label}, {k} columns…`. +[[nodiscard]] inline std::string groupLabel(MenuGroup const& group) { + return "Filter " + group.label + ", " + std::to_string(group.columns) + " columns…"; +} + +/// @brief A heading line: a label that is not a command. +/// @param label The caption. +/// @return The entry, which no backend lets a user choose. +[[nodiscard]] MORPH_API TableMenuEntry heading(std::string label); + +/// @brief A view's entry in "Views": checked while it is the view the arrangement was taken from, and labelled +/// `{name} (modified)` while the arrangement differs from it. +/// @param name The view's name. +/// @param command `ApplyView` or `ApplySharedView`. +/// @param current Whether it is the view the arrangement was taken from. +/// @param modified Whether the arrangement differs from it. +/// @return The entry; its argument is the name. +[[nodiscard]] MORPH_API TableMenuEntry viewEntry(std::string const& name, MenuCommand command, bool current, + bool modified); + +} // namespace detail + +/// @brief A table's "Views" submenu. +/// +/// In order, each part with a separator between: the user's own views, one checkable entry a view, checked while +/// the arrangement was taken from it and labelled `{name} (modified)` while it differs from it; "Save view…", +/// "Rename view…", "Remove view" and "Set as default", the last three enabled while the arrangement was taken from +/// one of the user's own views, then "Start from the default view", checkable; while there are shared views, the +/// heading "Shared views" and one entry a shared view, marked as an own view is; then "Save as my view" while the +/// arrangement was taken from a shared view, and "Publish view…" while the store shares. +/// @param input What the submenu is built from. +/// @return The "Views" entry, its submenu in `items`. +[[nodiscard]] MORPH_API TableMenuEntry viewsMenu(ViewsMenuInput const& input); + +/// @brief A column's header menu. +/// +/// In order, each part with a separator between: the sort entries (a sortable column); "Filter…" (a filterable +/// one) and one "Filter {group}, {k} columns…" a group the column is in; the arranging entries the table allows +/// ("Move left" and "Move right" for reorder, "Pin column" or "Unpin" for pin, "Hide column" for hide), disabled on +/// a locked column; and "Display unit", with a checkable entry `{dimension}: {unit}` a unit, when the column has +/// dimensions. "Add to sort" is disabled for a column in the chain and at the bound, "Remove from sort" for one +/// not in it. "Move left" and "Move right" stop at the pin boundary as at the ends. The lowering turns a choice of +/// the checked unit into `SetDisplayUnit` with no unit, which clears it. +/// @param input What the menu is built from. +/// @return The entries. +[[nodiscard]] MORPH_API std::vector headerMenu(HeaderMenuInput const& input); + +/// @brief A table's own menu. +/// +/// "Columns…" (while the table allows any arranging), "Sort…", one "Filter {group}, {k} columns…" a group, +/// "Clear all filters" (disabled with no filter), "Reset columns" (while any arranging is allowed); then "Views" +/// (`viewsMenu`) on a table that keeps a state; then "Copy" (`Ctrl+C`) and "Copy with headers". +/// @param input What the menu is built from. +/// @return The entries. +[[nodiscard]] MORPH_API std::vector tableMenu(TableMenuInput const& input); + +/// @brief What a backend shows for a table's menu. +/// @param entries The menu. +/// @return Each entry's `MenuEntry`, its submenu filled from the entry's `items`, in the same order, so a path of +/// indices names the same entry in both. +// NOLINTNEXTLINE(misc-no-recursion): one call per submenu level, bounded by the menu's depth. +[[nodiscard]] MORPH_API std::vector menuEntries(std::span entries); + +/// @brief The entry a backend reports chosen. +/// @param entries The menu. +/// @param path The indices, from the top menu down through each submenu. +/// @return The entry; null when the path leaves the menu or names a separator, a heading, a disabled entry or an +/// entry with a submenu. +[[nodiscard]] MORPH_API TableMenuEntry const* chosen(std::span entries, + std::span path); + +// --------------------------------------------------------------------------------------------------------------- +// Copy +// --------------------------------------------------------------------------------------------------------------- + +/// @brief The text a copy puts on the clipboard. +struct CopiedText { + /// @brief One line a row, its cells separated by tabs. + std::string text; + /// @brief The cells copied as empty because they were not loaded. + std::size_t unloaded = 0; +}; + +namespace detail { + +/// @brief Appends a cell's text as one clipboard field: each tab, CR LF, lone CR and lone LF becomes one space. +/// @param out The text to append to. +/// @param text The cell's text. +MORPH_API void appendField(std::string& out, std::string_view text); + +} // namespace detail + +/// @brief Writes rows as clipboard text. +/// @param labels The columns' labels, a first line; empty for no header line. +/// @param rows The rows' cell texts, in view order, by the visible columns; `nullopt` for an unloaded cell. +/// @return The text, lines separated by `\n` with none after the last; an unloaded cell is empty and counted. +[[nodiscard]] MORPH_API CopiedText copyText(std::span labels, + std::span> const> rows); + +} // namespace morph::ui diff --git a/include/morph/ui/table_dialogs.hpp b/include/morph/ui/table_dialogs.hpp new file mode 100644 index 000000000..fe3667a83 --- /dev/null +++ b/include/morph/ui/table_dialogs.hpp @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file ui/table_dialogs.hpp +/// @brief The column chooser, the sort dialog and the view name dialog a table's menu opens: what each lists, the +/// edits the sort dialog makes to a chain, and the dialogs' view trees. +/// +/// The view trees hold no state of their own: the lowering of a table node gives them what to read and what to call, +/// and carries out each change through the same gesture functions the header and the menus use +/// (`applyLayoutGesture`, `applySortGesture`), so a change made in a dialog is applied, refused and reported as the +/// same change made from a header is. See `docs/spec/table/table.md`, "Configuring a table". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +// --------------------------------------------------------------------------------------------------------------- +// The column chooser +// --------------------------------------------------------------------------------------------------------------- + +/// @brief One column as the column chooser lists it. +struct ChooserColumn { + /// @brief The column's id. + std::string id; + /// @brief Its label, the check box's caption. + std::string label; + /// @brief What it holds; "Group columns…" offers only columns of the first ticked column's kind. + table::ColumnKind kind = table::ColumnKind::Text; + /// @brief Whether it is visible. + bool shown = false; + /// @brief Whether its check box can be toggled: hiding is allowed, it is not locked, and it is not the only + /// visible column. + bool toggles = false; + /// @brief Whether "Move up" can move it: as "Move left" can in its header's menu. + bool up = false; + /// @brief Whether "Move down" can move it: as "Move right" can in its header's menu. + bool down = false; + /// @brief Whether the table lets its user move columns, which draws the move buttons. + bool movable = false; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(ChooserColumn const&) const = default; +}; + +/// @brief One user-formed group as the column chooser lists it. +struct ChooserGroup { + /// @brief The group's id. + std::string id; + /// @brief Its label. + std::string label; + /// @brief How many columns it has. + std::size_t columns = 0; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(ChooserGroup const&) const = default; +}; + +/// @brief What the column chooser shows. +struct ChooserState { + /// @brief Every column of the layout, in its order, hidden ones included. + std::vector columns; + /// @brief The groups the user formed, in the order they were formed. + std::vector groups; + /// @brief Whether the table lets its user move columns: the move buttons are drawn. + bool reorder = false; + /// @brief Whether the table lets its user hide columns: the check boxes can be toggled. + bool hide = false; + /// @brief Whether "Group columns…" is offered: while `reorder` or `hide` is allowed. + bool grouping = false; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(ChooserState const&) const = default; +}; + +/// @brief What the column chooser lists for a layout. +/// +/// A column the layout orders but @p columns does not list is left out, so a companion column, which is not among a +/// table's columns, is never listed. +/// @param layout The layout the table holds now. +/// @param columns The table's columns. +/// @param allowed What the table lets its user change. +/// @return The columns in the layout's order, with what each can do, and the user-formed groups. +[[nodiscard]] MORPH_API ChooserState chooserState(table::ColumnLayout const& layout, + std::span columns, Configure allowed); + +/// @brief The line the column chooser shows for a user-formed group. +/// @param group The group. +/// @return `{label}, {k} columns`, as `Pair, 2 columns`. +[[nodiscard]] inline std::string chooserGroupText(ChooserGroup const& group) { + return group.label + ", " + groupedCount(static_cast(group.columns)) + " columns"; +} + +/// @brief The group "Group columns…" is forming: open or not, its label and the columns ticked so far. +struct GroupDraft { + /// @brief Whether the form is shown. + bool open = false; + /// @brief The label typed. + std::string label; + /// @brief The ticked columns' ids, in the order they were ticked; the first decides the kind the rest must hold. + std::vector ticked; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(GroupDraft const&) const = default; +}; + +/// @brief Whether a draft can form its group: a label with more than spaces, and 2 to 16 ticked columns. +/// @param draft The draft. +/// @return Whether "Create group" is enabled. +[[nodiscard]] MORPH_API bool canFormGroup(GroupDraft const& draft); + +/// @brief What the column chooser reads and calls. Every reader is read inside a binding, so a change of what it +/// reads redraws what shows it. +struct ColumnChooserView { + /// @brief Whether the dialog is open. + std::function open; + /// @brief What it lists. + std::function state; + /// @brief The group being formed. + std::function draft; + /// @brief Replaces the group being formed. + std::function setDraft; + /// @brief A check box was toggled: the column's id and whether it is to be shown. + std::function onShow; + /// @brief A move button was pressed: the column's id and the places, -1 up or 1 down. + std::function onMove; + /// @brief "Reset columns" was pressed. + Action onReset; + /// @brief "Create group" was pressed: the label and the ticked columns in the layout's order. Returns whether the + /// group was formed, which closes and clears the form. + std::function)> onFormGroup; + /// @brief "Remove group" was pressed: the group's id. + std::function onRemoveGroup; + /// @brief "Done" was pressed, or the dialog dismissed. + Action onClose; +}; + +/// @brief The column chooser: a dialog, test id `table_columns`, titled "Columns". +/// +/// Per column, in the layout's order: a check box `table_columns_show_` (its label, checked while the column is +/// visible) and the buttons `table_columns_up_` and `table_columns_down_`, drawn while the table allows +/// moving. Then "Reset columns" (`table_columns_reset`) and, while moving or hiding is allowed, "Group columns…" +/// (`table_columns_group`), which shows the group form: a text input `table_group_label`, a check box +/// `table_group_column_` per column (once one is ticked, only columns of its kind stay enabled) and "Create group" +/// (`table_group_create`), enabled while `canFormGroup`. Under them, one line per user-formed group: a text +/// `table_group_` (`chooserGroupText`) and "Remove group" (`table_group_remove_`). "Done" +/// (`table_columns_done`) and a dismissal close it. +/// @param view What it reads and calls; every member must be set. +/// @return The dialog's node. +[[nodiscard]] MORPH_API Node columnChooser(ColumnChooserView view); + +// --------------------------------------------------------------------------------------------------------------- +// The sort dialog +// --------------------------------------------------------------------------------------------------------------- + +/// @brief Sets the column of the chain's key at a place. +struct SetSortColumn { + /// @brief The key's place in the chain, from 0. + std::size_t index = 0; + /// @brief The column's id; a column another key holds, or one that does not sort, changes nothing. + std::string column; +}; + +/// @brief Sets the direction of the chain's key at a place. +struct SetSortDirection { + /// @brief The key's place in the chain, from 0. + std::size_t index = 0; + /// @brief The direction. + table::SortDirection direction = table::SortDirection::Ascending; +}; + +/// @brief Moves the chain's key at a place by one place, swapping it with its neighbour. +struct MoveSortKey { + /// @brief The key's place in the chain, from 0. + std::size_t index = 0; + /// @brief -1 to move it towards the first key, 1 towards the last; a move past either end changes nothing. + int by = 0; +}; + +/// @brief Removes the chain's key at a place. +struct RemoveSortKey { + /// @brief The key's place in the chain, from 0. + std::size_t index = 0; +}; + +/// @brief Adds the first sortable column the chain does not hold, ascending, as its last key. +struct AddSortKey {}; + +/// @brief Any edit the sort dialog makes to a chain. +using SortEdit = std::variant; + +/// @brief Applies a sort dialog's edit to a chain. +/// +/// Adding and removing a key, and changing its direction, are the header's sort gestures (`SortGesture::Add`, +/// `Remove` and `Extend`), so "Add key" at the bound is refused with `tableText::sortBound` and the chain is kept. An +/// edit naming a place the chain does not have changes nothing. +/// @param chain The current chain. +/// @param sortable The ids of the columns that sort, in the table's order. +/// @param edit The edit. +/// @param maxSortKeys The table's bound on the chain. +/// @return The new chain, or the old one with the refusal. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one visit over the edit kinds. +[[nodiscard]] MORPH_API SortChange applySortEdit(SortChain const& chain, std::span sortable, + SortEdit const& edit, std::size_t maxSortKeys); + +/// @brief A sortable column as the sort dialog offers it. +struct SortColumnOption { + /// @brief The column's id. + std::string id; + /// @brief Its label. + std::string label; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(SortColumnOption const&) const = default; +}; + +/// @brief One key as the sort dialog lists it. +struct SortDialogKey { + /// @brief Its place in the chain, from 0. + std::size_t index = 0; + /// @brief Its column's id. + std::string column; + /// @brief Its direction. + table::SortDirection direction = table::SortDirection::Ascending; + /// @brief The columns its column select offers: the sortable columns no other key holds. + std::vector columns; + /// @brief Whether it can move towards the first key. + bool up = false; + /// @brief Whether it can move towards the last key. + bool down = false; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(SortDialogKey const&) const = default; +}; + +/// @brief What the sort dialog lists for a chain. +/// @param chain The chain. +/// @param sortable The columns that sort, in the table's order. +/// @return Its keys, in order. +[[nodiscard]] MORPH_API std::vector sortDialogKeys(SortChain const& chain, + std::span sortable); + +/// @brief What the sort dialog reads and calls. Every reader is read inside a binding. +struct SortDialogView { + /// @brief Whether the dialog is open. + std::function open; + /// @brief The chain the table sorts by now. + std::function chain; + /// @brief The columns that sort, in the table's order. + std::function()> sortable; + /// @brief An edit was made. + std::function onEdit; + /// @brief "Done" was pressed, or the dialog dismissed. + Action onClose; +}; + +/// @brief The sort dialog: a dialog, test id `table_sort`, titled "Sort". +/// +/// Per key `i` from 0: a select `table_sort_column_{i}` (the sortable columns no other key holds), a select +/// `table_sort_direction_{i}` (`ascending`, `descending`), and the buttons `table_sort_up_{i}`, `table_sort_down_{i}` +/// and `table_sort_remove_{i}`. Then "Add key" (`table_sort_add`), enabled while a sortable column is not in the +/// chain, and "Done" (`table_sort_done`); a dismissal closes it too. +/// @param view What it reads and calls; every member must be set. +/// @return The dialog's node. +[[nodiscard]] MORPH_API Node sortDialog(SortDialogView view); + +// --------------------------------------------------------------------------------------------------------------- +// The view name dialog +// --------------------------------------------------------------------------------------------------------------- + +/// @brief What the view name dialog reads and calls. Every reader is read inside a binding. +struct ViewNameDialogView { + /// @brief Whether the dialog is open. + std::function open; + /// @brief Its title: "Save view", "Rename view" or "Publish view". + std::function title; + /// @brief The name as typed so far. + std::function name; + /// @brief The name was edited. + std::function onName; + /// @brief "Save" was pressed, or Enter in the name, with a name that is not blank. + Action onSave; + /// @brief "Cancel" was pressed, or the dialog dismissed. + Action onClose; +}; + +/// @brief Whether a view's name is blank: empty, or spaces alone. +/// @param name The name. +/// @return Whether it is. +[[nodiscard]] inline bool blankViewName(std::string_view name) { + return name.find_first_not_of(" \t") == std::string_view::npos; +} + +/// @brief The view name dialog: a dialog, test id `table_view_dialog`, that names a view to save, rename or publish. +/// +/// A text input `table_view_name` (the name), a button `table_view_save` ("Save"), enabled while the name is not +/// blank, and a button `table_view_cancel` ("Cancel"); a dismissal closes it too. +/// @param view What it reads and calls; every member must be set. +/// @return The dialog's node. +[[nodiscard]] MORPH_API Node viewNameDialog(ViewNameDialogView view); + +} // namespace morph::ui diff --git a/include/morph/ui/table_filter_menu.hpp b/include/morph/ui/table_filter_menu.hpp new file mode 100644 index 000000000..53722edd3 --- /dev/null +++ b/include/morph/ui/table_filter_menu.hpp @@ -0,0 +1,600 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file ui/table_filter_menu.hpp +/// @brief A table's filter menu: what it edits, the state it holds while open, the filter it writes, and its view +/// tree. +/// +/// The menu edits one column's filter, or one group's: a values list (ticks over the distinct values the table's +/// rows list), or up to two conditions by the column's kind, never both. Ticks apply when the user presses Apply; +/// conditions apply on their own, `FilterMenuHost::debounce` after the last edit. The lowering of a table node owns +/// one `FilterMenu`, gives it a host that reaches the table's rows and filters, and mounts `filterMenuDialog` beside +/// the table. See `docs/spec/table/table.md`, "Filters from the header" and "Column groups". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +/// @brief What a filter menu edits: one column, or one group of columns. +struct FilterTarget { + /// @brief The column's id; empty for a group. + std::string column; + /// @brief A declared group's id, by which its values are pooled (`DistinctRequest::group`) and its filter named; + /// empty for a column and for a group the user formed. + std::string group; + /// @brief A group's columns, in the group's order; empty for a column. + std::vector columns; + /// @brief Whether the group is one the user formed: it has no values list, and its filter names its columns. + bool formed = false; + /// @brief The menu's title: the column's or the group's label. + std::string label; + /// @brief The column as it shows its values, with its kind; a group's first column. + table::TableColumn shown; + /// @brief What a `Measure` value is shown through; its registry is kept alive by `keep`. + DisplayUnits units; + /// @brief The table's units, which a `Measure` operand is read with. + std::vector unitList; + /// @brief The units a `Measure` condition offers, by id. + std::vector unitChoices; + /// @brief Whether the rows can list the column's values: the menu then shows a values list. + bool listed = true; + /// @brief Holds what `units` points into. + std::shared_ptr keep; +}; + +/// @brief A group's filter in a table's filters, as the menu finds it. +/// @param filters The table's filters. +/// @param target The group. +/// @return Its index in `filters.groups`: by id for a declared group, by its columns for one the user formed. +[[nodiscard]] MORPH_API std::optional groupFilterIndex(table::FilterSpec const& filters, + FilterTarget const& target); + +/// @brief One condition as the menu shows it while the user edits it. +struct ConditionDraft { + /// @brief The condition; none while the user has chosen none. + std::optional op; + /// @brief The operand as typed, or a date as the picker gives it (`YYYY-MM-DD`). + std::string operand; + /// @brief `between`'s upper end, as typed. + std::string second; + /// @brief A `Measure` operand's unit when the user typed none: one of `FilterTarget::unitChoices`. + std::string unit; + /// @brief Whether the operand, or the second, does not read as the column's kind. + bool invalid = false; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(ConditionDraft const&) const = default; +}; + +/// @brief One entry of a values list: a value, or a date bucket of the tree. +struct FilterListEntry { + /// @brief The value as the reply gave it. + table::DistinctValue value; + /// @brief A date tree's bucket; `Value` for a flat list. + table::DateBucket bucket = table::DateBucket::Value; + /// @brief The entry's depth in a date tree: 0 for a year, 1 for a month, 2 for a day. + std::size_t depth = 0; + /// @brief Whether a date bucket is opened, its children listed after it. + bool opened = false; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(FilterListEntry const&) const = default; +}; + +/// @brief What a filter menu holds while it is open. +struct MORPH_API FilterMenuState { + /// @brief Whether the menu is open. + bool open = false; + /// @brief Counts the menu's openings: a new opening builds its content again. + std::uint64_t opening = 0; + /// @brief The column or group it edits. + FilterTarget target; + /// @brief The search typed. + std::string search; + /// @brief The values listed: the pages asked for under `search`, or the date tree. + std::vector list; + /// @brief The values the search matches, as the last reply counted them. + std::int64_t distinct = 0; + /// @brief Every value of the column, the search aside; -1 until a reply without a search counted them. + std::int64_t total = -1; + /// @brief Rows with an empty cell, as the last reply counted them. + std::int64_t blanks = 0; + /// @brief Invalid cells, which no box ticks. + std::int64_t invalid = 0; + /// @brief Whether rows were left out because a cell was not loaded. + bool partial = false; + /// @brief Whether a reply to the values list came. + bool listedOnce = false; + /// @brief The ticks of a flat list, as operations. + ValueTicks ticks; + /// @brief The ticks of a date tree: each ticked bucket's operand, `a..b`. + std::vector dates; + /// @brief The two conditions. + std::array conditions; + /// @brief "match case", for a text column's conditions. + bool matchCase = false; + /// @brief How the two conditions join. + table::Combine combine = table::Combine::Any; + /// @brief A group's match line, and its N. + GroupMatch match = GroupMatch::AnyColumn; + /// @brief The N of "in at least N columns" and "in exactly N columns", as typed. + std::string count = "1"; + /// @brief Why the last Apply applied nothing; empty when it applied. + std::string refusal; + + /// @brief Memberwise equality. + /// @param other The state to compare with. + /// @return Whether every member matches. + bool operator==(FilterMenuState const& other) const; +}; + +// --------------------------------------------------------------------------------------------------------------- +// Pure parts +// --------------------------------------------------------------------------------------------------------------- + +namespace detail::filtermenu { + +/// @brief Folds ASCII letters to lower case, as a search's text is compared locally. +/// @param text The text. +/// @return It, folded. +[[nodiscard]] MORPH_API std::string folded(std::string_view text); + +/// @brief Reads a number from a slice of a text. +/// @tparam Number The integer type read. +/// @param text The text. +/// @param from The slice's first character. +/// @param count The slice's length; the slice ends where the text does when it is shorter. +/// @param out The number read. +/// @return Whether the slice starts with a number. +template +[[nodiscard]] inline bool readNumber(std::string_view text, std::size_t from, std::size_t count, Number& out) { + std::string_view const slice = text.substr(from, count); + return std::from_chars(std::to_address(slice.begin()), std::to_address(slice.end()), out).ec == std::errc{}; +} + +/// @brief The day a `YYYY-MM-DD` date, or the date part of an ISO date-time, falls on. +/// @param text The text. +/// @return Days since 1970-01-01; nothing when it does not read. +[[nodiscard]] MORPH_API std::optional dayOf(std::string_view text); + +/// @brief A date bucket's range, as days. +/// @param operand The bucket's operand, `a..b`. +/// @return Its first and last day; nothing when it does not read. +[[nodiscard]] MORPH_API std::optional> rangeOf(std::string_view operand); + +/// @brief A range of days as a date bucket's operand. +/// @param first Its first day. +/// @param last Its last day. +/// @param dateTime Whether the column holds date-times: its ends are `YYYY-MM-DDT00:00:00Z` and `…T23:59:59Z`. +/// @return `a..b`. +[[nodiscard]] MORPH_API std::string rangeText(std::int64_t first, std::int64_t last, bool dateTime); + +/// @brief Whether a ticked range covers a bucket. +/// @param ranges The ticked ranges' operands. +/// @param bucket The bucket's operand. +/// @return `{covered, own}`: whether a range covers it, and whether one of those is the bucket's own. +[[nodiscard]] MORPH_API std::pair coverOf(std::span ranges, std::string const& bucket); + +/// @brief Whether a text column's condition, or a number's or a date's, takes an operand. +/// @param op The condition. +/// @return `false` for `is empty` and `is not empty`. +[[nodiscard]] inline bool takesOperand(ConditionOp op) { + return op != ConditionOp::IsEmpty && op != ConditionOp::IsNotEmpty; +} + +/// @brief The condition an entry is, with its operands, when it is one the menu offers. +/// @param entry The entry. +/// @return The draft; nothing for an entry the menu cannot show. +[[nodiscard]] MORPH_API std::optional draftOf(table::FilterEntry const& entry); + +} // namespace detail::filtermenu + +/// @brief Merges the ticked buckets of a date tree into the ranges a filter sends. +/// +/// The ranges are sorted by their first end; one inside another adds nothing, and two that touch (the next begins +/// the day after the previous ends, or the second after on a date-time column) or overlap become one. +/// @param ticked The ticked buckets' operands, `a..b`, in any order. +/// @param dateTime Whether the column holds date-times: its ends are `YYYY-MM-DDT00:00:00Z` and `…T23:59:59Z`. +/// @return The ranges, ascending, as `a..b` operands; an operand that does not read is left out. +[[nodiscard]] MORPH_API std::vector mergeDateRanges(std::span ticked, bool dateTime); + +/// @brief A values list's ticks as a stored values filter makes them. +/// @param filter The column's filter, of the values part (`classifyFilter`). +/// @return The ticks: an include side ticks its members and nothing else, an exclude side unticks its members. +[[nodiscard]] MORPH_API ValueTicks ticksOfFilter(table::ColumnFilter const& filter); + +/// @brief The conditions a stored filter's entries are, as the menu shows them. +/// @param entries The include entries. +/// @return Up to two drafts, the rest of the array empty; nothing when an entry is one the menu cannot show or +/// there are more than two. +[[nodiscard]] MORPH_API std::optional> draftsOf( + std::span entries); + +/// @brief A group's match line as a filter's quantifier. +/// @param match The match line's choice; `Together` is not a quantifier and reads as `AnyColumn`. +/// @param n N, for `AtLeast` and `Exactly`. +/// @return The quantifier. +[[nodiscard]] MORPH_API table::ColumnCount columnCountOf(GroupMatch match, std::int64_t n); + +/// @brief A match line's text. +/// @param match The choice. +/// @return `in any column`, `in every column`, `in at least N columns`, `in exactly N columns`, or +/// `all of them, each in a column`. +[[nodiscard]] MORPH_API std::string_view matchLabel(GroupMatch match); + +/// @brief One line of a values list as the view draws it. +struct FilterListRow { + /// @brief What the line is. + enum class Kind : std::uint8_t { + Heading, ///< A `Measure` column's dimension, before its first value. + Value, ///< A value or a date bucket, with its box. + }; + /// @brief What the line is. + Kind kind = Kind::Value; + /// @brief The line's identity among the list's lines. + std::string key; + /// @brief A value's index in the list, the `{i}` of its test ids; the dimension of a heading. + std::string id; + /// @brief A value's box caption, `{text} ({count})`; a heading's dimension. + std::string label; + /// @brief Whether a value's box is ticked. + bool checked = false; + /// @brief Whether a value's box can be toggled: a bucket a ticked bucket above covers cannot. + bool enabled = true; + /// @brief Whether a date bucket opens to its months or days. + bool opens = false; + /// @brief The value's index in `FilterMenuState::list`. + std::size_t index = 0; + /// @brief The value's depth in a date tree. + std::size_t depth = 0; + + /// @brief Memberwise equality. + /// @return Whether every member matches. + bool operator==(FilterListRow const&) const = default; +}; + +/// @brief What a filter menu reaches of its table. +struct FilterMenuHost { + /// @brief The rows the values are asked of. + std::function rows; + /// @brief The filters the table holds now. + std::function filters; + /// @brief Applies the user's filters: the rows', the held ones and `onFiltersChange`. Returns whether they were + /// applied; a refusal is the host's to show. + std::function apply; + /// @brief A gesture on the table: clears its status line's message. + std::function touch; + /// @brief The columns a values list reads while the menu is open; empty when it closes. + std::function const&)> listing; + /// @brief Waits out the debounce; null applies each edit at once. + reactive::Scheduler* scheduler = nullptr; + /// @brief How long a search and a condition wait after the last edit. + std::chrono::milliseconds debounce{250}; + /// @brief The session's formatting: the values' texts, and the locale operands are typed in. + FormatContext format; + /// @brief The bound on one `oneOf` entry (`QueryLimits::maxSetValues`). + std::size_t maxSetValues = 10'000; + /// @brief The bound on one column's entries (`QueryLimits::maxEntries`). + std::size_t maxEntries = 32; + /// @brief The most values one request asks for while Apply names values (`QueryLimits::maxLimit`). + std::int64_t maxLimit = 1000; + /// @brief The values one page of the list shows (`DistinctRequest::limit`). + std::int64_t pageSize = 200; +}; + +/// @brief A table's filter menu: its state while open, the requests it makes and the filters it applies. +/// +/// Neither copied nor moved: its replies and timers hold it. +class MORPH_API FilterMenu { +public: + /// @brief A closed menu. + /// @param runtime The runtime its state belongs to. + explicit FilterMenu(reactive::Runtime& runtime) : _state{runtime} {} + + FilterMenu(FilterMenu const&) = delete; + FilterMenu& operator=(FilterMenu const&) = delete; + FilterMenu(FilterMenu&&) = delete; + FilterMenu& operator=(FilterMenu&&) = delete; + /// @brief Stops its timers; replies still in flight are dropped. + ~FilterMenu() = default; + + /// @brief Gives the menu what it reaches of its table: the lowering's, set again by each mount. + /// @param host The host. + void setHost(FilterMenuHost host) { _host = std::move(host); } + + /// @brief The menu's state. Tracked. + /// @return It. + [[nodiscard]] FilterMenuState const& state() const { return _state.get(); } + + /// @brief Opens the menu on a column or a group, showing the part its stored filter is, and asks for the first + /// page of its values. + /// @param target The column or group. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one ordered setup sharing `next`. + void open(FilterTarget target); + + /// @brief Closes the menu; a pending condition is dropped with it. + void close(); + + /// @brief The search typed: the list asks again, `debounce` after the last keystroke. + /// @param text The search. + void search(std::string text); + + /// @brief Ticks or unticks a value, or a date bucket. + /// @param index The value's index in the list. + /// @param checked Its new state. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one tick, by the kind of row it lands on. + void tick(std::size_t index, bool checked); + + /// @brief Ticks or unticks "(Select all)": every value the search shows, every page of them. + /// @param checked Its new state. + void tickAll(bool checked); + + /// @brief Ticks or unticks "(Blanks)". + /// @param checked Its new state. + void tickBlanks(bool checked); + + /// @brief Asks for the next page of values. + void more(); + + /// @brief Opens or closes a date bucket: an opened year lists its months, an opened month its days. + /// @param index The bucket's index in the list. + void openBucket(std::size_t index); + + /// @brief Chooses a condition: conditions apply `debounce` after the last edit. + /// @param which The condition, 0 or 1. + /// @param op The condition chosen. + void setOp(std::size_t which, ConditionOp op) { + editCondition([&](FilterMenuState& state) { state.conditions.at(which).op = op; }); + } + + /// @brief Types a condition's operand. + /// @param which The condition, 0 or 1. + /// @param text The operand. + void setOperand(std::size_t which, std::string text) { + editCondition([&](FilterMenuState& state) { state.conditions.at(which).operand = std::move(text); }); + } + + /// @brief Types `between`'s upper end. + /// @param which The condition, 0 or 1. + /// @param text The upper end. + void setSecond(std::size_t which, std::string text) { + editCondition([&](FilterMenuState& state) { state.conditions.at(which).second = std::move(text); }); + } + + /// @brief Chooses a `Measure` condition's unit. + /// @param which The condition, 0 or 1. + /// @param unit The unit's id. + void setUnit(std::size_t which, std::string unit) { + editCondition([&](FilterMenuState& state) { state.conditions.at(which).unit = std::move(unit); }); + } + + /// @brief Sets "match case". + /// @param enabled Whether text conditions match case. + void setMatchCase(bool enabled) { + editCondition([&](FilterMenuState& state) { state.matchCase = enabled; }); + } + + /// @brief Sets how the two conditions join. + /// @param combine `All` for "and", `Any` for "or". + void setCombine(table::Combine combine) { + editCondition([&](FilterMenuState& state) { state.combine = combine; }); + } + + /// @brief Chooses a group's match line; a group's conditions apply it as they apply an edit. + /// @param match The choice. + void setMatch(GroupMatch match); + + /// @brief Types the N of a group's match line. + /// @param text N, as typed. + void setCount(std::string text); + + /// @brief Applies the menu: a condition waiting for its debounce goes at once; otherwise the ticks are resolved, + /// every page of the values they reach asked for, and the side `planValueFilter` chooses is set. The menu + /// closes once the filter is applied, and says in its note why when nothing is. + void apply(); + + /// @brief "Clear filter": removes the column's or the group's filter, and the menu's ticks and conditions. + void clearFilter(); + + /// @brief The list's lines as the view draws them: a `Measure` column's dimension heading before its first + /// value, each value's caption by the column's display and its count, ticked as the ticks say. Tracked. + /// @return The lines. + [[nodiscard]] std::vector rows() const; + + /// @brief Whether "(Select all)" shows ticked: every value listed is. Tracked. + /// @return It. + [[nodiscard]] bool allTicked() const; + + /// @brief Whether Apply can apply something: a condition, or a values list with a box ticked. A date tree's + /// Apply with nothing ticked clears its filter, so it is always enabled. Tracked. + /// @return It. + [[nodiscard]] bool canApply() const; + + /// @brief The note under the list: that it may grow, how many cells could not be read, and why the last Apply + /// applied nothing, one a line. Tracked. + /// @return It. + [[nodiscard]] std::string note() const; + + /// @brief Whether the open target shows a values list. + /// @param state The menu's state. + /// @return `false` for a group the user formed, a `Custom` column, and rows that list no values. + [[nodiscard]] static bool valuesListed(FilterMenuState const& state); + + /// @brief Whether the open target's list is a date tree. + /// @param state The menu's state. + /// @return `true` on a `Date` or `DateTime` column. + [[nodiscard]] static bool dates(FilterMenuState const& state); + +private: + using Reply = std::expected; + + static void clearConditions(FilterMenuState& state); + + [[nodiscard]] static bool hasConditions(FilterMenuState const& state) { + return std::ranges::any_of(state.conditions, [](ConditionDraft const& draft) { return draft.op.has_value(); }); + } + + [[nodiscard]] static std::vector columnsOf(FilterTarget const& target) { + return target.column.empty() ? target.columns : std::vector{target.column}; + } + + // "all of them, each in a column" is offered while 2 or more values are ticked: below that the match line falls + // back to its default. + static void leaveTogether(FilterMenuState& state); + + // Whether a date bucket lies under a listed bucket that is ticked itself. + [[nodiscard]] static bool underTicked(FilterMenuState const& state, std::size_t index); + + // Whether a value's box shows ticked: the ticks' first state, then each operation that reaches it in order. A + // search reaches the values whose text contains it, folded. + [[nodiscard]] static bool tickedNow(FilterMenuState const& state, table::DistinctValue const& value); + + static void readGroup(FilterMenuState& next, table::GroupFilter const& group); + + void touch() const; + + // Runs @p fn after the debounce, replacing what @p timer held; at once without a scheduler. + void later(reactive::TimerHandle& timer, std::function fn); + + template + void editCondition(F&& edit) { + touch(); + _state.mutate([&](FilterMenuState& state) { + std::forward(edit)(state); + // Editing a condition leaves the values part: its ticks start again. + state.ticks = ValueTicks{.ticked = !dates(state) && !state.target.column.empty(), + .ops = {}, + .blanks = state.blanks > 0 ? std::optional{!dates(state)} : std::nullopt}; + state.dates.clear(); + state.refusal.clear(); + }); + scheduleSend(); + } + + void scheduleSend(); + + [[nodiscard]] table::DistinctRequest requestOf(FilterMenuState const& state) const; + + void ask(table::DistinctRequest request, std::function done); + + // Asks for the list's first page under the search, or with @p next the page after those listed. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the request and its reply share one edit. + void load( + bool + next); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the reply's continuations are owned by the scope. + + // Every value a search shows, every page of them, asked at `maxLimit` a request. + void pageAll( + std::string search, + std::function, std::string>, std::int64_t distinct)> + done); + + // Resolves the ticks: the values each search's "(Select all)" reached, one search after another, and the count + // of every value. + void resolve(std::function, std::string>)> const& done); + + void refuse(std::string why) { + _state.mutate([&](FilterMenuState& state) { state.refusal = std::move(why); }); + } + + // Sets @p spec and closes the menu once it is applied. + void commit(table::FilterSpec spec); + + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one resolve-then-write sequence. + void applyValues(); + + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one resolve-then-write sequence. + void applyGroupValues(); + + void applyDates(); + + // Sends the conditions when every operand reads and every `between` has both ends; marks those that do not + // read. Returns whether a filter was sent. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): reads both condition lines into one filter. + bool sendConditions(); + + reactive::Signal _state; + FilterMenuHost _host; + reactive::TimerHandle _searchTimer; + reactive::TimerHandle _sendTimer; + std::uint64_t _serial = 0; + /// Last, so it is the first to go: no reply or timer reaches a half-destroyed menu. + async::CallbackScope _scope; +}; + +// --------------------------------------------------------------------------------------------------------------- +// The view +// --------------------------------------------------------------------------------------------------------------- + +namespace detail::filtermenu { + +/// @brief A date as the picker shows it. +/// @param text `YYYY-MM-DD`, or an ISO date-time's date part. +/// @return The instant at its start, UTC; nothing for text that does not read. +[[nodiscard]] MORPH_API std::optional instantOf(std::string_view text); + +/// @brief The operand a picked instant is. +/// @param instant The instant, UTC. +/// @param dateTime Whether the column holds date-times. +/// @return `YYYY-MM-DD`, or `YYYY-MM-DDTHH:MM:SSZ`. +[[nodiscard]] MORPH_API std::string operandOfInstant(time::DateTime const& instant, bool dateTime); + +/// @brief One condition's line: the condition select, the operand (a text input, or the date picker), `between`'s +/// second end and a `Measure` column's unit. +/// @param menu The menu. +/// @param which The condition, 0 or 1. +/// @param target The column or group the menu edits. +/// @return The line. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one line's controls, by condition kind. +[[nodiscard]] MORPH_API Node conditionLine(FilterMenu& menu, std::size_t which, FilterTarget const& target); + +/// @brief The menu's content for one opening: what it shows depends on what it edits, so each opening builds it. +/// @param menu The menu. +/// @param target What the opening edits. +/// @return The content. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one widget per part the spec lists. +[[nodiscard]] MORPH_API Node menuContent(FilterMenu& menu, FilterTarget const& target); + +} // namespace detail::filtermenu + +/// @brief The filter menu: a dialog, test id `table_filter`, titled with the column's or the group's label. +/// +/// Its content is built for each opening, by what the menu edits. A values list: a search `table_filter_search`, a +/// box "(Select all)" `table_filter_all` and one "(Blanks)" `table_filter_blanks` while the column has empty cells, +/// then a box `table_filter_value_{i}` per value (`{text} ({count})`, in the reply's order, `i` from 0), a +/// `Measure` column's dimension heading `table_filter_heading_` before its first value, a button +/// `table_filter_open_{i}` on a date bucket that opens to its months or days, and "More values" +/// (`table_filter_more`). A date tree has no search and no "(Select all)". A note `table_filter_note`. The +/// conditions, by the column's kind: `table_filter_op_1` and `_2`, `table_filter_operand_1` and `_2` (a date +/// picker on a date column), `table_filter_second_1` and `_2` for `between`, `table_filter_unit_1` and `_2` on a +/// `Measure` column, `table_filter_combine`, and "match case" (`table_filter_case`) on a text column. A group's +/// match line `table_filter_match` and its N `table_filter_count`. Then Apply (`table_filter_apply`) and "Clear +/// filter" (`table_filter_clear`). A dismissal closes it. +/// @param menu The menu; it must outlive the node. +/// @return The dialog's node. +[[nodiscard]] MORPH_API Node filterMenuDialog(FilterMenu& menu); + +} // namespace morph::ui diff --git a/include/morph/ui/table_rows.hpp b/include/morph/ui/table_rows.hpp new file mode 100644 index 000000000..7082a5502 --- /dev/null +++ b/include/morph/ui/table_rows.hpp @@ -0,0 +1,1942 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file ui/table_rows.hpp +/// @brief What a table's mount reads, whoever serves its rows: `TableRows`, over the engine (`EngineRows`) or over +/// a server's pages (`WindowRows`); and `ValueRowsSource`, a document's rows as the engine's source. +/// +/// `EngineRows` holds every row: `visible` does nothing and `keysOf` completes at once. `WindowRows` holds the +/// pages around the visible rows in a `table::PageWindow`, sends the fetches the window asks for through the +/// session's read, which makes no cache entry, and keeps the window current from the table record's change events. +/// It owns the two timing rules the window has no clock for: when a fetch goes while the user scrolls, and how +/// often an order that waits for a level is fetched again. +/// +/// A row is a record keyed by column id. `EngineRows` builds it with the caller's `RecordOf`; `WindowRows` converts +/// the cells the latest `visible` call named, one at a time. Both keep the record until the row changes. +/// +/// See `docs/spec/table/table.md`, "The client table model". + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +namespace testing { +/// @brief What a test reads of a `WindowRows` that its interface does not show; the tests define it. +struct WindowRowsProbe; +} // namespace testing + +/// @brief The rows of a table's view, as far as the model knows them. +struct TableTotal { + /// @brief Rows in the view, or a lower bound (see `kind`). + std::int64_t rows = 0; + /// @brief Whether `rows` is the count of the view or a lower bound. + table::TotalKind kind = table::TotalKind::Exact; + /// @brief `false` until a server-mode table's first reply; always `true` over the engine. + bool known = false; + + /// @brief Member-wise equality. + /// @param other The total to compare with. + /// @return `true` when rows, kind and knowledge match. + [[nodiscard]] bool operator==(TableTotal const& other) const = default; +}; + +/// @brief One row of the view: its key and its record, both owned by the model. +/// +/// The references hold until the model's next `onChange`. +struct TableRowRef { + /// @brief The row's key. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members): a view onto the model's row. + table::RowId const& key; + /// @brief The row as a record keyed by column id. A field the model does not hold for the row is absent. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members): a view onto the model's row. + Value const& row; +}; + +/// @brief What the status line counts. +struct TableCountsView { + /// @brief The view's rows. + TableTotal view; + /// @brief Rows before the filter, where the model knows it. + std::optional source; + /// @brief Rows the filter can neither admit nor reject until a level loads. + std::int64_t undecided = 0; + /// @brief A sort, filter or fetch is in flight. + bool pending = false; + /// @brief Levels the order still waits for. + std::vector awaiting; + /// @brief Levels whose load failed for a row the table shows or orders by. + std::vector failed; + /// @brief Held view rows that are retained and no longer match the filter. + std::int64_t retained = 0; + /// @brief Rows an action of this session is working on: `RowStates::busyCount`. + std::int64_t busy = 0; +}; + +/// @brief What `TableRows::retain` did with the keys it was given. +enum class RetainResult : std::uint8_t { + Retained, ///< The keys are retained, those retained already included. + OverBound, ///< None is: they would take the set past `table::QueryLimits::maxRetained`. +}; + +/// @brief Where a key's row is in the view: its view index, nothing when the view has no row with the key, or why +/// that cannot be told. +using RowLocation = std::expected, table::TableError>; + +/// @brief A row `TableRows::fetchRows` fetched by its key: where it is in the view, and its cells. +struct FetchedRow { + /// @brief The row's key. + table::RowId key; + /// @brief The row's view index under the current sort and filters. + std::int64_t viewRow = 0; + /// @brief One cell per column asked for, in that order; `table::Unloaded` for a cell of a level the row has not + /// loaded, empty for a column the rows do not have. + std::vector cells; +}; + +/// @brief The view a selection of the view is of: what the server resolves it against. +struct ViewSelection { + /// @brief The view's filter, as the table queried it. + table::FilterSpec filters; + /// @brief The rows the view kept although they no longer match. + std::vector retained; + /// @brief The view's `viewRevision` when the user selected it. + std::string revision; + + /// @brief Member-wise equality. + /// @param other The view to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(ViewSelection const& other) const = default; +}; + +/// @brief What a user selected in a table: exactly some keys, or every row of a view less some keys. Its JSON is +/// `table::RowSelection`'s (`selectionJsonOf`). +struct TableSelection { + /// @brief Without `view`: exactly these rows. + std::vector keys; + /// @brief With it: every row of that view, less `except`. + std::optional view; + /// @brief The keys a selection of the view leaves out. + std::vector except; + + /// @brief Member-wise equality. + /// @param other The selection to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(TableSelection const& other) const = default; +}; + +/// @brief Whether a selected count is the count or an estimate; element value `exact` or `approximate`. +enum class CountKind : std::uint8_t { + Exact, ///< The count of the rows selected. + Approximate, ///< An estimate: the total is a lower bound, or a key left out is not accounted for. +}; + +/// @brief How many rows a selection holds. +struct SelectedCount { + /// @brief The rows. + std::int64_t rows = 0; + /// @brief Whether `rows` is exact. + CountKind kind = CountKind::Exact; + + /// @brief Member-wise equality. + /// @param other The count to compare with. + /// @return `true` when rows and kind match. + [[nodiscard]] bool operator==(SelectedCount const& other) const = default; +}; + +/// @brief Why the view cannot be selected yet: its membership is still open. +struct SelectAllRefusal { + /// @brief Rows the filter cannot decide until a level loads. + std::int64_t undecided = 0; + /// @brief The awaited levels a filtered column needs. + std::vector levels; +}; + +/// @brief The JSON of a selection, as an action's body carries it: `{"keys": […]}`, or `{"view": {…}, "except": +/// […]}` with the filter's default members left out. +/// @param selection The selection. +/// @return The JSON text. +[[nodiscard]] MORPH_API std::string selectionJsonOf(TableSelection const& selection); + +/// @brief What the status line says when select-all is refused. +/// @param refusal Why. +/// @param locale The formatting facts: the count's group separator. +/// @return `"Select all is available once rows are decided"`, or with no undecided row `"Select all is available +/// once data has loaded"`, or with neither `"Select all is available once the +/// rows have loaded"`: the view has not answered its current query yet. +[[nodiscard]] MORPH_API std::string selectAllRefusalText(SelectAllRefusal const& refusal, FormatContext const& locale); + +/// @brief The rows of one table an action's reply says it changed, and those it could not. +struct ChangedRowsValue { + /// @brief The rows changed. + std::vector rows; + /// @brief The rows the action could not change, each with its message. + std::vector failed; + + /// @brief Member-wise equality. + /// @param other The value to compare with. + /// @return `true` when rows and failures match. + [[nodiscard]] bool operator==(ChangedRowsValue const& other) const = default; +}; + +/// @brief Reads the `ChangedRows` of one table from an action's reply. +/// +/// Each path the catalog gives for @p record names a `ChangedRows`' `rows` member: `".rows"`, or `"rows"` +/// for the result itself. The value at the path's parent is read as `{"rows": [{"key", "from"}], "failed": [{"key", +/// "message"}]}`; a number is an integer key and a string a text key, and an entry whose `key` is neither is +/// skipped, as is a `from` of neither. +/// @param reply The action's reply. +/// @param action The action's catalog entry. +/// @param record The table's record, `.`. +/// @return The rows of every such path, in the reply's order; none when the catalog names no path for @p record. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one walk down the reply along the catalog's path. +[[nodiscard]] MORPH_API ChangedRowsValue changedRowsOf(Value const& reply, ActionInfo const& action, + std::string_view record); + +/// @brief The rows of a table an action of this session is working on, and those an action could not change. +/// +/// A run's rows are busy until it settles, whatever its outcome: the keys of a key selection or of a row, or every +/// row of a selection of the view but its `except`. Runs are kept apart, so two runs over one row keep it busy until +/// both settle. A failed row holds its message until its mark is cleared. +class MORPH_API RowStates { +public: + /// @brief Makes rows busy for a run; a run named again adds to its keys. + /// @param run The run's id, unique in the session. + /// @param keys The rows' keys. + void busyKeys(std::uint64_t run, std::vector keys); + + /// @brief Makes every row of a selection of the view busy for a run, but its `except`. + /// @param run The run's id, unique in the session. + /// @param except The keys the selection leaves out. + /// @param count The rows the selection held when the run started: what `busyCount` counts for it. + void busyView(std::uint64_t run, std::vector except, std::int64_t count); + + /// @brief Ends a run: its rows are no longer busy for it, whatever its outcome. + /// @param run The run's id; one that holds nothing is ignored. + void settle(std::uint64_t run); + + /// @brief Marks rows an action could not change, each with its message; a row marked already takes the new one. + /// @param rows The rows. + void fail(std::span rows); + + /// @brief Drops the failed marks of some rows. + /// @param keys The rows' keys. + void clearFailed(std::span keys) { + std::erase_if(_failed, [&keys](table::FailedRow const& row) { return std::ranges::contains(keys, row.key); }); + } + + /// @brief Drops every failed mark. + void clearFailed() { _failed.clear(); } + + /// @brief Moves a row's busy membership and failed mark from its old key to its new one; where the new key has + /// its own, the new key's is kept and the old key's dropped. + /// @param from The row's old key. + /// @param target The row's new key. + void move(table::RowId const& from, table::RowId const& target); + + /// @brief Whether a row is busy: a key run holds it, or a view run does not leave it out. + /// @param key The row's key. + /// @return `true` while any run in flight works on it. + [[nodiscard]] bool isBusy(table::RowId const& key) const; + + /// @brief A row's failed mark. + /// @param key The row's key. + /// @return Its message, or nothing for a row not marked. + [[nodiscard]] std::optional failure(table::RowId const& key) const; + + /// @brief How many rows are busy. + /// @return With no view run in flight, the distinct keys of the key runs; with one, the largest `count` among + /// the view runs plus the distinct keys of key runs that every view run leaves out, which are outside its + /// rows. + [[nodiscard]] std::int64_t busyCount() const; + + /// @brief The rows marked failed. + /// @return Their keys, in the order they failed. + [[nodiscard]] std::vector failedKeys() const; + +private: + // A selection of the view a run works on: the keys it leaves out, and the rows it held when the run started. + struct ViewRun { + std::vector except; + std::int64_t count = 0; + }; + + std::map> _keyRuns; + std::map _viewRuns; + std::vector _failed; +}; + +/// @brief What a table's mount reads, whatever serves the rows. +/// +/// Every member is called on the runtime's owner. +class MORPH_API TableRows { +public: + /// @brief A model with no rows of its own yet. + TableRows() = default; + TableRows(TableRows const&) = delete; + TableRows& operator=(TableRows const&) = delete; + TableRows(TableRows&&) = delete; + TableRows& operator=(TableRows&&) = delete; + virtual ~TableRows() = default; + + /// @brief The view's rows. + /// @return The total. + [[nodiscard]] virtual TableTotal total() const = 0; + + /// @brief The rows a mount realizes: the view's, and the rows a decorator adds outside it, such as summary rows, + /// which no count and no selection takes in. A decorator over such rows forwards this too, or the rows they + /// add are dropped. + /// @return The total the mount positions rows by; `total()` for rows that add none. + [[nodiscard]] virtual TableTotal mountedTotal() const { return total(); } + + /// @brief The row at a view index, or nothing while it is not fetched. + /// @param index The view index. + /// @return The row; its references hold until the next `onChange`. + [[nodiscard]] virtual std::optional row(std::int64_t index) const = 0; + + /// @brief The levels not loaded for the row at a view index, and which of them failed. + /// @param index The view index. + /// @return Views into the model, valid until its next `onChange`; empty when the row is not held. + [[nodiscard]] virtual table::UnloadedLevels unloadedLevels(std::int64_t index) const = 0; + + /// @brief Tells the model which rows and which columns are in or near view; a server-mode model fetches them. + /// @param first The first view row. + /// @param count The rows. + /// @param columns The column ids the rows' records hold; empty means every column. + virtual void visible(std::int64_t first, std::int64_t count, std::span columns) = 0; + + /// @brief The keys of a range of view rows, for a range selection; completes when every key is known. + /// @param first The first view row. + /// @param count The rows. + /// @return The keys in view order, or why they cannot be had. + virtual async::Completion, table::TableError>> keysOf( + std::int64_t first, std::int64_t count) = 0; + + /// @brief Finds the view index of the row with a key, under the current sort and filters, whether or not the row + /// is held: what focus follows its key by when a new order moves it away from the rows in view. + /// @param key The row's key. + /// @param stop Once a stop is requested, @p done is not called. + /// @param done Called once on the owner, never before this returns, with the row's view index, nothing when the + /// view has no row with @p key, or the error that kept the model from telling. + virtual void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) = 0; + + /// @brief Fetches rows by key, whether or not they are held, with the cells of the columns named: what a copy + /// of rows the model does not hold reads. Nothing is held or cached for them. + /// @param keys The rows' keys. + /// @param columns The column ids whose cells each row carries, in that order. + /// @return The rows the view has, each with its view index, in no particular order; a key the view lacks is + /// left out. Delivered on the owner. + virtual async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) = 0; + + /// @brief Sets the sort chain. + /// @param sort The keys, most significant first; empty is the table's own order. + /// @return The error that left the sort unchanged, or nothing. + virtual std::expected setSort(SortChain sort) = 0; + + /// @brief Sets the filter. + /// @param filter The filter; an empty one shows every row. + /// @return The error that left the filter unchanged, or nothing. + virtual std::expected setFilter(table::FilterSpec filter) = 0; + + /// @brief The distinct values of a column, or of a declared group's columns pooled, over the rows the other + /// filters leave: what a header's filter menu lists. + /// @param request The column or group, the search, the date bucket and the page of values. + /// @return The values, delivered on the owner; `Unavailable` when the rows cannot list values. + virtual async::Completion> distinctValues( + table::DistinctRequest request) = 0; + + /// @brief What the status line counts. + /// @return The counts. + [[nodiscard]] virtual TableCountsView counts() const = 0; + + /// @brief The view as a selection of it takes it: its filter, its retained rows and its revision. + /// @return The view, or why it cannot be selected yet; rows that select by keys alone refuse with nothing + /// undecided and no level. + [[nodiscard]] virtual std::expected selectView() const { + return std::unexpected(SelectAllRefusal{}); + } + + /// @brief How many rows a selection holds, as far as the rows know. + /// @param selection The selection. + /// @return The count; for keys, their number, exact. + [[nodiscard]] virtual SelectedCount selectedCount(TableSelection const& selection) const { + return SelectedCount{.rows = static_cast(selection.keys.size()), .kind = CountKind::Exact}; + } + + /// @brief Whether a reply has shown that the view has no row with a key: a key of a selection's `except` that + /// left the view is dropped from it. + /// @param key The key. + /// @return `true` once a reply that asked for the key left it out, until one holds it again. + [[nodiscard]] virtual bool leftView(table::RowId const& key) const; + + /// @brief Adds rows the view keeps although the filter rejects them: the rows an action of this session changed. + /// All of them are added, or, when they would take the set past `table::QueryLimits::maxRetained`, none. + /// A change of the filter clears them. + /// @param keys The rows' keys; a key retained already counts once. + /// @return `Retained`, or `OverBound` with the set unchanged. Rows that cannot retain keep nothing and answer + /// `Retained`. + [[nodiscard]] virtual RetainResult retain(std::span keys); + + /// @brief Drops every retained row: the view holds the rows the filter admits again. + virtual void clearRetained() {} + + /// @brief Whether a held row is retained and the filter rejects it. + /// @param key The row's key; a row's look has its key, not its view index. + /// @return `true` for a held row the latest reply that supplied it listed as unmatched; `false` for a key the + /// rows do not hold. + [[nodiscard]] virtual bool unmatched(table::RowId const& key) const; + + /// @brief Holds back the refetches the table's change events cause while an action of this session that changes + /// the table runs, so a row it changed is fetched with the retained rows its reply adds, never before. + /// The hold lasts while any run holds, for at most `SessionOptions::retainHold` from the first. + /// @param run The run's id. + virtual void holdRefetches(std::uint64_t run) { static_cast(run); } + + /// @brief Ends a run's hold: when no run holds any more, what the events marked is fetched, as one refetch. + /// @param run The run's id, as `holdRefetches` took it; one that holds nothing is ignored. + virtual void releaseRefetches(std::uint64_t run) { static_cast(run); } + + /// @brief Fetches a range of view rows with the cells of the columns named, whether or not they are held: what + /// a copy of a selection of the view reads. Nothing is held or cached for them. + /// @param first The first view row. + /// @param count The rows. + /// @param columns The column ids whose cells each row carries, in that order. + /// @return One row per view row of the range the view has, in view order, delivered on the owner; none from + /// rows that cannot read a range. + virtual async::Completion, table::TableError>> rowsOf( + std::int64_t first, std::int64_t count, std::span columns); + + /// @brief The view rows the model holds now, as `{first, count}` ranges in view order: what a lookup by key reads, + /// so it is bounded by what is held and not by the view. + /// @return The ranges; every view row for rows that hold them all. + [[nodiscard]] virtual std::vector> heldRanges() const { + return {{0, total().rows}}; + } + + /// @brief The rows an action of this session is working on, and those an action could not change. + /// @return The rows' states. + [[nodiscard]] virtual RowStates& states() = 0; + + /// @brief The rows an action of this session is working on, and those an action could not change. + /// @return The rows' states. + [[nodiscard]] virtual RowStates const& states() const = 0; + + /// @brief Moves what the rows hold by a row's key to its new key: its place among the retained rows and its + /// states, as `RowStates::move` moves them. An action that gave a row a new key names the old one in a + /// `table::ChangedRow::from`. + /// @param from The row's old key. + /// @param target The row's new key. + virtual void moveKey(table::RowId const& from, table::RowId const& target) = 0; + + /// @brief Sets the one receiver of the view's changes, called after the rows changed with the operations that + /// turn the old view into the new one. + /// + /// A single slot: a call replaces the handler, and the mount is what sets it. Anything else that needs the + /// changes wraps this `TableRows` in a forwarding decorator and hands the wrapper to the mount. + /// @param handler The receiver; empty to stop receiving. + virtual void onChange(std::function handler) = 0; +}; + +/// @brief Why a row is locked: its `rowLock` companion's text. +/// @param row The row. +/// @param description The table's description; a `rowLock` that is empty locks no row. +/// @return The companion's text when it is non-empty text, else nothing. +[[nodiscard]] MORPH_API std::optional lockText(TableRowRef const& row, + table::TableDescription const& description); + +/// @brief Whether a row takes no cell edit: an action of this session is working on it, or it is locked. +/// @param rows The rows. +/// @param index The row's view index. +/// @param description The table's description. +/// @return `true` for a busy or locked row; `false` for a row the rows do not hold. +[[nodiscard]] MORPH_API bool refusesEdit(TableRows const& rows, std::int64_t index, + table::TableDescription const& description); + +/// @brief A row's key and its record, owned. +struct RowRecord { + /// @brief The row's key. + table::RowId key; + /// @brief The row as a record keyed by column id. + Value row; +}; + +/// @brief What `EngineRows` reads a row's key and record through: its source's snapshot and a source row. +using RecordOf = std::function; + +namespace detail { + +/// @brief The site names a misuse of a table's rows is reported under, through the runtime's owner probe. +namespace site { +/// @brief A ForEach, Table or rows-source snapshot repeated a key; the later row is refused and the first one kept. +/// Declared here, and not beside the mount's other sites, because `mount.hpp` includes this header. +inline constexpr char const* kDuplicateKey = "morph::ui: duplicate ForEach key"; +} // namespace site + +/// @brief A `double` as the record holds it: the decimal its shortest fixed-notation text spells, or that text's +/// shortest form when it spells no decimal `parseDecimal` reads, so the value is never lost to `null`. +/// @param value The number. +/// @return A `Decimal`, or the `String` of `std::to_chars`'s shortest text (`"1e+308"`, `"inf"`). +[[nodiscard]] MORPH_API Value doubleValue(double value); + +/// @brief A `Date` cell's days since 1970-01-01 as `YYYY-MM-DD`. +/// @param days The days. +/// @return The date's text; the number's own text past the years 0 to 9999. +[[nodiscard]] MORPH_API Value dateValue(std::int64_t days); + +/// @brief A `DateTime` cell's seconds since the epoch as a timestamp. +/// @param seconds The seconds. +/// @return The timestamp; the number's own text when its milliseconds do not fit an `int64`. +[[nodiscard]] MORPH_API Value dateTimeValue(std::int64_t seconds); + +} // namespace detail + +/// @brief A cell as the document reads it. +/// +/// Empty and unloaded cells are `null`. An integer is an `Int`, a `Date` column's the `String` `YYYY-MM-DD` and a +/// `DateTime` column's a `Timestamp`. A `Rational` is a `Decimal` with its places. A `double` is the `Decimal` its +/// shortest fixed-notation text spells, or that text's shortest form as a `String` when it spells none +/// `table::parseDecimal` reads (non-finite, more than 18 fraction digits, beyond an `int64` numerator). Text is a +/// `String`, a flag a `Bool`, and a quantity the `Decimal` of its amount in the column's canonical unit. A measure is +/// a `Quantity` of its amount in its own unit, named by the unit's id in @p units; its amount alone, a `Decimal`, when +/// @p units is null or does not hold the unit. +/// @param cell The cell. +/// @param column The cell's column, whose kind decides how an integer reads. +/// @param units The registry a measure's unit number is named through; null for none. +/// @return The value. +[[nodiscard]] MORPH_API Value cellValue(table::Cell const& cell, table::ColumnInfo const& column, + table::UnitRegistry const* units = nullptr); + +/// @brief The status line's counts part, its numbers grouped with @p format's separator. +/// +/// Nothing while no total is known; `" so far, loading"` while rows are undecided; +/// `" of selected"` with a selection; `" or more"` under a lower bound; otherwise `"1 row"` or +/// `" rows"`. A lower bound's `` is followed by `" or more"` in the selection's text too. +/// @param counts The model's counts. +/// @param selected Rows selected. +/// @param format The formatting facts: their numbers' group separator. +/// @return The text. +[[nodiscard]] MORPH_API std::string countsText(TableCountsView const& counts, std::int64_t selected, + FormatContext const& format); + +// ── Over the engine ───────────────────────────────────────────────────────── + +/// @brief A table's rows over a `table::Engine`: every row is present. +/// +/// `visible` does nothing and `keysOf` completes at once; a change is the engine's `ViewChange`. A row's record is +/// built by `RecordOf` once per source row of the engine's `viewSnapshot()` and kept: dropped for the rows an +/// `Updated` change names, and whole after any other change of the source, when the engine's view first shows it. +/// The view's snapshot is matched to the change that made it by pointer, so a source's `snapshot()` must return the +/// same pointer until its rows change, as `VectorSource` does; with a source that returns a new one on every call, +/// every logged change is applied whenever the view's snapshot moves. +class MORPH_API EngineRows final : public TableRows, private table::ChangeListener { +public: + /// @brief Rows over a new engine. + /// @param source The rows. Must not be null. + /// @param recordOf What builds a row's key and record. + /// @param options How the engine runs. `owner` must not be null: `keysOf` delivers there. + /// @throws std::invalid_argument when @p source or `options.owner` is null. + EngineRows(std::shared_ptr source, RecordOf recordOf, table::EngineOptions options); + + EngineRows(EngineRows const&) = delete; + EngineRows& operator=(EngineRows const&) = delete; + EngineRows(EngineRows&&) = delete; + EngineRows& operator=(EngineRows&&) = delete; + + /// @brief Stops hearing the engine and the source. + ~EngineRows() override; + + /// @brief The engine. + /// @return It. + [[nodiscard]] table::Engine& engine() noexcept { return *_engine; } + + /// @brief Calls of `RecordOf` so far: the memo's measure. + /// @return The count. + [[nodiscard]] std::size_t recordsBuilt() const noexcept { return _built; } + + /// @brief Holds the rows back while a table's stored arrangement is read, or lets them through. + /// + /// While restoring, `total()` is the view's rows, not known, and `row` answers nothing, so a mount draws + /// placeholder rows in place of an order the stored state is about to change; the engine still runs. A change of + /// it tells the receiver of `onChange` that the whole view changed. + /// @param restoring Whether the rows are held back. + void setRestoring(bool restoring); + + /// @brief Whether the rows are held back (`setRestoring`). + /// @return Whether they are. + [[nodiscard]] bool restoring() const noexcept { return _restoring; } + + /// @brief Every row of the view, counted exactly; not known while restoring. + /// @return The total. + [[nodiscard]] TableTotal total() const override; + + /// @brief The row at a view index, built once and kept until it changes. + /// @param index The view index. + /// @return The row; nothing past the view, and nothing while restoring. + [[nodiscard]] std::optional row(std::int64_t index) const override; + + /// @brief The levels of the row's columns that hold an unloaded cell. + /// @param index The view index. + /// @return The levels, sorted; none failed, since a source's level has no failure of its own. + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override; + + /// @brief Does nothing: every row is present. + /// @param first Unused. + /// @param count Unused. + /// @param columns Unused. + void visible(std::int64_t first, std::int64_t count, std::span columns) override; + + /// @brief The keys of a range of view rows, at once. + /// @param first The first view row. + /// @param count The rows. + /// @return The keys, delivered on the engine's owner; `InvalidSpec` for a range outside the view. + async::Completion, table::TableError>> keysOf(std::int64_t first, + std::int64_t count) override; + + /// @brief The rows of keys in the engine's view, read from its snapshot at once. + /// @param keys The rows' keys. + /// @param columns The column ids whose cells each row carries; a column the engine lacks gives an empty cell. + /// @return The rows the view has, in the order of @p keys, delivered on the engine's owner. + async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) override; + + /// @brief The engine's view as a selection takes it. A table held whole selects all by keys, so the lowering + /// does not ask; the answer is the engine's filter and the digest of its view's keys. + /// @return The view; never refused, since every row is decided. + [[nodiscard]] std::expected selectView() const override; + + /// @brief How many rows a selection holds: every row is here, so the count is exact. + /// @param selection The selection. + /// @return The keys' number, or the view's rows less the keys of `except` in it. + [[nodiscard]] SelectedCount selectedCount(TableSelection const& selection) const override; + + /// @brief A range of view rows, read from the engine at once. + /// @param first The first view row. + /// @param count The rows. + /// @param columns The column ids whose cells each row carries. + /// @return The rows in view order, delivered on the engine's owner; the part of the range outside the view has + /// none. + async::Completion, table::TableError>> rowsOf( + std::int64_t first, std::int64_t count, std::span columns) override; + + /// @brief Finds the view index of the row with a key in the engine's view, as it is now. + /// @param key The row's key. + /// @param stop Once a stop is requested, @p done is not called. + /// @param done Called on the engine's owner with the row's view index, or nothing when the view lacks it. + void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) override; + + /// @brief Sets the engine's sort. + /// @param sort The keys. + /// @return The engine's error, or nothing. + std::expected setSort(SortChain sort) override { + return _engine->setSort(std::move(sort)); + } + + /// @brief Sets the engine's filter. + /// @param filter The filter. + /// @return The engine's error, or nothing. + std::expected setFilter(table::FilterSpec filter) override { + return _engine->setFilter(std::move(filter)); + } + + /// @brief The distinct values of a column, from the engine's rows, in a task on the owner: a change of the + /// source made before the call (a column put in use to be listed) is taken in first. + /// @param request The request. + /// @return The engine's answer, delivered on its owner. + async::Completion> distinctValues( + table::DistinctRequest request) override; + + /// @brief The engine's counts: its view, its source's rows, its undecided rows and whether it computes. + /// @return The counts. + [[nodiscard]] TableCountsView counts() const override; + + /// @brief Adds keys to the engine's retained rows, all or none. + /// @param keys The rows' keys. + /// @return `OverBound` when they would take the set past `table::QueryLimits::maxRetained`. + [[nodiscard]] RetainResult retain(std::span keys) override; + + /// @brief Drops the engine's retained rows. + void clearRetained() override; + + /// @brief Whether the engine's view row of a key is retained and rejected by the filter. + /// @param key The row's key. + /// @return `false` for a key not in the view. + [[nodiscard]] bool unmatched(table::RowId const& key) const override; + + /// @brief The rows an action of this session is working on, and those an action could not change. + /// @return The rows' states. + [[nodiscard]] RowStates& states() override { return _states; } + + /// @brief The rows an action of this session is working on, and those an action could not change. + /// @return The rows' states. + [[nodiscard]] RowStates const& states() const override { return _states; } + + /// @brief Moves a row's place among the engine's retained rows and its states to its new key. + /// @param from The row's old key. + /// @param target The row's new key. + void moveKey(table::RowId const& from, table::RowId const& target) override; + + /// @brief Sets the one receiver of the engine's view changes. + /// @param handler The receiver; empty to stop receiving. + void onChange(std::function handler) override { _onChange = std::move(handler); } + +private: + // One row's record and its unloaded levels, for one source row. + struct Entry { + RowRecord record; + std::vector levels; + }; + RowStates _states; + + // One change of the source: the snapshot it made, and the rows it touched or the whole source. + struct Logged { + std::shared_ptr snapshot; + bool whole = false; + std::vector rows; + }; + + [[nodiscard]] static std::shared_ptr checked(std::shared_ptr source, + table::EngineOptions const& options); + + void rowsChanged(table::RowChange const& change) override; + + // Brings the memo to the engine's view snapshot: every change up to the one that made it is applied. The + // changes after it are kept, since a record built now reads the view's snapshot, which they are not in yet. + void sync() const; + + [[nodiscard]] Entry const* entryAt(std::int64_t index) const; + + std::shared_ptr _source; + RecordOf _recordOf; + exec::IExecutor* _owner; + std::unique_ptr _engine; + std::function _onChange; + mutable std::unordered_map _memo; + mutable std::shared_ptr _memoSnapshot; + mutable std::deque _log; + mutable std::size_t _built = 0; + bool _restoring = false; + /// Last, so it is the first to go: no values list reaches a destroyed engine. + async::CallbackScope _scope; +}; + +// ── A document's rows as a source ─────────────────────────────────────────── + +/// @brief The expression language's text order: the default collator's fold, then the text itself. +/// +/// Texts that fold alike order by their own bytes, so the order is total and is the one the expression language's +/// `sort` gives text. A text is folded once for both its sort key and its `fold`: the engine asks for one and then +/// the other of the same text, and each thread keeps the last text it folded. Safe to call concurrently: +/// `cloneForTask` returns null. +class MORPH_API ValueRowsCollator final : public table::TextCollator { +public: + /// @brief The fold of @p text, a NUL, then @p text: case-folded order first, then the text's own bytes. + /// @param text UTF-8 text. + /// @return The collation key. + [[nodiscard]] std::string sortKey(std::string_view text) const override; + + /// @brief @p text folded as the default collator folds it, which filters match against. + /// @param text UTF-8 text. + /// @return The folded text. + [[nodiscard]] std::string fold(std::string_view text) const override { return folded(text); } + + /// @brief Texts folded so far, by `sortKey` and `fold` together. + /// @return The count. + [[nodiscard]] std::size_t folds() const noexcept { return _folds.load(std::memory_order_relaxed); } + +private: + // The fold of a text: the one this thread made last when it was of the same text, else a new one, counted. + [[nodiscard]] MORPH_PROCESS_UNIQUE std::string folded(std::string_view text) const; + + mutable std::atomic _folds{0}; +}; + +/// @brief One column of a `rows` table, as its source reads it. +struct ValueColumn { + /// @brief The column's id: the row field it reads when it has no `sortBy`. + std::string id; + /// @brief The column part's literal `kind`; empty to infer the kind from the cells. + std::optional kind; + /// @brief The column's `sortBy` evaluated in the row's scope, read tracked; empty reads the field `id`. + std::function sortBy; +}; + +/// @brief The hidden leading sort key of a grouped rows table: an `Integer` column of each row's run index. +/// +/// It begins with U+001F, a character no document name holds, so no column a document declares can share its id. +inline constexpr std::string_view kGroupRunColumn = + "\x1F" + "group"; + +namespace detail { + +/// @brief What one non-null value says a column's kind is. +enum class ValueVote : std::uint8_t { + None, ///< Nothing: a `null`, a list or a record that is not a measure. + Bool, ///< A `Bool` column. + Integer, ///< An `Integer` column. + Decimal, ///< A `Decimal` column. + Text, ///< A `Text` column. + DateTime, ///< A `DateTime` column. + Measure, ///< A `Measure` column. +}; + +/// @brief How many `ValueVote`s there are. +inline constexpr std::size_t kValueVotes = 7; + +/// @brief An amount and its unit's id, as a quantity or a `{num, den, unit}` record holds them. +struct MeasureParts { + /// @brief The amount. + math::Rational amount; + /// @brief The unit's id; points into the value read. + std::string const* unit = nullptr; +}; + +/// @brief The places a fraction with denominator @p den is written to exactly, or the most a decimal holds. +/// @param den The denominator, positive. +/// @return The places. +[[nodiscard]] MORPH_API std::uint32_t exactPlacesOf(std::int64_t den); + +/// @brief A quantity, or a record of exactly `num`, `den` and `unit` (integers and a text), read as a measure. +/// @param value The value. +/// @return Its amount and unit, or nothing for any other value. +[[nodiscard]] MORPH_API std::optional measureOf(Value const& value); + +/// @brief The kind a value votes its column. +/// @param value The value. +/// @return The vote; `None` for `null`, a list and a record that is not a measure. +[[nodiscard]] MORPH_API ValueVote voteOf(Value const& value); + +/// @brief The column kind a vote names. +/// @param vote A vote other than `None`. +/// @return The kind. +[[nodiscard]] constexpr table::ColumnKind kindOfVote(ValueVote vote) noexcept { + switch (vote) { + case ValueVote::Bool: + return table::ColumnKind::Bool; + case ValueVote::Integer: + return table::ColumnKind::Integer; + case ValueVote::Decimal: + return table::ColumnKind::Decimal; + case ValueVote::DateTime: + return table::ColumnKind::DateTime; + case ValueVote::Measure: + return table::ColumnKind::Measure; + case ValueVote::Text: + case ValueVote::None: + default: + return table::ColumnKind::Text; + } +} + +/// @brief A column's kind from its cells' votes. +/// +/// No vote is `Text`; votes all alike are their kind; integers and decimals together are `Decimal`, an integer being +/// an exact decimal. Any other mix takes the first non-null cell's kind, `Decimal` when that is an integer and a +/// decimal voted too. +/// @param counts The votes of each kind. +/// @param votes Each row's vote, in source order. +/// @return The kind. +[[nodiscard]] MORPH_API table::ColumnKind inferredKind(std::array const& counts, + std::span votes); + +/// @brief A cell of a column and whether it is not of the column's kind. +struct ConvertedCell { + /// @brief The cell. + table::Cell cell; + /// @brief The value is not of the column's kind: the cell sorts last. + bool invalid = false; +}; + +/// @brief @p value as a cell of a column of @p kind. +/// +/// `null` is an empty cell. A value not of the kind is invalid: an empty cell in a `Text` column, which reads any +/// other cell as text, and elsewhere a measure in no unit, which every other kind reads as invalid. A timestamp is +/// UTC seconds rounded down (a `Date`'s days, rounded down); an integer in a `Decimal` column is a decimal of 0 +/// places; under `Number` an integer or a decimal is the nearest `double`; a measure is its amount in its unit's +/// number in @p units, invalid when @p units is null or lacks the unit. +/// @param value The value. +/// @param kind The column's kind. +/// @param units The registry a measure's unit is found in; null for none. +/// @return The cell. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one conversion per column kind, kept together. +[[nodiscard]] MORPH_API ConvertedCell convertedCell(Value const& value, table::ColumnKind kind, + table::UnitRegistry const* units); + +/// @brief Whether two cells are the same, a decimal's places included. +/// @param left A cell. +/// @param right Another. +/// @return `true` when they hold the same value with the same places. +[[nodiscard]] MORPH_API bool sameCell(table::Cell const& left, table::Cell const& right); + +/// @brief Whether two row values are one object: a record or a list by its storage, any other value by equality. +/// @param left A value. +/// @param right Another. +/// @return `true` when nothing in @p right can differ from @p left. +[[nodiscard]] MORPH_API bool sameObject(Value const& left, Value const& right); + +/// @brief The rows of a `ValueRowsSource` at one moment: each row's value and key, and the cells of the columns in +/// use, shared with the source until it changes them. +class MORPH_API ValueRowsSnapshot final : public table::RowSnapshot { +public: + /// @brief A snapshot over shared storage. + /// @param rows Each row's value. + /// @param keys Each row's key. + /// @param columns Each column's cells; null for a column not in use, whose cells are empty. + ValueRowsSnapshot(std::shared_ptr const> rows, std::shared_ptr const> keys, + std::vector const>> columns) + : _rows{std::move(rows)}, _keys{std::move(keys)}, _columns{std::move(columns)} {} + + /// @brief The rows. + /// @return Their count. + [[nodiscard]] std::size_t rowCount() const override { return _keys->size(); } + + /// @brief A row's key. + /// @param row Row index. + /// @return The key. + [[nodiscard]] table::RowId rowId(std::size_t row) const override { return _keys->at(row); } + + /// @brief One cell. + /// @param row Row index. + /// @param column Column index. + /// @return The cell; empty for a column not in use. + [[nodiscard]] table::Cell cell(std::size_t row, std::size_t column) const override; + + /// @brief Hands rows `[first, last)` of @p column to @p sink in one run. + /// @param column Column index. + /// @param sink Receives the cells. + /// @param first First row. + /// @param last One past the last row. + void readColumn(std::size_t column, table::ColumnSink& sink, std::size_t first, std::size_t last) const override; + + /// @brief A row's value. + /// @param row Row index. + /// @return The value the row was given. + [[nodiscard]] Value const& row(std::size_t row) const { return _rows->at(row); } + +private: + std::shared_ptr const> _rows; + std::shared_ptr const> _keys; + std::vector const>> _columns; +}; + +} // namespace detail + +/// @brief A `table::DataSource` over a document's list of values: what a `rows` table sorts and filters through the +/// engine. +/// +/// A column holds cells only while it is in use (`use`, `unuse`); one no sort, filter or values list reads holds +/// none. A cell is the column's `sortBy` of the row, or the row's field of the column's id, converted to the +/// column's kind: a literal `kind`, or the kind its cells vote for (see `detail::inferredKind`). A `sortBy` is read in +/// a tracked computation per row: a change to what one row's reads notifies `Updated` for that row, and a change that +/// every row's reads is a `Reset`. +/// +/// `assign` matches the new list to the held one by key: a row whose value is the held object is kept unread, any +/// other has its in-use cells derived and compared with the held ones. It is `Updated` when a cell differs, and also +/// when only a field no column in use reads differs, so what the table shows of it is read again; its keys are the +/// same, so the engine repairs it in place. New keys are `Inserted`, missing keys `Removed`, and a list that both +/// adds and drops rows, or reorders them, is a `Reset`. So is a change of a column's kind, and of a grouped table's +/// runs. A later row with a key already seen is dropped and reported (`detail::site::kDuplicateKey`), once per +/// duplicate. +/// +/// Grouped, adjacent rows are one run while their `by` is the same element as the run's first row's +/// (`detail::sameElement`, the rule of the interpreter's `group` and of `runs`). A run whose heading record changed +/// while the runs kept their places is an `Updated` of its first source row. +/// +/// `snapshot()` returns one pointer until the rows or cells change. Every member is called on the runtime's owner. +class MORPH_API ValueRowsSource final : public table::DataSource { +public: + /// @brief A source of no rows over @p columns. + /// @param runtime The runtime each `sortBy` is tracked on and duplicates are reported to; must outlive the source. + /// @param columns The document's columns, each id once. + /// @param keyOf Reads a row's key. + /// @param units The registry `Quantity` cells' units are found in; null: none, and every quantity is invalid. + ValueRowsSource(reactive::Runtime& runtime, std::vector columns, + std::function keyOf, std::shared_ptr units = {}); + + ValueRowsSource(ValueRowsSource const&) = delete; + ValueRowsSource& operator=(ValueRowsSource const&) = delete; + ValueRowsSource(ValueRowsSource&&) = delete; + ValueRowsSource& operator=(ValueRowsSource&&) = delete; + /// @brief Ends every tracked `sortBy`. + ~ValueRowsSource() override = default; + + /// @brief The document's columns, then `kGroupRunColumn` while the table is grouped. + /// @return The columns. + [[nodiscard]] std::span columns() const override { return _infos; } + + /// @brief The column groups the document declares (a `rows` table's `groups`). + /// @return They, as `setGroups` gave them. + [[nodiscard]] std::span groups() const override { return _groups; } + + /// @brief Declares the column groups: a group filter or a values list names them by id. Set before an engine + /// reads the source. + /// @param groups The groups, each of 2 to 16 columns of the source. + void setGroups(std::vector groups) { _groups = std::move(groups); } + + /// @brief The rows and the cells of the columns in use. + /// @return The same pointer until they change. + [[nodiscard]] std::shared_ptr snapshot() const override; + + /// @brief Registers @p listener. + /// @param listener The listener. + void subscribe(table::ChangeListener& listener) override { _listeners.add(listener); } + + /// @brief Removes @p listener; safe from inside a notification. + /// @param listener The listener. + void unsubscribe(table::ChangeListener& listener) override { _listeners.remove(listener); } + + /// @brief Takes a new list: matched to the held rows by key, then by the cells of the columns in use. + /// @param rows The rows, in source order. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one diff whose steps share their working vectors. + void assign(ValueList rows); + + /// @brief Groups the rows by the `group` part's `by`, read per row, and adds the hidden column + /// `kGroupRunColumn`; notifies `Reset`. + /// + /// `by` is read untracked: what it reads besides the row regroups the rows when `setGroup` or `assign` is called + /// again. + /// @param groupBy The `by`; empty: no groups, and the hidden column goes. + /// @param units The unit table two quantities of a run's `by` are compared through: the screen's, so 1 kg and + /// 1000 g are one run. + void setGroup(std::function groupBy, UnitTable units); + + /// @brief The run a source row belongs to: its index among the runs of adjacent rows whose `by` is the same + /// element as their run's first row's, in source order. + /// @param sourceRow The row. + /// @return The run's index; 0 when the table is not grouped or the row is past the rows. + [[nodiscard]] std::size_t runOf(std::size_t sourceRow) const; + + /// @brief Each run's heading record `{key, count, first, last, items}`, with its heading key in + /// `detail::kGroupHeadingField`, by run index, as `TableView::runs` holds them. + /// @return The records; none when the table is not grouped. + [[nodiscard]] std::span runRecords() const noexcept { return _runRecords; } + + /// @brief A sort, a filter or a values list began to read @p column: its cells are derived when this is its + /// first use, and a `Reset` is notified so the engine reads them. + /// @param column The column's id; one the source does not have is ignored. + void use(std::string_view column); + + /// @brief A use of @p column ended; at its last, its cells and tracked `sortBy`s go. Nothing is notified. + /// @param column The column's id; one not in use is ignored. + void unuse(std::string_view column); + + /// @brief What `EngineRows` reads a row's key and record through: the snapshot's key and the row's value. + /// @return The reader; it holds nothing of the source. + [[nodiscard]] static RecordOf recordOf(); + + /// @brief Cells held: one per row of each column in use, and of the run column while grouped. + /// @return The count. + [[nodiscard]] std::size_t cellsHeld() const noexcept; + + /// @brief Cells derived so far: a row's field read, or its `sortBy` run, for a column in use. + /// @return The count. + [[nodiscard]] std::size_t cellsDerived() const noexcept { return _derived; } + + /// @brief Cells of @p column, a column in use, that are not of its kind. + /// @param column The column's id. + /// @return The count; 0 for a column not in use. + [[nodiscard]] std::size_t invalidCells(std::string_view column) const; + +private: + // A `sortBy` cell: the row it reads, the value it read last and the tracked computation that reads it. + struct Tracker { + std::size_t column = 0; + std::size_t row = 0; + Value input; + Value value; + bool live = false; + std::unique_ptr effect; + }; + + // A column's cells while it is in use, each row's vote and whether its cell is invalid. + struct Held { + std::size_t uses = 0; + std::shared_ptr> cells; + std::vector votes; + std::vector invalid; + std::array counts{}; + std::vector> trackers; + }; + + // What tracked `sortBy`s changed since the last notification. + struct Pending { + std::vector rows; + std::set rerun; + bool reset = false; + [[nodiscard]] bool any() const noexcept { return reset || !rows.empty(); } + }; + + [[nodiscard]] std::optional columnOf(std::string_view columnId) const; + + void notify(table::RowChange const& change) { _listeners.notify(change); } + + // The `group`'s `by` of a row, read untracked: a change of the list is what regroups it. + [[nodiscard]] Value readBy(Value const& row) const { + return _runtime->untracked([&] { return _group(row); }); + } + + // A field column's value for a row. + [[nodiscard]] Value fieldOf(std::size_t column, Value const& row) const; + + // The value a column's cell of a row converts: the tracked `sortBy`'s last, or the row's field. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): column index, then row index, in every call here. + [[nodiscard]] Value valueOf(std::size_t column, std::size_t row, Value const& input) const; + + // A new tracked `sortBy` for a row: its first run derives the value. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): column index, then row index, in every call here. + std::unique_ptr track(std::size_t column, std::size_t row, Value const& input); + + // A tracked `sortBy`'s run: the first stores the value, a later one updates the row's cell. + void rerun(Tracker& tracker); + + // One notification for the tracked `sortBy`s that ran: `Reset` when every row's ran or a kind changed. + void flushTracked(); + + // Changes one row's vote and returns the column's kind after it. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): column index, then row index, in every call here. + table::ColumnKind vote(Held& held, std::size_t column, std::size_t row, detail::ValueVote next); + + [[nodiscard]] table::ColumnKind kindOf(std::size_t column, Held const& held) const; + + // The column's cells, copied first when a snapshot still shares them. + static std::vector& writable(Held& held); + + // Every cell of a column converted again for its kind, from the values held. + void reconvert(std::size_t column); + + // A column's first use: every row's cell derived. + void rebuild(std::size_t column); + + // A held column over a new list: kept rows keep their cells, others are derived and compared. Marks the rows + // whose cell changed in @p updated; returns whether the column's kind changed. + bool reassign(std::size_t column, std::vector const& rows, std::vector const& was, + std::vector const& same, std::vector& updated); + + // Each row's run, each run's first row and each run's heading record, from the `by` values held. A run's key is + // its first row's `by`, as the interpreter keys it. + void buildRuns(std::vector const& rows); + + reactive::Runtime* _runtime; + std::vector _columns; + std::function _keyOf; + std::shared_ptr _units; + std::vector _infos; + std::vector _groups; + std::vector _held; + std::shared_ptr const> _rows = std::make_shared const>(); + std::shared_ptr const> _keys = std::make_shared const>(); + std::unordered_map _index; + std::function _group; + std::vector _byValues; + UnitTable _groupUnits; + std::vector _runs; + std::vector _runFirst; + std::vector _runRecords; + std::shared_ptr> _runCells; + Pending _pending; + bool _posted = false; + std::size_t _derived = 0; + mutable std::shared_ptr _snapshot; + table::detail::Listeners _listeners; + // Last, so it is the first to go: no posted notification reaches a half-destroyed source. + async::CallbackScope _alive; +}; + +// ── A typed list action's pages ───────────────────────────────────────────── + +namespace detail { + +/// @brief A typed list action's reply as read before its rows are cells: `Page`'s members, each row a JSON DOM. +using TypedPageDom = table::Page; + +/// @brief What one JSON member says its column's kind is. +enum class JsonVote : std::uint8_t { + None, ///< Nothing: `null`, an array, or an object that is neither a decimal nor a measure. + Bool, ///< `true` or `false`: a `Bool` column. + Integer, ///< An integer: an `Integer` column. + Number, ///< A number with a fraction or an exponent: a `Number` column. + Decimal, ///< `{num, den, dp}`: a `Decimal` column. + Measure, ///< `{num, den, dp, unit}`: a `Measure` column. + Text, ///< A string: a `Text` column. +}; + +/// @brief How many `JsonVote`s there are. +inline constexpr std::size_t kJsonVotes = 7; + +/// @brief A JSON integer as an `int64`. +/// @param member The member. +/// @return Its value, or nothing when it is not an integer or does not fit. +[[nodiscard]] MORPH_API std::optional jsonInteger(glz::generic_u64 const& member); + +/// @brief An exact amount written `{num, den, dp}`, with a `unit` or without. +struct JsonDecimal { + /// @brief The amount, its places kept. + math::Rational amount; + /// @brief The unit's id; null when the object names none. + std::string const* unit = nullptr; +}; + +/// @brief An object of exactly `num`, `den` and `dp` (integers, `den` not 0, `dp` 0 to 18), and optionally a `unit` +/// string, read as an exact amount. +/// @param member The member. +/// @return The amount and its unit, or nothing for any other member. +[[nodiscard]] MORPH_API std::optional jsonDecimal(glz::generic_u64 const& member); + +/// @brief The kind a member votes its column. +/// @param member The member. +/// @return The vote; `None` for `null`, an array and any object that is not a decimal or a measure. +[[nodiscard]] MORPH_API JsonVote jsonVoteOf(glz::generic_u64 const& member); + +/// @brief The column kind a vote names. +/// @param vote A vote other than `None`. +/// @return The kind. +[[nodiscard]] constexpr table::ColumnKind kindOfJsonVote(JsonVote vote) noexcept { + switch (vote) { + case JsonVote::Bool: + return table::ColumnKind::Bool; + case JsonVote::Integer: + return table::ColumnKind::Integer; + case JsonVote::Number: + return table::ColumnKind::Number; + case JsonVote::Decimal: + return table::ColumnKind::Decimal; + case JsonVote::Measure: + return table::ColumnKind::Measure; + case JsonVote::Text: + case JsonVote::None: + default: + return table::ColumnKind::Text; + } +} + +/// @brief A column's kind from the members its rows hold under its id. +/// +/// No vote is `Text`; votes all alike are their kind; integers and decimals alone are `Decimal`; integers with +/// fractional numbers, decimals or not, are `Number`; any other mix is the first non-null member's kind. +/// @param rows The rows. +/// @param column The column's id. +/// @return The kind. +[[nodiscard]] MORPH_API table::ColumnKind inferredJsonKind(std::span rows, + std::string_view column); + +/// @brief A member as a cell of a column of @p kind. +/// +/// `null` is an empty cell. An integer is an `int64` (beyond its range a `double`), a `Rational` of 0 places under +/// `Decimal` and a `double` under `Number`; a fractional number a `double`; a string its text, under `Date` its days +/// when it is `YYYY-MM-DD` and under `DateTime` its seconds rounded down when it is ISO-8601; `{num, den, dp}` its +/// `Rational`; with a `unit` under `Measure` a measure in @p units' number for the unit (`kUnknownUnit`, invalid, when +/// @p units lacks it). Anything else is the member's JSON text, which only a `Text` column reads as valid. +/// @param member The member. +/// @param kind The column's kind. +/// @param units The registry a measure's unit is found in; null finds none. +/// @param named The unit ids of the page's measures, by number: what a measure found adds to. +/// @return The cell. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per column kind. +[[nodiscard]] MORPH_API table::Cell typedCell(glz::generic_u64 const& member, table::ColumnKind kind, + table::UnitRegistry const* units, + std::map& named); + +/// @brief A key member read as a row's id: an integer, or a string. +/// @param member The member. +/// @return The id, or nothing for any other member. +[[nodiscard]] MORPH_API std::optional typedKey(glz::generic_u64 const& member); + +/// @brief A typed list action's reply, read as a DOM, as a generic page over @p description's columns. +/// @param dom The reply. +/// @param description The description: its columns, their kinds and its key. +/// @param units The registry a measure's unit is found in; null resolves through `registryOf(description)`, +/// built only when a column is `Measure`. +/// @return The page, or `InvalidValue` when a row is not an object or has no key, or `unloadedRows` or `indices` do +/// not fit the rows, or what `registryOf` refuses. +[[nodiscard]] MORPH_API std::expected typedPageOf( + TypedPageDom const& dom, table::TableDescription const& description, table::UnitRegistry const* units); + +/// @brief The most units a window lists for the members of its replies that no description lists. Each is a +/// dimension of its own that the description and its registry keep for the window's life, and one more +/// is added per unit a reply names; a reply naming more is not describing quantities, and its further +/// units stay unknown, their cells invalid. +inline constexpr std::size_t kMaxUnlistedUnits = 64; + +/// @brief The units the `Measure` columns' members of @p rows name that @p units does not have, each its own +/// canonical unit in a dimension named by its id, in the order first met. +/// @param rows The rows. +/// @param description The description: its `Measure` columns. +/// @param units The registry the description's units are in; null has none. +/// @param room How many more units may be listed: the rest stay unknown. +/// @return The units to list, at most @p room. +[[nodiscard]] MORPH_API std::vector unlistedUnits(std::span rows, + table::TableDescription const& description, + table::UnitRegistry const* units, std::size_t room); + +/// @brief Reads a typed list action's reply text as a DOM. +/// @param json The reply. +/// @return The DOM, or `InvalidValue` when the text is not a page. +[[nodiscard]] MORPH_API std::expected typedPageDom(std::string_view json); + +} // namespace detail + +/// @brief A typed list action's reply (`Page`'s JSON: `rows`, `total`, `totalKind`, `offset`, `indices`) as a +/// generic page over @p description's columns: each row object's member of a column's id read by its kind. +/// +/// The text is read as a `glz::generic_u64` DOM, so an `int64` keeps every digit. A member absent or `null` is an +/// empty cell; an integer an `int64` (a `Rational` of 0 places under `Decimal`, a `double` under `Number`); a number +/// with a fraction a `double`; a string its text, under `Date` `YYYY-MM-DD` its days and under `DateTime` ISO-8601 +/// its seconds rounded down; `true` and `false` a `bool`; `{num, den, dp}` its `Rational`, and with a `unit` under +/// `Measure` a measure through @p units, invalid when the unit is not there. Anything else is the member's JSON +/// text, invalid outside `Text`. A row's key is its member named by the description's `key`. The page's `columns` +/// are every description column, whatever the query named, and its `revision` is empty. +/// @param json The reply's text. +/// @param description The description: the columns, their kinds and the key. +/// @param units The registry a measure's unit is found in; null resolves through `registryOf(description)`, +/// built only when a column is `Measure`. +/// @return The page, or `InvalidValue` when the text is not a page, a row is not an object or has no key, or +/// `unloadedRows` or `indices` do not fit the rows, or what `registryOf` refuses. +[[nodiscard]] MORPH_API std::expected readTypedPage( + std::string_view json, table::TableDescription const& description, table::UnitRegistry const* units = nullptr); + +// ── Over a server's pages ─────────────────────────────────────────────────── + +/// @brief How a `WindowRows` reaches its table. +struct WindowRowsOptions { + /// @brief The model's channel. + std::shared_ptr channel; + /// @brief The table's id: its actions are `Table.` and `Table..describe`. Empty with `action`. + std::string table; + /// @brief A typed list action's id, sent in place of `Table.`: its reply is a `Page`, read with + /// `readTypedPage`. Empty for a model's table. + std::string action; + /// @brief With `action`: the request member the query is written into, the one its schema marks `x-table`. + std::string queryMember; + /// @brief With `action`: the columns whose kind the first reply with rows decides, by the members of their id + /// (`detail::inferredJsonKind`). Their kind in the description is a placeholder until then, and stays + /// what that reply made it for the rows' life. + std::vector inferKinds; + /// @brief The records watched for the window's life: a model's table its `.`, a typed list + /// action each record its catalog entry names. None: a reconnect or `resync` of the session drops the + /// pages, as a record watch's change of every row does. + std::vector records; + /// @brief The node's `body`: the query's fixed part. A `query` record in it gives the query's other members. + Value body; + /// @brief Rows per page. + std::int64_t pageSize = 200; + /// @brief Pages held at most. + std::size_t maxPages = 8; + /// @brief Keys one keyed fetch asks for at most. + std::size_t maxKeys = 1000; + /// @brief Columns a page holds at most. + std::size_t maxColumns = 96; + /// @brief Sends no query until `release`, so a stored sort and filter can be applied first. + bool restoring = false; +}; + +/// @brief What a `WindowRows` has done, for tests and the inspector. +struct WindowRowsStats { + /// @brief Page and column fetches sent. + std::size_t pageFetches = 0; + /// @brief Keyed fetches sent. + std::size_t rowsFetches = 0; + /// @brief Fetches cancelled because the visible rows left their pages. + std::size_t cancelled = 0; + /// @brief Cells turned into a row record's fields. + std::size_t cellsConverted = 0; + /// @brief Distinct-values queries sent. + std::size_t distinctFetches = 0; +}; + +/// @brief A table's rows over a server's pages: a `table::PageWindow` of generic rows, the table's description +/// and the session. +/// +/// It watches the table's records first and sends no page fetch until every watch is answered, a description is +/// set and, when restoring, `release` is called. Every fetch goes through `Session::read` as `Table.`, makes +/// no cache entry and is cancelled through its own stop token; its reply's text is read with +/// `table::readGenericPage` against the held description. +/// +/// Over a typed list action (`WindowRowsOptions::action`) every fetch is that action, its body the node's body with +/// the query in `queryMember`, and its reply is read with `readTypedPage`. The reply holds whole rows, so `visible`'s +/// columns name what a row's record converts and not what is fetched. The columns of `inferKinds` take their kinds +/// from the first reply that has rows and reads, read once as a DOM for both the kinds and the page. A unit a +/// `Measure` member names that the description does not list is added to it as its own canonical unit, so its cell +/// is a measure in that unit and not an invalid one. A window that watches no record drops its pages on the +/// session's reconnect and `resync`. +/// +/// Timing. A fetch for a page held, or next to a page held, goes at once, and so does the first page while none is +/// held; any other waits until the first visible row has stayed in one page for `SessionOptions::tableSettle`. +/// Every fetch the window no longer covers is cancelled. While the order waits for a level every change event +/// invalidates, and a refetch of a held page goes no sooner than `SessionOptions::tableAwaitedRefetch` after the last +/// one: the first after a quiet spell goes at once, and the events between two refetches are one. +/// +/// A row's record holds one field per column of the latest `visible` call that the window holds for the row, +/// converted by `cellValue` when the row is first read and kept by key until the row's page is fetched again. +/// +/// A change is the diff, by key, of the rows held before a reply against the rows held after it: a new total moves +/// the view's end (`Inserted` or `Removed` there), a row that moved within its page is `Moved`, a row that came or +/// went is `Inserted` or `Removed`, and a place whose cells arrived, were replaced or were evicted is `Changed`. +/// Each operation is valid on the list the one before it leaves, and no key is held twice between two of them. A new +/// query (a sort, a filter or a description revision) is a `Reset`, and so is a reply whose page holds a key twice, +/// which no diff by key can place, or whose page diff would take more than 5,000 operations, the bound of the +/// `ViewChange` contract. +/// +/// A values list (`distinctValues`) is a query carrying `distinct` under the held filter. The window keeps each reply +/// by the query's body until the table's record changes, the session reconnects or a new revision is described, so +/// a filter menu opened again sends nothing; it keeps at most 64, the oldest going first, and a reply asked for +/// before such a change answers its menu without being kept. The replies are this table's rows' own, not shared with +/// another table. +/// +/// Neither copied nor moved: its watch handler and its replies hold it. +class MORPH_API WindowRows final : public TableRows { +public: + /// @brief Rows of a table, watching its record from now. + /// @param session The session; must outlive the rows. + /// @param options The channel, the table and the window's bounds. + WindowRows(Session& session, WindowRowsOptions options); + + WindowRows(WindowRows const&) = delete; + WindowRows& operator=(WindowRows const&) = delete; + WindowRows(WindowRows&&) = delete; + WindowRows& operator=(WindowRows&&) = delete; + + /// @brief Cancels every fetch in flight. + // NOLINTNEXTLINE(bugprone-exception-escape): only allocation can throw, and that ends the process either way. + ~WindowRows() override; + + /// @brief Takes the table's description: fits the sort, the filters and the visible columns to it, and starts + /// a new query when it is another revision than the one held. + /// @param description The description, its revision set. + void setDescription(table::TableDescription description); + + /// @brief Takes the description as the `Table..describe` query holds it. + /// + /// A description's numbers are integers or exact decimals, which a `Value` holds without loss, so it is read + /// back from the value's canonical JSON. One that does not read sets `error()` to `InvalidValue` and stops + /// every page fetch until a description that reads is set. + /// @param described The query's value. + void setDescription(Value const& described); + + /// @brief The description held. + /// @return It, or null before the first. + [[nodiscard]] table::TableDescription const* description() const noexcept { + return _description ? &*_description : nullptr; + } + + /// @brief Sets what hears a reply that names another revision than the description held, once per revision. + /// The reply is still taken. + /// @param handler The receiver; empty to stop receiving. + void onStaleDescription(std::function handler) { _onStale = std::move(handler); } + + /// @brief Sets what hears the rows a keyed fetch named and its reply holds none of: a change event's refetch of a + /// row that was deleted or no longer matches the filter. Called once per such reply, after the rows took + /// it, with those keys; a reply that holds every key it named is not reported. + /// @param handler The receiver; empty to stop receiving. + void onRowsAbsent(std::function)> handler) { + _onRowsAbsent = std::move(handler); + } + + /// @brief Sets what hears that `error()` or `counts()` may have changed: a fetch was sent, answered or failed, + /// or a reply or a description did not read. A failed fetch changes no row, so the view's `onChange` says + /// nothing of it; this is how a status line learns of it. Called after the rows took the event. + /// @param handler The receiver; empty to stop receiving. + void onStatus(std::function handler) { _onStatus = std::move(handler); } + + /// @brief The query's filter. + /// @return It. + [[nodiscard]] table::FilterSpec const& filter() const noexcept { return _filter; } + + /// @brief Whether the kinds of `WindowRowsOptions::inferKinds` still wait for the first reply with rows: until + /// then those columns hold a `Text` placeholder, which a filter must not be compiled against. + /// @return `true` while they wait. + [[nodiscard]] bool inferring() const noexcept { return _inferring; } + + /// @brief Sets what hears that the first reply with rows fixed the kinds of `inferKinds`, once. Called while + /// that reply is being read, so the receiver posts what it does to the rows. + /// @param handler The receiver; empty to stop receiving. + void onInferred(std::function handler) { _onInferred = std::move(handler); } + + /// @brief Leaves the restoring state: the first query goes, with the sort and filter set meanwhile. + void release(); + + /// @brief Fetches the visible pages again with `TableQuery::retry`, so failed level loads are tried at once. + /// Every fetch of that refetch carries the flag, one the timing rules hold back included. + void retry(); + + /// @brief The last error: a fetch that failed, a reply or a description that did not read. Cleared by the next + /// page taken. + /// @return The error, or nothing. + [[nodiscard]] std::optional const& error() const noexcept { return _error; } + + /// @brief What the rows have done. + /// @return The counters. + [[nodiscard]] WindowRowsStats const& stats() const noexcept { return _stats; } + + /// @brief The view's rows, as the latest page reply said. + /// @return The total; not known before a reply. + [[nodiscard]] TableTotal total() const override; + + /// @brief The held row at a view index, as a record of the columns the latest `visible` named. + /// @param index The view index. + /// @return The row, or nothing while it is not held. + [[nodiscard]] std::optional row(std::int64_t index) const override; + + /// @brief The view rows the window holds, as whole pages: what a reader of every held row walks instead of the + /// view. A page's last rows may lie past the view's end, where `row` answers nothing. + /// @return Each held page's first view row and its rows, ascending. + [[nodiscard]] std::vector> heldRanges() const override; + + /// @brief The held row's unloaded levels. + /// @param index The view index. + /// @return The window's view of them. + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override { + return _window.unloadedLevels(index); + } + + /// @brief Declares the visible rows and the columns their records hold, and sends what is due. + /// @param first The first visible view row. + /// @param count The rows. + /// @param columns The column ids; empty means every column. An id the description lacks is dropped. + void visible(std::int64_t first, std::int64_t count, std::span columns) override; + + /// @brief The keys of a range of view rows, for a range selection: the rows held give theirs, and every page of + /// the range with a row not held is fetched naming no columns, so its reply carries keys alone. The pages + /// so fetched are not held. + /// @param first The first view row. + /// @param count The rows. + /// @return The keys once every page has answered; `InvalidSpec` for a negative range, `Unavailable` when a page + /// failed or a row of the range is in none. + async::Completion, table::TableError>> keysOf(std::int64_t first, + std::int64_t count) override; + + /// @brief Finds the view index of the row with a key: a keyed fetch naming no columns, under the current sort and + /// filters. + /// @param key The row's key. + /// @param stop Stops the fetch; once a stop is requested, @p done is not called. + /// @param done Called on the owner with the row's view index, nothing when the reply has no row, or the error the + /// fetch failed with; `Unavailable` while no description is held, and `InvalidValue` when the reply holds + /// the row without its index. + void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) override; + + /// @brief Fetches rows by key: keyed queries under the current sort and filters naming @p columns, at most + /// `WindowRowsOptions::maxKeys` keys each, through the session's read, which makes no cache entry. The + /// replies are not held. + /// @param keys The rows' keys. + /// @param columns The column ids whose cells each row carries. + /// @return The rows the replies hold, with their view indices; a key no reply holds is left out. A cell of a + /// level the reply names the row as lacking is `table::Unloaded`. `Unavailable` while no description is + /// held or when a fetch failed, and `InvalidValue` for a reply that gives a row no index. + async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) override; + + /// @brief Finds a row's view index, as `locateRow` does, stopping the fetch an earlier call still has in flight, + /// whose handler is then never called. + /// @param key The row's key. + /// @param done Called with the row's view index, or nothing when the view has no row with @p key or the fetch + /// failed. + void locate(table::RowId key, std::function)> done); + + /// @brief Stops a `locate` fetch in flight; its handler is never called. + void stopLocating(); + + /// @brief Sets the query's sort: a new query. + /// @param sort The keys. + /// @return `UnknownColumn`, `InvalidSpec` for a column that is not sortable or named twice, or `LimitExceeded` + /// past the table's sort bound, checked against the description held; the sort is then unchanged. + std::expected setSort(SortChain sort) override; + + /// @brief Sets the query's filter: a new query. + /// @param filter The filter. + /// @return The error compiling it against the description held; the filter is then unchanged. + std::expected setFilter(table::FilterSpec filter) override; + + /// @brief The distinct values of a column: a query carrying `distinct` under the held filter. Its reply is kept + /// by the query's body until the table's record changes, so a menu opened again sends nothing. + /// @param request The request. + /// @return The values, delivered on the owner; `Unavailable` without a description, for a table whose + /// description says it lists no values, and over a typed list action, whose reply holds rows alone. + async::Completion> distinctValues( + table::DistinctRequest request) override; + + /// @brief The window's counts: its total, undecided rows, awaited and failed levels, and whether a fetch is in + /// flight. The rows before the filter are not known. + /// @return The counts. + [[nodiscard]] TableCountsView counts() const override; + + /// @brief The rows an action of this session is working on, and those an action could not change. + /// @return The rows' states. + [[nodiscard]] RowStates& states() override { return _states; } + + /// @brief The rows an action of this session is working on, and those an action could not change. + /// @return The rows' states. + [[nodiscard]] RowStates const& states() const override { return _states; } + + /// @brief Moves a row's place among the retained rows and its states to its new key. Nothing is fetched: the + /// change event of the action names both keys. + /// @param from The row's old key. + /// @param target The row's new key. + void moveKey(table::RowId const& from, table::RowId const& target) override; + + /// @brief Adds keys to the retained rows, all or none; each query from then on carries the set in `retain`. + /// + /// The keys added are refetched as a change event's keys are, so the rows that left the filter come back into + /// the view; while a run holds the refetches, they are marked with the events'. + /// @param keys The rows' keys. + /// @return `OverBound` when they would take the set past `table::QueryLimits::maxRetained`; the set is then + /// unchanged. + [[nodiscard]] RetainResult retain(std::span keys) override; + + /// @brief Drops every retained row, and fetches the held pages again without them. + void clearRetained() override; + + /// @brief The retained rows, in the order they were added. + /// @return Their keys. + [[nodiscard]] std::span retained() const noexcept { return _retained; } + + /// @brief Whether a held row is retained and the filter rejects it. + /// @param key The row's key. + /// @return `true` for a held row the latest reply that supplied it listed in `unmatched`. + [[nodiscard]] bool unmatched(table::RowId const& key) const override { return _unmatchedHeld.contains(key); } + + /// @brief Holds back the refetches change events cause, while @p run runs, for at most + /// `SessionOptions::retainHold` from the first run held; an event meanwhile only marks what it would fetch. + /// Without a scheduler nothing is held. + /// @param run The run's id. + void holdRefetches(std::uint64_t run) override; + + /// @brief Ends @p run's hold; when no run holds any more, what the events marked goes as one refetch. + /// @param run The run's id. + void releaseRefetches(std::uint64_t run) override; + + /// @brief The view as a selection takes it: the held filter and the latest reply's revision. + /// + /// Refused while the view's membership is open: rows are undecided, or an awaited level is one a filtered + /// column needs. A level only the sort needs refuses nothing, since order is not membership. Refused too, with + /// nothing undecided and no level, until a reply to the current filter has named its revision. + /// @return The view, or the refusal with the undecided rows and the filtered columns' awaited levels. + [[nodiscard]] std::expected selectView() const override; + + /// @brief How many rows a selection holds, as far as the window knows. + /// + /// A selection of the view holds the view's total less each key of `except` the window holds; a key owed a + /// refetch still subtracts. The count is exact when the total is, and every key of `except` is held and owed + /// nothing, or known to have left the view. + /// @param selection The selection. + /// @return The count. + [[nodiscard]] SelectedCount selectedCount(TableSelection const& selection) const override; + + /// @brief Whether a keyed reply left a key out of the view since the filter was set. + /// @param key The key. + /// @return `true` until a reply holds the key again. + [[nodiscard]] bool leftView(table::RowId const& key) const override { return _outOfView.contains(key); } + + /// @brief Fetches a range of view rows as page queries of `pageSize` rows naming @p columns, under the held sort + /// and filter, whether or not the window holds them. + /// @param first The first view row. + /// @param count The rows. + /// @param columns The column ids whose cells each row carries. + /// @return The rows of the range, delivered on the owner; `Unavailable` without a description. + async::Completion, table::TableError>> rowsOf( + std::int64_t first, std::int64_t count, std::span columns) override; + + /// @brief Sets the one receiver of the rows' changes. + /// @param handler The receiver; empty to stop receiving. + void onChange(std::function handler) override { _onChange = std::move(handler); } + +private: + friend struct testing::WindowRowsProbe; + + // A row's record, kept by key until its page is fetched again or the columns named change. + struct Entry { + table::RowId key; + Value record; + std::uint64_t stamp = 0; + }; + + // More operations than this in one page's diff are one `Reset`, as for the engine's default. + static constexpr std::size_t kResetThreshold = 5000; + + struct PageFlight { + table::PageFetch fetch; + ::core::async::StopSource stop; + // The retained set the query carried, by `_retainStamp`. + std::uint64_t retained = 0; + }; + + // A range's keys in the making: the pages fetched for it, by page, and how many it still waits for. + struct KeysRequest { + async::Completion, table::TableError>>::Promise promise; + std::int64_t first = 0; + std::int64_t count = 0; + std::map> pages; + std::size_t waiting = 0; + std::optional failed; + std::vector<::core::async::StopSource> stops; + }; + + void keysAnswered(KeysRequest& request, std::int64_t page, + std::expected, table::TableError> keys); + + // The range's keys: a fetched page's where one was fetched, the window's otherwise. + void finishKeys(KeysRequest& request); + + // A `fetchRows` in the making: the rows its replies held so far, and how many replies it still waits for. + struct RowsRequest { + async::Completion, table::TableError>>::Promise promise; + std::vector rows; + std::size_t waiting = 0; + std::optional failed; + std::vector<::core::async::StopSource> stops; + }; + + static void rowsAnswered(RowsRequest& request, std::expected, table::TableError> rows); + + static void finishRows(RowsRequest& request); + + // A keyed reply's rows, each with the cells of @p columns in that order; a cell of a level the reply names its + // row as lacking is unloaded, as it is `null` on the wire. + [[nodiscard]] std::expected, table::TableError> fetchedOf( + table::GenericPage& page, std::vector const& columns) const; + + struct RowsFlight { + table::RowsFetch fetch; + ::core::async::StopSource stop; + // The retained set the query carried, by `_retainStamp`. + std::uint64_t retained = 0; + }; + + [[nodiscard]] std::chrono::milliseconds now() const; + + [[nodiscard]] bool ready() const noexcept { + return _watched && _description.has_value() && !_descriptionError && !_restoring && _hasVisible; + } + + [[nodiscard]] std::optional sortError(SortChain const& sort) const; + + // A new query: the window drops every page, every fetch in flight is stopped, and the view is reset. + void restart(); + + void stopAll(); + + [[nodiscard]] bool heldPage(std::int64_t page) const; + + // Whether a fetch goes now rather than when the visible rows settle. + [[nodiscard]] bool due(table::PageFetch const& fetch, std::chrono::milliseconds instant) const; + + // Whether a refetch of a held page waits: the order awaits a level and the last refetch was too recent. + [[nodiscard]] bool spaced(std::chrono::milliseconds instant) const; + + // Asks the window for what the visible rows need, cancels what it no longer covers, sends what is due and + // leaves the rest to the settle timer, or, for a refetch while the order awaits a level, to the refetch timer. + void pump(); + + // The request body: the node's body, its query member (`query`, or a typed list action's `queryMember`) + // overlaid with the window's sort, filter, rows and columns. + [[nodiscard]] std::expected bodyOf(table::TableQuery const& query) const; + + [[nodiscard]] table::TableQuery queryOf(table::PageRequest page, std::vector const& columns) const; + + void send(table::PageFetch const& fetch); + + void send(table::RowsFetch const& fetch); + + [[nodiscard]] std::string actionName() const { + return _options.action.empty() ? "Table." + _options.table : _options.action; + } + + void answered(); + + // A reply's page against the held description. A typed list action's first reply with rows also fixes the kinds + // of the columns `inferKinds` names, from the same DOM the page is read from. + [[nodiscard]] std::expected decode(std::string const& text); + + // A unit a `Measure` column's member names that the description does not list is its own canonical unit, in a + // dimension of its own named by its id, as an expression reads a unit missing from the screen's table. It is + // added after the units listed, so the numbers held cells carry keep their meaning; at most + // `detail::kMaxUnlistedUnits` are, the rest staying unknown. + void listUnits(std::span rows); + + // The kinds the first rows give the columns `inferKinds` names. The description keeps its revision, so the + // query, the window and the fetches in flight stand; only the records made of the cells are made again. + void inferKinds(std::span rows); + + [[nodiscard]] static bool wasCancelled(std::exception_ptr const& error); + + [[nodiscard]] static table::TableError failureOf(std::exception_ptr const& error); + + [[nodiscard]] static table::TableError unavailable(); + + void heardRevision(std::string const& revision); + + // The key held at each place of a page, or nothing at a place not held. + [[nodiscard]] std::vector> slotsOfPage(std::int64_t page) const; + + // The view's length as the mount holds it: the total, or nothing while none is known. + [[nodiscard]] std::int64_t shownRows() const { return _window.total().value_or(0); } + + // The change a page reply made, by key, as operations each valid on the list the one before it leaves: + // - a view that shrank loses its end first, so no row there is still held when the page's rows move in; + // - the page's places both views have are diffed by key, so a row that moved keeps its identity, and a place + // held on one side only is the same row when that row is nowhere else on the other side (its cells arrived + // or left); + // - a view that grew gains its end last, taken from the new view, once the rows that moved there have left + // their old places; + // - the pages the reply evicted are changed places. + // Rows of other pages do not move, since a page's places are fixed by its index. + // NOLINTNEXTLINE(readability-function-cognitive-complexity,bugprone-easily-swappable-parameters): page, count + [[nodiscard]] table::ViewChange pageChange(std::int64_t page, std::int64_t rowsBefore, + std::vector> const& before, + std::set const& heldBefore) const; + + void pageArrived(table::PageFetch const& fetch, std::string const& text); + + void pageFailed(table::PageFetch const& fetch, std::exception_ptr const& error); + + void rowsArrived(table::RowsFetch const& fetch, std::string const& text); + + void rowsFailed(table::RowsFetch const& fetch, std::exception_ptr const& error); + + // A keyed fetch that brought nothing: the rows stay as they were and may be out of date, so the pages are + // fetched again. + void keyedFailed(table::TableError error); + + void planned(table::RefreshPlan const& plan); + + // The values lists kept and in flight are bounded: a menu's pages and searches and an Apply's paging of every + // value (up to `QueryLimits::maxLimit` values a reply) are what fill them, and the oldest is the least likely to + // be asked for again. + static constexpr std::size_t kMaxDistinctReplies = 64; + static constexpr std::size_t kMaxDistinctFlights = 64; + + // Keeps a values list's reply by its query's body, the oldest going past the bound. + void keepDistinct(std::string const& key, table::DistinctValues const& values); + + // Drops every values list kept, and marks the replies in flight as asked for before the change. + void forgetDistinct(); + + // A change of the table's record. While the order awaits a level every event invalidates; `pump` spaces the + // refetches. + void heard(effects::RecordChange const& change); + + // Fetches @p keys again, as a change event naming them does; marked instead while a run holds the refetches. + void refetch(std::vector const& keys); + + // Sends what the events marked while the refetches were held, as one refetch. + void flushMarked(); + + // Takes a reply's word on which of its rows are retained and unmatched. + void heardUnmatched(table::GenericPage const& page); + + // The unmatched rows among those held now. + void heldUnmatched(); + + void status() const; + + void announce(table::ViewChange const& change); + + Session* _session; + WindowRowsOptions _options; + table::PageWindow _window; + std::optional _description; + std::shared_ptr _units; + std::map> _infos; + bool _descriptionError = false; + SortChain _sort; + table::FilterSpec _filter; + bool _restoring; + bool _watched = false; + std::size_t _unanswered = 0; + bool _inferring = false; + bool _retry = false; + std::vector _watches; + std::shared_ptr _reconnect; + std::size_t _unlisted = 0; + std::function _onInferred; + std::optional _error; + std::int64_t _first = 0; + std::int64_t _count = 0; + std::vector _columns; + bool _hasVisible = false; + std::uint64_t _columnsStamp = 1; + std::int64_t _anchor = -1; + std::chrono::milliseconds _anchorSince{0}; + reactive::TimerHandle _settleTimer; + std::optional _awaitedLast; + reactive::TimerHandle _awaitedTimer; + std::vector _pageFlights; + // The pages the mount has been told of, so one the window evicts is reported as changed places. + std::set _heldPages; + std::vector _rowsFlights; + // The latest reply's `viewRevision`: the membership a selection of the view names. + std::string _viewRevision; + // Keys a keyed reply asked for and left out of the view, until a reply holds them again or the filter changes. + std::unordered_set _outOfView; + // The retained rows, in the order they were added, and as a set; each change advances the stamp, by which a + // reply to a query of another set is told apart. + std::vector _retained; + std::unordered_set _retainedSet; + std::uint64_t _retainStamp = 0; + // The rows an action of this session works on, and those one could not change. + RowStates _states; + // Keys the latest reply that supplied them listed as unmatched, and those of them held. + std::unordered_set _unmatched; + std::unordered_set _unmatchedHeld; + // The runs holding the refetches, the hold's timer, and what events marked meanwhile. + std::set _holding; + reactive::TimerHandle _holdTimer; + std::vector _marked; + bool _markedAll = false; + std::set> _staleRevisions; + std::function _onStale; + std::function)> _onRowsAbsent; + std::function _onChange; + std::function _onStatus; + mutable std::unordered_map _memo; + mutable WindowRowsStats _stats; + // The stops of the key pages a range selection fetched, and of the fetch that locates a highlighted row. + std::vector> _keyRequests; + // The stops of the keyed fetches `fetchRows` sent. + std::vector> _rowsRequests; + std::map> _distinct; + std::deque _distinctOrder; + std::uint64_t _distinctEpoch = 0; + std::map _distinctFlights; + std::uint64_t _distinctFlight = 0; + ::core::async::StopSource _locateStop; + // Last, so it is the first to go: no reply or timer reaches a half-destroyed object. + async::CallbackScope _scope; +}; + +} // namespace morph::ui diff --git a/include/morph/ui/table_state.hpp b/include/morph/ui/table_state.hpp new file mode 100644 index 000000000..e22a7c4d7 --- /dev/null +++ b/include/morph/ui/table_state.hpp @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "table_state_model.hpp" + +/// @file +/// @brief The client half of persisted table state: `PreferencesTableStateStore`, which reaches the server's +/// `morph.tableState` model through the interpreter's `Dispatcher`, and `TableStates`, the states a session +/// keeps, with load batching and debounced saves. +/// +/// Specified in `docs/spec/table/table.md`, "Persisted state". + +namespace morph::ui { + +class Dispatcher; +class ModelChannel; + +/// @brief A table-state store over the server's `morph.tableState` model, so table state lives in the application's +/// preferences store under the person the server verified. +/// +/// Every call is made, and every completion delivered, on the owner. Loads asked for in one turn of the owner go out +/// as one `load` call per `kMaxTableStateKeys` keys, and a key a full reply defers is asked for in the next call, so +/// one table's state never fails another's load; a document longer than the head the server answers is completed with +/// `read` calls by offset, started again when its revision changes meanwhile. A document over a part's size is saved +/// as parts under one upload id; one the server refuses because its person has `kMaxTableStateUploads` uploads open +/// is sent again after a short wait, so a screen of many large states unmounting at once saves them all. +class MORPH_API PreferencesTableStateStore final : public table::ITableStateStore { +public: + /// @brief A store calling through @p dispatcher. + /// @param dispatcher Where model calls go; bound to `morph.tableState` once, at the first call. Borrowed: it must + /// outlive the store. + /// @param owner The runtime's owner, where calls are made and completions delivered. Borrowed. + /// @param scheduler The timers a save the server refused for its open uploads waits on before it is sent again; + /// without one it is sent again on the owner's next turn. Borrowed. + /// @param retryDelay How long such a save waits: a session's `tableStateTimeout`. + PreferencesTableStateStore(Dispatcher& dispatcher MORPH_LIFETIMEBOUND, exec::IExecutor& owner MORPH_LIFETIMEBOUND, + reactive::Scheduler* scheduler = nullptr, + std::chrono::milliseconds retryDelay = std::chrono::milliseconds{300}) + : _dispatcher{&dispatcher}, + _owner{&owner}, + _scheduler{scheduler}, + _retryDelay{retryDelay}, + _random{std::random_device{}()} {} + + /// @brief Sets the timers a save the server refused for its open uploads waits on, and how long it waits. A + /// `Session` calls it with its own scheduler and `tableStateTimeout` when its `tableState` is this store. + /// @param scheduler The timers. Borrowed: it must outlive the store. + /// @param retryDelay How long such a save waits before it is sent again. + void retryOn(reactive::Scheduler& scheduler, std::chrono::milliseconds retryDelay); + + /// @brief Reads a stored document, in the owner's turn's one `load` call. + /// @param key Which table's state, and which part. + /// @return The stored document, or nothing when none is stored. + [[nodiscard]] async::Completion> load( + table::TableStateKey const& key) override; + + /// @brief Stores @p json under the `expected` rule of `ITableStateStore::save`. + /// @param key Which table's state, and which part. + /// @param json The document. + /// @param expected The revision the caller loaded, or empty. + /// @return What the server answered. + [[nodiscard]] async::Completion save(table::TableStateKey const& key, std::string json, + std::string expected = {}) override; + + /// @brief Forgets a stored document. + /// @param key Which table's state, and which part. + /// @return Whether a document was stored. + [[nodiscard]] async::Completion remove(table::TableStateKey const& key) override; + + /// @brief Whether the store keeps the `shared` part for everyone. + /// @return `true`: the server keeps it with no person. + [[nodiscard]] bool shares() const override { return true; } + + /// @brief Applies one operation to the `shared` part, through the server's `publish` action, which the + /// application's authoriser admits or refuses by its id. + /// @param key Which table's state; its `part` is `"shared"`. + /// @param operation The operation. + /// @param expected The revision the caller loaded, `table::kNoDocument` when it loaded nothing, or empty. + /// @return What the server answered; the call's failure when the server refused it. + [[nodiscard]] async::Completion publish(table::TableStateKey const& key, + table::ViewOperation const& operation, + std::string expected) override; + +private: + /// The most bytes one `save` part carries: the server's default part size. + static constexpr std::size_t kPartBytes = kTableStatePartBytes; + /// How often one load starts again because the document changed while it was read. + static constexpr int kMaxRestarts = 8; + /// How often a save is sent again while the server refuses it for its open uploads: a hundred tries, about as + /// long as the server keeps an abandoned upload. + static constexpr int kMaxUploadRetries = 100; + + struct Reading { + table::TableStateKey key; + async::Completion>::Promise promise; + std::string revision; + std::uint64_t size = 0; + std::string text; + int restarts = 0; + }; + + struct Upload { + table::TableStateKey key; + std::string expected; + std::string id; + std::string text; + std::size_t offset = 0; + async::Completion::Promise promise; + int retries = 0; + }; + + [[nodiscard]] std::shared_ptr const& channel(); + + /// Adds a load to the owner's turn's batch, posting the batch's call with the first. + void queue(std::shared_ptr reading); + + /// Sends the turn's loads, in calls of at most `kMaxTableStateKeys` keys. + void flushLoads(); + + void sendLoads( + std::shared_ptr>> const& + batch); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the continuations the load registers are owned by the scope. + + void start(std::shared_ptr const& reading, TableStateHead head); + + void readMore( + std::shared_ptr const& + reading); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the continuations the read registers are owned by the scope. + + /// Sends a save the server refused for its open uploads again, after `retryDelay`. + void retryLater(std::shared_ptr const& upload); + + void sendPart( + std::shared_ptr const& + upload); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the continuations the save registers are owned by the scope. + + Dispatcher* _dispatcher; + exec::IExecutor* _owner; + reactive::Scheduler* _scheduler; + std::chrono::milliseconds _retryDelay; + std::mt19937_64 _random; + /// Saves waiting to be sent again, by a counter. + std::map _retries; + std::uint64_t _lastRetry = 0; + std::shared_ptr _channel; + /// Loads asked for in this turn of the owner. + std::vector> _batch; + /// Last, so it is stopped first: a delivery after the store is gone runs nothing. + async::CallbackScope _scope; +}; + +/// @brief The parts of a table's state a change touches: a bit set. +enum class StateParts : std::uint8_t { + None = 0, ///< No part. + Layout = 1, ///< The column layout, with the columns and groups carried for an absent column. + Sort = 2, ///< The sort chain, with the keys carried for an absent column. + Filters = 4, ///< The filters, with those carried for an absent column or group. + View = 8, ///< The saved view the arrangement was taken from. +}; + +/// @brief The union of two sets of parts. +/// @param lhs One set. +/// @param rhs The other. +/// @return Every part in either. +[[nodiscard]] constexpr StateParts operator|(StateParts lhs, StateParts rhs) noexcept { + return static_cast(static_cast(lhs) | static_cast(rhs)); +} + +/// @brief Whether @p set holds @p part. +/// @param set The set. +/// @param part One part. +/// @return `true` when @p part is in @p set. +[[nodiscard]] constexpr bool holds(StateParts set, StateParts part) noexcept { + return (static_cast(set) & static_cast(part)) != 0; +} + +/// @brief The table states one session keeps, loads and saves: one per `Session` that has a store. +/// +/// Every document it loaded or saved is kept, by key, for its life, so a key loaded once is answered at once after. +/// Changes are debounced per key: a save goes out when a key has not changed for the debounce, at once on `flush`, +/// and one save per key is in flight, a change made during it being one more save after it. A save writes the +/// whole `state` document with no expected revision. +/// +/// A change made before the key's load settles is held: when the load completes, the save writes the loaded document +/// with only the changed parts replaced, so a sort changed during a slow load never overwrites the stored filters. A +/// load that fails, or whose text `table::readState` refuses, gives an empty document to change: the stored text is +/// never merged into, so the first save after a change replaces it with a `table::kStateVersion` document holding +/// the changed parts, and nothing is written until a change. +/// +/// Everything runs on the owner, where the store delivers its completions. +class MORPH_API TableStates { +public: + /// @brief The kept states of a session. + /// @param store Where states are loaded from and saved to. + /// @param owner The runtime's owner, where `load` answers. Borrowed. + /// @param scheduler The debounce's timers; without one every change saves at once. Borrowed. + /// @param debounce How long a key must stay unchanged before its save goes out. + /// @throws std::invalid_argument for a null store. + TableStates(std::shared_ptr store, exec::IExecutor& owner MORPH_LIFETIMEBOUND, + reactive::Scheduler* scheduler, std::chrono::milliseconds debounce); + + TableStates(TableStates const&) = delete; + TableStates& operator=(TableStates const&) = delete; + TableStates(TableStates&&) = delete; + TableStates& operator=(TableStates&&) = delete; + ~TableStates() = default; + + /// @brief The kept copy of a key's state: what the store held when it was loaded, or what was last saved. + /// @param key The key. + /// @return It; nothing when the key was not loaded, or nothing is stored under it. + [[nodiscard]] std::optional kept(table::TableStateKey const& key) const; + + /// @brief A key's stored state: the kept copy at once, with no call, when the key is known; otherwise from the + /// store, one load in flight per key however many ask. + /// @param key The key. + /// @return The stored document, or nothing; the store's failure when the load fails. + [[nodiscard]] async::Completion> load(table::TableStateKey const& key); + + /// @brief Marks @p parts of the key's state changed to those of @p document; a debounced save, one in flight per + /// key. + /// @param key The key. + /// @param document The arrangement now; only @p parts of it are taken. + /// @param parts The parts that changed. + void changed(table::TableStateKey const& key, table::StateDocument const& document, StateParts parts); + + /// @brief Takes @p document as the key's state now, without saving it, as a table does when it starts from a view + /// while nothing is stored: the next change is saved on top of it, so the rest of what it started from is + /// kept. Ignored until the key's load settles, and once a change has been made. + /// @param key The key. + /// @param document The state the table started from. + void start(table::TableStateKey const& key, table::StateDocument document); + + /// @brief Saves a key's unsaved change now, as a table does when it unmounts; held until its load settles. + /// @param key The key. + void flush(table::TableStateKey const& key); + + /// @brief Sets the one handler told of every save that did not end `Saved`: the store's completion failed (as + /// `Refused` with the failure's text as `reason`), or it answered `Refused` or `Conflict`. + /// @param handler Called on the owner with the key and the result; empty to tell no one. + void onSaveFailed(std::function handler) { + _onSaveFailed = std::move(handler); + } + + /// @brief The store it loads from and saves to, for a part this class does not debounce, such as saved views. + /// @return The store. + [[nodiscard]] table::ITableStateStore& store() const noexcept { return *_store; } + + /// @brief Replaces the kept copy of @p key after a save made through `store()`, so a later mount restores it. + /// A debounced save of the key still goes out, with its own document. + /// @param key The key. + /// @param state What the store holds now. + void keep(table::TableStateKey const& key, table::StoredTableState state); + +private: + using Key = std::tuple; + + struct Entry { + /// What the store holds, as far as this session knows. + std::optional kept; + /// Whether `kept` is known: loaded, saved or kept. + bool known = false; + bool loading = false; + std::vector>::Promise> waiters; + /// Whether the document changes are made to is decided: the load settled. + bool settled = false; + /// Whether that document came from a failed load, and so a later load may still replace it. + bool fromFailure = false; + /// The document saves write, once settled. + table::StateDocument current; + /// Changes made before the load settled, and which parts they touch. + table::StateDocument held; + StateParts heldParts{}; + bool dirty = false; + bool saving = false; + reactive::TimerHandle timer; + }; + + [[nodiscard]] static Key tie(table::TableStateKey const& key) { + return Key{key.application, key.model, key.table, key.qualifier, key.part}; + } + + /// Copies @p parts of @p from into @p into, with what each part carries for an absent column. + static void take(table::StateDocument& into, table::StateDocument const& from, StateParts parts); + + void startLoad( + table::TableStateKey const& key, + Entry& + entry); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the continuations the load registers are owned by the scope. + + void loaded(table::TableStateKey const& key, std::optional const& stored); + + void loadFailed(table::TableStateKey const& key, std::exception_ptr const& error); + + /// Decides the document changes are made to: @p stored as `readState` reads it, or an empty one, with the held + /// changes applied. + static void settle(Entry& entry, std::optional const& stored); + + void trySave( + table::TableStateKey const& + key); // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the continuations the save registers are owned by the scope. + + void saved(table::TableStateKey const& key, std::string const& json, table::SaveResult const& result); + + std::shared_ptr _store; + exec::IExecutor* _owner; + reactive::Scheduler* _scheduler; + std::chrono::milliseconds _debounce; + std::function _onSaveFailed; + std::map _entries; + /// Last, so it is stopped first: a delivery or timer after the states are gone runs nothing. + async::CallbackScope _scope; +}; + +} // namespace morph::ui diff --git a/include/morph/ui/table_state_model.hpp b/include/morph/ui/table_state_model.hpp new file mode 100644 index 000000000..6115e0c33 --- /dev/null +++ b/include/morph/ui/table_state_model.hpp @@ -0,0 +1,1012 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../table/state_store.hpp" +#include "preferences.hpp" + +/// @file +/// @brief The server half of `PreferencesTableStateStore`: the `morph.tableState` model, which keeps a table's state +/// of any size in the application's `IPreferencesStore`, under the person the verified session names. +/// +/// Specified in `docs/spec/table/table.md`, "Persisted state", "The framework's stores". + +namespace morph::ui { + +/// @brief The most document bytes one `save` part carries and one `load` head or `read` chunk answers, by default. +/// `PreferencesTableStateStore` sends parts of this size, so a server's `partBytes` is at least this. +inline constexpr std::size_t kTableStatePartBytes = std::size_t{1} << 20; + +/// @brief The table-state model's bounds. +struct TableStateOptions { + /// @brief The longest document kept in its head entry, in bytes; a larger one is written as segments, each a JSON + /// string of at most this many bytes. A head also holds the key in clear and the revision, so a head of a + /// document near this size is longer than it. + std::size_t segmentBytes = std::size_t{12} * 1024; + /// @brief The most document bytes one `save` part carries and one `load` head or `read` chunk answers: 16 to + /// `kTableStatePartBytes`. The client sends parts of `kTableStatePartBytes`, so a server refuses its saves + /// in parts when this is lower; a larger value is refused, since one head could then outgrow its envelope. + std::size_t partBytes = kTableStatePartBytes; + /// @brief The operator's quota: the most document bytes one person may have stored, across every application. + /// Unset, nothing limits a state. + std::optional maxBytesPerPerson; + /// @brief How long an upload in parts may wait for its next part before it is dropped. A client sends each part + /// as soon as the previous one is answered, so a gap a hundred times a session's `tableStateTimeout` + /// (300 ms) is an upload abandoned. + std::chrono::milliseconds uploadExpiry = std::chrono::milliseconds{300} * 100; + /// @brief The clock `uploadExpiry` is measured on; empty uses `std::chrono::steady_clock`. + std::function clock; +}; + +/// @brief The most uploads in parts one person may have open on a server. A save that would start one more answers +/// `Refused` with `kTableStateUploadsBusy`, and `PreferencesTableStateStore` sends it again a little later. +inline constexpr std::size_t kMaxTableStateUploads = 4; + +/// @brief The `reason` of a save refused because its person has `kMaxTableStateUploads` uploads open. +inline constexpr std::string_view kTableStateUploadsBusy = "too many table-state uploads in progress"; + +/// @brief The most bytes of head text one `load` answers, counted as the text travels, escaped once in the reply and +/// again in its envelope: a reply then stays inside the 8 MiB envelope, a head of a full part included. +inline constexpr std::size_t kTableStateLoadReplyBytes = std::size_t{6} << 20; + +/// @brief The longest key member a table-state request may carry, in bytes. +inline constexpr std::size_t kMaxTableStateNameBytes = 256; + +/// @brief The most keys one `load` may name. +inline constexpr std::size_t kMaxTableStateKeys = 256; + +/// @brief `load`: the heads of the caller's stored documents under @p keys. A request carries no person. +struct TableStateLoad { + /// @brief The keys, each answered in order. + std::vector keys; +}; + +/// @brief One key's answer to `load`. +struct TableStateHead { + /// @brief Whether a document is stored under the key. + bool found = false; + /// @brief The stored document's revision. + std::string revision; + /// @brief The document's whole length, in bytes. + std::uint64_t size = 0; + /// @brief The document's first bytes, at most `TableStateOptions::partBytes`; the rest is read by `read`. + std::string text; + /// @brief Why this key's document could not be read, such as a key out of bounds or a missing segment; empty + /// when it could. + std::string error; + /// @brief Not answered in this reply, which is full: the caller asks for the key again. + bool deferred = false; +}; + +/// @brief What `load` answers. +struct TableStateLoaded { + /// @brief One head per key, in the request's order. + std::vector entries; +}; + +/// @brief `read`: more of a stored document, from @p offset. +struct TableStateRead { + /// @brief Which document. + table::TableStateKey key; + /// @brief The revision the caller is reading. + std::string revision; + /// @brief The first byte wanted. + std::uint64_t offset = 0; +}; + +/// @brief What `read` answers. +struct TableStateChunk { + /// @brief The revision stored now. When it is not the one asked for, @p text is empty and the caller starts + /// again; empty when nothing is stored. + std::string revision; + /// @brief The document's bytes from the asked offset, at most `TableStateOptions::partBytes`. + std::string text; +}; + +/// @brief `save`: stores a document, or one part of it. +/// +/// A document of at most `TableStateOptions::partBytes` is one request with `upload` empty. A larger one is sent as +/// parts under one `upload` id, each at the offset where the previous ended, and is stored when the part with `last` +/// arrives; `expected` and the quota are checked then, against the whole text. +struct TableStateSave { + /// @brief Which document. + table::TableStateKey key; + /// @brief Empty to replace whatever is stored; otherwise the revision the stored document must have. + std::string expected; + /// @brief The upload's id, for a document sent in parts; empty for one sent whole. + std::string upload; + /// @brief Where @p text starts in the document. + std::uint64_t offset = 0; + /// @brief The document's bytes from @p offset. + std::string text; + /// @brief Whether this part ends the document. + bool last = true; +}; + +/// @brief What `save` answers. +struct TableStateSaved { + /// @brief The outcome; a part that is not `last` answers `Saved` with no revision. + table::SaveResult result; +}; + +/// @brief `publish`: applies one operation to the views published for everyone. +struct TableStatePublish { + /// @brief Which table's shared views; its `part` is `"shared"`. + table::TableStateKey key; + /// @brief The operation's JSON, as `table::writeViewOperation` writes it. + std::string operation; + /// @brief Empty to apply it to whatever is stored; `table::kNoDocument` to apply it only when nothing is; + /// otherwise the revision the stored document must have. Even with it empty the model writes over the + /// revision it read, so a publish that lands between that read and its write answers `Conflict`. + std::string expected; +}; + +/// @brief `remove`: forgets a stored document. +struct TableStateRemove { + /// @brief Which document. + table::TableStateKey key; +}; + +/// @brief What `remove` answers. +struct TableStateRemoved { + /// @brief Whether a document was stored. + bool removed = false; +}; + +namespace detail { + +/// @brief A stored document's head entry: the key in clear, the revision, and either the document or its segments. +struct StoredStateHead { + /// @brief The key, for whoever reads the store. + table::TableStateKey key; + /// @brief The document's revision. + std::string revision; + /// @brief The document, for one of at most `segmentBytes`. + std::optional document; + /// @brief The number of segments, for a larger one. + std::optional segments; + /// @brief The document's length, for a larger one. + std::optional bytes; +}; + +/// @brief The intent a save writes before its segments: the revisions whose segments may be stray if it stops. +struct StoredStateIntent { + /// @brief The revision being written. + std::string revision; + /// @brief Its segments; 0 for an unsegmented document. + std::uint64_t segments = 0; + /// @brief The revision being replaced; empty when none. + std::string previous; + /// @brief Its segments; 0 for an unsegmented document. + std::uint64_t previousSegments = 0; +}; + +/// @brief A person's table-state usage entry. +struct StoredStateUsage { + /// @brief The document bytes stored. + std::uint64_t bytes = 0; +}; + +/// @brief Reads stored entries leniently. +inline constexpr glz::opts kStoredRead{.null_terminated = false, .error_on_unknown_keys = false}; + +/// @brief The first @p digits lower-case hex digits of SHA-256 of @p text. +/// @param text The text. +/// @param digits How many digits, at most 64. +/// @return The digits. +[[nodiscard]] MORPH_API std::string sha256Hex(std::string_view text, std::size_t digits); + +/// @brief The preferences scope a key's entries are kept under: `morph.table.` and 32 hex digits of the digest of +/// its `model`, `table` and `qualifier`, so the scope fits a preference name's length whatever the ids are. +/// @param key The key. +/// @return The scope. +[[nodiscard]] MORPH_API std::string tableStateScope(table::TableStateKey const& key); + +/// @brief A document's revision: 16 hex digits of the digest of the revision it replaces and its text. +/// @param previous The replaced revision; empty when none. +/// @param document The document's text. +/// @return The revision. +[[nodiscard]] MORPH_API std::string tableStateRevision(std::string const& previous, std::string_view document); + +/// @brief How many bytes a byte takes inside a JSON string as `quotedSegment` writes it. +/// @param byte The byte. +/// @return 1, 2 for a short escape, or 6 for `\u00XX`. +[[nodiscard]] constexpr std::size_t escapedBytes(unsigned char byte) noexcept { + switch (byte) { + case '"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + return 2; + default: + return byte < 0x20 ? 6 : 1; + } +} + +/// @brief @p text as a JSON string, quotes included. +/// @param text The text. +/// @return The JSON string. +[[nodiscard]] MORPH_API std::string quotedSegment(std::string_view text); + +/// @brief The length of the UTF-8 sequence @p lead starts; 1 for a byte that starts none. +/// @param lead The byte. +/// @return 1 to 4. +[[nodiscard]] constexpr std::size_t sequenceBytes(unsigned char lead) noexcept { + if (lead >= 0xF0 && lead <= 0xF7) { + return 4; + } + if (lead >= 0xE0) { + return lead <= 0xEF ? 3 : 1; + } + return lead >= 0xC0 ? 2 : 1; +} + +/// @brief The longest prefix of @p text of at most @p limit bytes that does not cut a UTF-8 sequence. +/// @param text The text. +/// @param limit The most bytes; at least 4. +/// @return The prefix's length. +[[nodiscard]] MORPH_API std::size_t utf8Prefix(std::string_view text, std::size_t limit) noexcept; + +/// @brief How many bytes @p text takes as it travels in a `load` reply: escaped once as a JSON string in the reply, +/// and the reply escaped again as the envelope's body. +/// @param text The text. +/// @return Its length on the wire, quotes excluded. +[[nodiscard]] MORPH_API std::uint64_t wireBytes(std::string_view text) noexcept; + +/// @brief A lock per name for coroutines: one holder at a time, the others waiting their turn in order and resumed +/// where they were running. +class MORPH_API TableStateLocks { +public: + /// @brief The held lock of one name, released when it is destroyed. + class MORPH_API Lease { + public: + /// @brief A lease of @p name. + /// @param locks The locks. Borrowed. + /// @param name The name held. + Lease(TableStateLocks* locks, std::string name) : _locks{locks}, _name{std::move(name)} {} + Lease(Lease const&) = delete; + Lease& operator=(Lease const&) = delete; + /// @brief Takes @p other's lock. + /// @param other The lease to take from; it then holds nothing. + Lease(Lease&& other) noexcept : _locks{std::exchange(other._locks, nullptr)}, _name{std::move(other._name)} {} + Lease& operator=(Lease&&) = delete; + /// @brief Releases the lock, handing it to the next waiter. + ~Lease(); + + private: + TableStateLocks* _locks; + std::string _name; + }; + + /// @brief The awaiter `lock` returns. + class MORPH_API Acquire { + public: + /// @brief An acquisition of @p name. + /// @param locks The locks. Borrowed. + /// @param name The name. + Acquire(TableStateLocks& locks, std::string name) : _locks{&locks}, _name{std::move(name)} {} + Acquire(Acquire const&) = delete; + Acquire& operator=(Acquire const&) = delete; + Acquire(Acquire&&) = delete; + Acquire& operator=(Acquire&&) = delete; + /// @brief Leaves the queue when the waiting coroutine is destroyed before its turn, and passes the lock on + /// when it was handed the lock but destroyed before it ran. + ~Acquire(); + + /// @brief Never ready before `await_suspend` has decided. + /// @return `false`. + // NOLINTNEXTLINE(readability-convert-member-functions-to-static): the awaiter protocol calls it on the object. + [[nodiscard]] constexpr bool await_ready() const noexcept { return false; } + + /// @brief Takes the lock when it is free, or queues for it. + /// @param awaiting The coroutine taking it. + /// @return `false` when taken at once; `true` when queued. + bool await_suspend(std::coroutine_handle<> awaiting); + + /// @brief The lease. + /// @return It. + [[nodiscard]] Lease await_resume(); + + private: + friend class TableStateLocks; + TableStateLocks* _locks; + std::string _name; + std::coroutine_handle<> _awaiting; + ::core::async::ResumeTarget _context; + bool _queued = false; + /// Holds the lock but has not yet made the lease that releases it. + bool _handed = false; + }; + + /// @brief Waits for the lock of @p name. + /// @param name The name. + /// @return The awaiter; `co_await` it for the lease. + [[nodiscard]] Acquire lock(std::string name) { return Acquire{*this, std::move(name)}; } + +private: + void release(std::string const& name); + + std::mutex _mutex; + /// @brief Each held name and its waiters, oldest first. + std::map, std::less<>> _held; +}; + +/// @brief A person has `kMaxTableStateUploads` uploads in parts open; their next one is refused until one ends. +struct UploadsBusy : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +/// @brief A segment a head names is missing or does not read. Reads take no lock, so a save that replaced the head +/// meanwhile is the usual cause: a reader then reads the head again. +struct MissingSegment : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +/// @brief What every instance of the table-state model on one server shares: the per-key locks that keep two saves of +/// one key from interleaving, and the uploads in parts. +struct TableStateShared { + /// @brief A document arriving in parts. + struct Upload { + /// @brief Which document. + table::TableStateKey key; + /// @brief The text so far. + std::string text; + /// @brief When it started, on the options' clock. + std::chrono::milliseconds started{0}; + /// @brief When its last part arrived. + std::chrono::milliseconds touched{0}; + }; + + /// @brief The locks, one name per key of one owner. + TableStateLocks locks; + /// @brief Guards `uploads`. + std::mutex mutex; + /// @brief Open uploads, by person and upload id. + std::map, Upload> uploads; +}; + +/// @brief Cuts @p text into segments, each written as a JSON string of at most @p segmentBytes bytes and none cutting +/// a UTF-8 sequence. +/// @param text The document's text. +/// @param segmentBytes The longest segment entry; at least 32. +/// @return Each segment's entry, a JSON string. +[[nodiscard]] MORPH_API std::vector segmentText(std::string_view text, std::size_t segmentBytes); + +} // namespace detail + +/// @brief The server's table-state model: keeps each person's table states in the application's preferences store, +/// a document of any size in entries of at most `segmentBytes`. +/// +/// The person is the principal of the verified session, as for the preferences model: no request names one. With no +/// verified principal, `load` answers nothing found for every key, `read` answers no revision and no text, and +/// `save` and `remove` are refused. +/// +/// The `shared` part is the exception: it is the views published for everyone, so its entries are kept with no +/// person, and every verified caller's `load` and `read` reach the same document. It is written only by `publish`, +/// an action of its own, so an authoriser admits or refuses publishing by action id; `save` of it answers `Refused` +/// and `remove` of it is refused. It counts against the operator's quota as an account of its own, the person "", +/// so the ceiling bounds it as it bounds each person's state. +/// +/// A key's entries are the caller's person's, of the key's `application`, under the scope +/// `detail::tableStateScope(key)`. The point `` is the head: the key in clear, the revision, and the document +/// itself when it is at most `segmentBytes`, else its segment count and length, the segments being the points +/// `..`. The store can only get, set and remove by exact key, so it cannot list a scope's +/// segments; a save that writes segments, or replaces segmented ones, first writes an intent at `.pending` +/// naming both revisions, and the next save of the key removes whatever segments the intent names and the head does +/// not. The write order is: clean up a previous intent, write the intent, the segments, the head, then remove the +/// replaced segments and the intent. A reader takes the head and then the segments it names, so it reads one whole +/// revision or the other. +class MORPH_API TableStateModel { +public: + /// @brief A model over @p store. + /// @param store Where states are kept. Shared by every instance. + /// @param options The bounds and the quota. + /// @param shared The locks and uploads every instance on the server shares; null gives this instance its own. + /// @throws std::invalid_argument for a null store, a `segmentBytes` under 32, or a `partBytes` under 16 or over + /// `kTableStatePartBytes`: a head of more than that could outgrow a reply's envelope. + TableStateModel(std::shared_ptr store, TableStateOptions options, + std::shared_ptr shared = nullptr); + + /// @brief Reads the heads of the caller's documents. + /// + /// Each key is answered alone: one out of bounds, or whose segment is missing, has its `error` and the others + /// load. A reply whose head text would pass `kTableStateLoadReplyBytes` answers its remaining keys `deferred`, + /// after at least one head, so a screen of large states takes more than one call and no reply outgrows its + /// envelope. + /// @param request The keys. + /// @return One head per key, in order. + /// @throws std::invalid_argument for more than `kMaxTableStateKeys` keys. + ::core::async::Task execute(TableStateLoad request) { + if (request.keys.size() > kMaxTableStateKeys) { + throw std::invalid_argument{"a table-state load names more than " + std::to_string(kMaxTableStateKeys) + + " keys"}; + } + TableStateLoaded reply; + std::string const person = verifiedPerson(); + std::uint64_t spent = 0; + bool full = false; + for (auto const& key : request.keys) { + TableStateHead entry; + if (full) { + entry.deferred = true; + reply.entries.push_back(std::move(entry)); + continue; + } + if (auto problem = keyProblem(key)) { + entry.error = std::move(*problem); + reply.entries.push_back(std::move(entry)); + continue; + } + if (person.empty()) { + reply.entries.push_back(std::move(entry)); + continue; + } + entry = co_await readFirst(ownerOf(person, key), key); + std::uint64_t const cost = detail::wireBytes(entry.text); + if (spent > 0 && spent + cost > kTableStateLoadReplyBytes) { + full = true; + reply.entries.push_back(TableStateHead{ + .found = false, .revision = {}, .size = 0, .text = {}, .error = {}, .deferred = true}); + continue; + } + spent += cost; + reply.entries.push_back(std::move(entry)); + } + co_return reply; + } + + /// @brief Reads more of the caller's document. + /// @param request The key, the revision and the offset. + /// @return The bytes from the offset, or the current revision with no bytes when it is not the one asked for. + ::core::async::Task execute(TableStateRead request) { + checkKey(request.key); + std::string const person = verifiedPerson(); + if (person.empty()) { + co_return TableStateChunk{}; + } + std::string const owner = ownerOf(person, request.key); + Head const head = co_await readHead(owner, request.key); + if (!head.found || head.revision != request.revision) { + co_return TableStateChunk{.revision = head.revision, .text = {}}; + } + if (request.offset > head.size()) { + throw std::invalid_argument{"a table-state read starts past the document's end"}; + } + std::string text; + std::string missing; + try { + text = co_await readRange(owner, request.key, head, request.offset); + } catch (detail::MissingSegment const& error) { + missing = error.what(); + } + if (!missing.empty()) { + // A save replaced the document meanwhile: the reader starts again from the head it names now. + Head const now = co_await readHead(owner, request.key); + if (!now.found || now.revision != head.revision) { + co_return TableStateChunk{.revision = now.revision, .text = {}}; + } + throw std::runtime_error{missing}; + } + co_return TableStateChunk{.revision = head.revision, .text = std::move(text)}; + } + + /// @brief Stores the caller's document, or one part of it. + /// @param request The key, the `expected` rule, and the document or part. + /// @return `Saved` with the new revision; `Conflict` with the current one when `expected` does not hold; + /// `Refused` over the quota, and for the `shared` part, which only `publish` writes. + ::core::async::Task execute(TableStateSave request) { + checkKey(request.key); + if (request.text.size() > _options.partBytes) { + throw std::invalid_argument{"a table-state save part is longer than " + + std::to_string(_options.partBytes) + " bytes"}; + } + std::string const person = signedInPerson(); + if (request.key.part == kSharedPart) { + co_return TableStateSaved{.result = + table::SaveResult{.outcome = table::SaveOutcome::Refused, + .revision = {}, + .reason = "the shared views are written by publish"}}; + } + if (request.upload.empty()) { + if (request.offset != 0 || !request.last) { + throw std::invalid_argument{"a table-state save in parts names its upload"}; + } + auto const lease = co_await _shared->locks.lock(lockName(person, request.key)); + co_return TableStateSaved{ + .result = co_await commit(person, request.key, std::move(request.expected), std::move(request.text))}; + } + if (request.upload.size() > kMaxTableStateNameBytes) { + throw std::invalid_argument{"a table-state upload id is at most " + + std::to_string(kMaxTableStateNameBytes) + " bytes"}; + } + std::optional whole; + bool busy = false; + try { + whole = takePart(person, request); + } catch (detail::UploadsBusy const&) { + busy = true; + } + if (busy) { + co_return TableStateSaved{.result = table::SaveResult{.outcome = table::SaveOutcome::Refused, + .revision = {}, + .reason = std::string{kTableStateUploadsBusy}}}; + } + if (!whole) { + co_return TableStateSaved{}; + } + auto const lease = co_await _shared->locks.lock(lockName(person, request.key)); + co_return TableStateSaved{ + .result = co_await commit(person, request.key, std::move(request.expected), std::move(*whole))}; + } + + /// @brief Forgets the caller's document. + /// @param request The key. + /// @return Whether a document was stored. + /// @throws std::invalid_argument for the `shared` part, which only `publish` writes. + ::core::async::Task execute(TableStateRemove request) { + checkKey(request.key); + std::string const person = signedInPerson(); + if (request.key.part == kSharedPart) { + throw std::invalid_argument{"the shared views are written by publish"}; + } + auto const lease = co_await _shared->locks.lock(lockName(person, request.key)); + co_await cleanUp(person, request.key); + Head const head = co_await readHead(person, request.key); + if (!head.found) { + co_return TableStateRemoved{}; + } + bool const intent = head.segments > 0; + if (intent) { + co_await setOrThrow( + pointKey(person, request.key, pendingPoint(request.key)), + write(detail::StoredStateIntent{ + .revision = {}, .segments = 0, .previous = head.revision, .previousSegments = head.segments})); + } + static_cast(co_await _store->remove(pointKey(person, request.key, request.key.part))); + co_await removeSegments(person, request.key, head.revision, head.segments); + if (intent) { + static_cast(co_await _store->remove(pointKey(person, request.key, pendingPoint(request.key)))); + } + if (_options.maxBytesPerPerson) { + std::uint64_t const used = co_await usage(person); + co_await setUsage(person, used - std::min(used, head.counted)); + } + co_return TableStateRemoved{.removed = true}; + } + + /// @brief Applies one operation to the views published for everyone, kept with no person. + /// @param request The `shared` key, the operation's JSON and the `expected` rule. + /// @return `Saved` with the new revision; `Conflict` with the current one when `expected` does not hold; + /// `Refused` for a default, which the shared views do not have, an operation that does not apply, or a + /// stored document that does not read. + /// @throws std::invalid_argument for a key of another part or an operation that does not read; + /// std::runtime_error for a caller with no verified person. + ::core::async::Task execute(TableStatePublish request) { + checkKey(request.key); + if (request.key.part != kSharedPart) { + throw std::invalid_argument{"a table-state publish names the part `shared`"}; + } + static_cast(signedInPerson()); + auto const operation = table::readViewOperation(request.operation); + if (!operation) { + throw std::invalid_argument{operation.error().message}; + } + auto const refuse = [](std::string revision, std::string reason) { + return TableStateSaved{.result = table::SaveResult{.outcome = table::SaveOutcome::Refused, + .revision = std::move(revision), + .reason = std::move(reason)}}; + }; + std::string const owner; // the shared views are no one's + auto const lease = co_await _shared->locks.lock(lockName(owner, request.key)); + co_await cleanUp(owner, request.key); + Head const head = co_await readHead(owner, request.key); + if (!holds(request.expected, head)) { + co_return TableStateSaved{.result = table::SaveResult{.outcome = table::SaveOutcome::Conflict, + .revision = head.revision, + .reason = {}}}; + } + table::ViewsDocument document; + if (head.found) { + auto read = table::readViews(co_await readWhole(owner, request.key, head)); + if (!read) { + co_return refuse(head.revision, read.error().message); + } + document = std::move(*read); + } + auto applied = table::applyViewOperation(std::move(document), *operation, table::ViewsPart::Shared); + if (!applied) { + co_return refuse(head.revision, table::viewErrorText(applied.error(), *operation)); + } + co_return TableStateSaved{ + .result = co_await commit(owner, request.key, head.found ? head.revision : std::string{table::kNoDocument}, + table::writeViews(*applied, table::ViewsPart::Shared))}; + } + +private: + /// @brief The part kept for everyone, with no person. + static constexpr std::string_view kSharedPart = "shared"; + /// @brief How often a load reads a head again because saves keep replacing it while it reads. + static constexpr int kMaxRereads = 8; + + /// @brief A head as read. + struct Head { + bool found = false; + std::string revision; + /// The document, for an unsegmented one. + std::string document; + std::uint64_t segments = 0; + std::uint64_t bytes = 0; + /// The document's length as its save received it, which the quota counts. + std::uint64_t counted = 0; + + /// The document's length. + [[nodiscard]] std::uint64_t size() const { return segments > 0 ? bytes : document.size(); } + }; + + /// @brief Whose entries a key's are: @p person's, or no one's for the `shared` part. + /// @param person The verified caller. + /// @param key The key. + /// @return The person the store is called with. + [[nodiscard]] static std::string ownerOf(std::string const& person, table::TableStateKey const& key) { + return key.part == kSharedPart ? std::string{} : person; + } + + /// @brief The verified principal of the call being run. + /// @return It; empty when the server verified nobody. + [[nodiscard]] static std::string verifiedPerson(); + + /// @brief The verified principal, for a call that writes. + /// @return It. + /// @throws std::runtime_error when the server verified nobody. + [[nodiscard]] static std::string signedInPerson(); + + /// @brief What is wrong with a key: a member out of bounds (`model` is 0 to 256 bytes, the others 1 to 256), or + /// a `part` holding a `.`, which would name another part's intent or segment points. + /// @param key The key. + /// @return The problem; nothing for a key in bounds. + [[nodiscard]] static std::optional keyProblem(table::TableStateKey const& key); + + /// @brief Refuses a key out of bounds. + /// @param key The key. + static void checkKey(table::TableStateKey const& key); + + /// @brief The lock of one owner's key: two writes of it never interleave on this server. + /// @param owner The person whose entries they are; empty for the shared views. + /// @param key The key. + /// @return The lock's name. + [[nodiscard]] static std::string lockName(std::string const& owner, table::TableStateKey const& key) { + return owner + "\x1F" + key.application + "\x1F" + detail::tableStateScope(key) + "\x1F" + key.part; + } + + /// @brief The options' clock now. + /// @return It. + [[nodiscard]] std::chrono::milliseconds now() const; + + /// @brief Adds one part to its upload, after dropping every upload that waited past `uploadExpiry`. + /// @param person The caller. + /// @param request The part. + /// @return The whole text at the last part; nothing before it. + /// @throws std::invalid_argument for a part that does not continue its upload, or that takes it past the quota; + /// detail::UploadsBusy for a first part while the person has `kMaxTableStateUploads` open. + [[nodiscard]] std::optional takePart(std::string const& person, TableStateSave& request); + + [[nodiscard]] static std::string pendingPoint(table::TableStateKey const& key) { return key.part + ".pending"; } + + [[nodiscard]] static std::string segmentPoint(table::TableStateKey const& key, std::string const& revision, + std::uint64_t index) { + return key.part + "." + revision + "." + std::to_string(index); + } + + [[nodiscard]] static PrefKey pointKey(std::string const& person, table::TableStateKey const& key, + std::string point); + + [[nodiscard]] static PrefKey usageKey(std::string const& person); + + template + [[nodiscard]] static std::string write(T const& value) { + std::string out; + if (auto const error = glz::write(value, out)) { + throw std::runtime_error{"a table-state entry does not write: " + glz::format_error(error, out)}; + } + return out; + } + + ::core::async::Task setOrThrow(PrefKey key, std::string value) { + if (!co_await _store->set(key, std::move(value))) { + throw std::runtime_error{"the preferences store refused a table-state entry"}; + } + } + + /// @brief Reads a key's head; one that does not read, or whose clear key is another's, is not found. + ::core::async::Task readHead(std::string person, table::TableStateKey key) { + std::optional const stored = co_await _store->get(pointKey(person, key, key.part)); + Head head; + if (!stored) { + co_return head; + } + detail::StoredStateHead entry; + if (glz::read(entry, *stored) || !(entry.key == key) || entry.revision.empty()) { + co_return head; + } + if (entry.document) { + head.document = std::move(entry.document->str); + head.counted = entry.bytes.value_or(head.document.size()); + } else if (entry.segments && *entry.segments > 0 && entry.bytes) { + head.segments = *entry.segments; + head.bytes = *entry.bytes; + head.counted = head.bytes; + } else { + co_return head; + } + head.found = true; + head.revision = std::move(entry.revision); + co_return head; + } + + /// @brief A key's head and the document's first bytes. A segment missing because a save replaced the head + /// meanwhile is read again from the head stored now, so a load answers the old document or the new one and + /// never fails over a concurrent save; one missing under an unchanged head is the key's `error`. + ::core::async::Task readFirst(std::string owner, table::TableStateKey key) { + TableStateHead entry; + for (int attempt = 0; attempt < kMaxRereads; ++attempt) { + Head const head = co_await readHead(owner, key); + entry = TableStateHead{}; + if (!head.found) { + co_return entry; + } + entry.found = true; + entry.revision = head.revision; + entry.size = head.size(); + std::string missing; + try { + entry.text = co_await readRange(owner, key, head, 0); + co_return entry; + } catch (detail::MissingSegment const& error) { + missing = error.what(); + } + Head const now = co_await readHead(owner, key); + if (now.found && now.revision == head.revision) { + co_return TableStateHead{.found = false, .revision = {}, .size = 0, .text = {}, .error = missing}; + } + } + co_return TableStateHead{.found = false, + .revision = {}, + .size = 0, + .text = {}, + .error = "a table's stored state kept changing while it was read"}; + } + + /// @brief The document's bytes from @p offset, at most `partBytes`, cut at a UTF-8 boundary. + /// @throws detail::MissingSegment when a segment the head names is missing or does not read. + ::core::async::Task readRange(std::string person, table::TableStateKey key, Head head, + std::uint64_t offset) { + std::string_view whole = head.document; + std::string gathered; + std::uint64_t skip = offset; + if (head.segments > 0) { + // Up to three more bytes than a part, so the cut can find a whole UTF-8 sequence. + std::size_t const wanted = _options.partBytes + 3; + for (std::uint64_t index = 0; index < head.segments && gathered.size() < wanted; ++index) { + std::optional const stored = + co_await _store->get(pointKey(person, key, segmentPoint(key, head.revision, index))); + std::string segment; + if (!stored || glz::read(segment, *stored)) { + throw detail::MissingSegment{"a table's stored state is missing segment " + std::to_string(index)}; + } + if (skip >= segment.size()) { + skip -= segment.size(); + continue; + } + gathered.append(segment, static_cast(skip)); + skip = 0; + } + whole = gathered; + skip = 0; + } + std::string_view const rest = + whole.substr(std::min(static_cast(skip), whole.size())); + co_return std::string{rest.substr(0, detail::utf8Prefix(rest, _options.partBytes))}; + } + + /// @brief The whole document a head names. + /// @throws std::runtime_error when a segment the head names is missing or does not read. + ::core::async::Task readWhole(std::string person, table::TableStateKey key, Head head) { + std::string text; + while (text.size() < head.size()) { + std::string const part = co_await readRange(person, key, head, text.size()); + if (part.empty()) { + throw std::runtime_error{"a table's stored state ended before its size"}; + } + text += part; + } + co_return text; + } + + /// @brief Whether @p expected holds over @p head: empty always; `kNoDocument` when nothing is stored; otherwise + /// when the stored document has that revision. + [[nodiscard]] static bool holds(std::string const& expected, Head const& head); + + /// @brief Removes a revision's segments; a removal the store does not make is left to a later save. + ::core::async::Task removeSegments(std::string person, table::TableStateKey key, std::string revision, + std::uint64_t segments) { + for (std::uint64_t index = 0; index < segments; ++index) { + static_cast(co_await _store->remove(pointKey(person, key, segmentPoint(key, revision, index)))); + } + } + + /// @brief Removes the segments a stopped save left: those its intent names and the head does not. + ::core::async::Task cleanUp(std::string person, table::TableStateKey key) { + std::optional const stored = co_await _store->get(pointKey(person, key, pendingPoint(key))); + if (!stored) { + co_return; + } + detail::StoredStateIntent intent; + if (!glz::read(intent, *stored)) { + Head const head = co_await readHead(person, key); + std::string const kept = head.found && head.segments > 0 ? head.revision : std::string{}; + if (!intent.revision.empty() && intent.revision != kept) { + co_await removeSegments(person, key, intent.revision, intent.segments); + } + if (!intent.previous.empty() && intent.previous != kept) { + co_await removeSegments(person, key, intent.previous, intent.previousSegments); + } + } + static_cast(co_await _store->remove(pointKey(person, key, pendingPoint(key)))); + } + + /// @brief The person's usage; 0 when the entry is absent or does not read. + ::core::async::Task usage(std::string person) { + std::optional const stored = co_await _store->get(usageKey(person)); + detail::StoredStateUsage entry; + if (!stored || glz::read(entry, *stored)) { + co_return 0; + } + co_return entry.bytes; + } + + /// @brief Writes the person's usage. A refused write leaves the old total; the document is stored either way. + ::core::async::Task setUsage(std::string person, std::uint64_t bytes) { + static_cast(co_await _store->set(usageKey(person), write(detail::StoredStateUsage{.bytes = bytes}))); + } + + /// @brief Stores a whole document under the `expected` rule and the quota, in the order the class describes. The + /// shared views, kept with no person, count as one more account. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): a revision token, then a document, at every call. + ::core::async::Task commit(std::string person, table::TableStateKey key, std::string expected, + std::string text) { + if (auto const error = glz::validate_json(text)) { + throw std::invalid_argument{"a table's state is JSON text: " + glz::format_error(error, text)}; + } + co_await cleanUp(person, key); + Head const head = co_await readHead(person, key); + if (!holds(expected, head)) { + co_return table::SaveResult{ + .outcome = table::SaveOutcome::Conflict, .revision = head.revision, .reason = {}}; + } + // The shared views, the person "", are an account of their own under the same quota. + bool const counted = _options.maxBytesPerPerson.has_value(); + std::uint64_t const replaced = head.found ? head.counted : 0; + std::uint64_t const added = text.size(); + std::uint64_t used = 0; + if (counted) { + used = co_await usage(person); + // used - replaced + added > quota, written so that nothing wraps. + if (used + added > static_cast(*_options.maxBytesPerPerson) + replaced) { + co_return table::SaveResult{.outcome = table::SaveOutcome::Refused, + .revision = head.revision, + .reason = "over the table-state quota"}; + } + } + std::string const revision = detail::tableStateRevision(head.revision, text); + bool const segmented = text.size() > _options.segmentBytes; + std::vector const segments = + segmented ? detail::segmentText(text, _options.segmentBytes) : std::vector{}; + bool const replacesSegments = head.found && head.segments > 0; + bool const intent = segmented || replacesSegments; + if (intent) { + co_await setOrThrow( + pointKey(person, key, pendingPoint(key)), + write(detail::StoredStateIntent{.revision = revision, + .segments = segments.size(), + .previous = replacesSegments ? head.revision : std::string{}, + .previousSegments = replacesSegments ? head.segments : 0})); + } + for (std::size_t index = 0; index < segments.size(); ++index) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < segments.size() by the loop + co_await setOrThrow(pointKey(person, key, segmentPoint(key, revision, index)), segments[index]); + } + detail::StoredStateHead entry{.key = key, .revision = revision, .document = {}, .segments = {}, .bytes = {}}; + if (segmented) { + entry.segments = segments.size(); + entry.bytes = added; + } else { + entry.document = glz::raw_json{text}; + entry.bytes = added; // the text's own length: reading the document back drops surrounding whitespace + } + co_await setOrThrow(pointKey(person, key, key.part), write(entry)); + if (replacesSegments) { + co_await removeSegments(person, key, head.revision, head.segments); + } + if (intent) { + static_cast(co_await _store->remove(pointKey(person, key, pendingPoint(key)))); + } + if (counted) { + // A usage below the replaced size undercounts (a quota set over existing states, two instances racing, a + // refused usage write): what remains of it is counted as nothing rather than wrapping. + co_await setUsage(person, (used > replaced ? used - replaced : 0) + added); + } + co_return table::SaveResult{.outcome = table::SaveOutcome::Saved, .revision = revision, .reason = {}}; + } + + std::shared_ptr _store; + TableStateOptions _options; + std::shared_ptr _shared; +}; + +} // namespace morph::ui + +/// @cond detail +// The traits the registration macros write, without their static-init registrars: registerTableState registers. +// NOLINTBEGIN(misc-const-correctness): inside the macros' codec bodies. +BRIDGE_DETAIL_MODEL_TRAITS_ONLY_BODY(morph::ui::TableStateModel, "morph.tableState") +BRIDGE_DETAIL_ACTION_TRAITS_ONLY_BODY(morph::ui::TableStateModel, morph::ui::TableStateLoad, + morph::ui::TableStateLoaded, "load", ::morph::model::Loggable::No) +BRIDGE_DETAIL_ACTION_TRAITS_ONLY_BODY(morph::ui::TableStateModel, morph::ui::TableStateRead, + morph::ui::TableStateChunk, "read", ::morph::model::Loggable::No) +BRIDGE_DETAIL_ACTION_TRAITS_ONLY_BODY(morph::ui::TableStateModel, morph::ui::TableStateSave, + morph::ui::TableStateSaved, "save", ::morph::model::Loggable::No) +BRIDGE_DETAIL_ACTION_TRAITS_ONLY_BODY(morph::ui::TableStateModel, morph::ui::TableStateRemove, + morph::ui::TableStateRemoved, "remove", ::morph::model::Loggable::No) +BRIDGE_DETAIL_ACTION_TRAITS_ONLY_BODY(morph::ui::TableStateModel, morph::ui::TableStatePublish, + morph::ui::TableStateSaved, "publish", ::morph::model::Loggable::No) +// NOLINTEND(misc-const-correctness) +/// @endcond + +namespace morph::ui { + +/// @brief Registers the table-state model and its five actions, with a factory that gives every instance @p store. +/// +/// Nothing registers it at static initialisation: a server that offers table state calls this once, before it serves, +/// with the dispatcher and registry its `RemoteServer` uses. A deployment's authoriser then admits +/// `morph.tableState` and its actions `load`, `read`, `save` and `remove` for every signed-in principal; the model +/// keeps each person to their own entries. `publish` writes the views shared with everyone, so the authoriser admits +/// it for those who may publish. +/// +/// The actions declare no effects: what they change is no record a screen shows, and a mounted table reads its state +/// when it mounts, not as it changes elsewhere. +/// +/// Every instance it makes shares one set of per-key locks, so two writes of one key on this server run one after +/// the other and the last wins whole; and one set of uploads in parts, at most `kMaxTableStateUploads` per person. +/// Servers share nothing, and a preferences store has no conditional write, so two saves of one key that reach two +/// servers in the same moment can interleave. Two saves of one person's different keys can both pass the quota: each +/// such race can leave one document uncounted, so the quota is overshot by one document per race. +/// @param store Where states are kept: the application's preferences store. +/// @param dispatcher The server's action dispatcher. +/// @param registry The server's model registry. +/// @param options The bounds and the quota. +MORPH_API void registerTableState(std::shared_ptr store, + model::detail::ActionDispatcher& dispatcher, + model::detail::ModelRegistryFactory& registry, TableStateOptions options = {}); + +} // namespace morph::ui diff --git a/include/morph/ui/table_views.hpp b/include/morph/ui/table_views.hpp new file mode 100644 index 000000000..565f742ee --- /dev/null +++ b/include/morph/ui/table_views.hpp @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file table_views.hpp +/// @brief A table's saved views: the user's own and the shared ones, loaded with the table's state and saved under +/// the store's revision rule, so two windows saving at once lose neither's view. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "table_state.hpp" + +namespace morph::ui { + +/// @brief The saved views of one table: the parts `"views"` (the user's own) and `"shared"` (published for everyone) +/// of its persisted state. +/// +/// `load` goes through the session's `TableStates`, so the views join the turn's one batched load with the screen's +/// `state` keys, and a second mount reads them from the kept copies with no call. A change applies an operation to +/// the views loaded and saves the whole document through the store, expecting the revision loaded, or `kNoDocument` +/// when nothing was: a window that saves over another window's newer document gets `Conflict`, reads the document +/// again, applies its operation to that one and saves once more, so neither window's view is lost. A table that is +/// mounted does not follow saves made elsewhere until its next conflict or mount. +/// +/// Every member is called on the session's owner, where every completion it returns is delivered. The object may go +/// before a change it started completes; the change still completes. +class MORPH_API TableViews { +public: + /// @brief What a load or a change answers: nothing, or the words a status line shows. + using Result = std::expected; + + /// @brief The views of the table @p key names. + /// @param states The session's table states; must outlive the object and every change it starts. + /// @param key The table's state key; its `part` is ignored. + /// @param owner The session's owner, where completions are delivered. Borrowed: it must outlive them. + TableViews(TableStates& states, table::TableStateKey const& key, exec::IExecutor& owner) + : _held{std::make_shared( + Held{.states = &states, + .owner = &owner, + .own = Part{.key = partOf(key, "views"), .document = {}, .revision = {}}, + .shared = Part{.key = partOf(key, "shared"), .document = {}, .revision = {}}})} {} + + /// @brief Loads the user's views, and the shared ones when the store shares. + /// @return Completes when every part is read; the reason a part could not be read otherwise. + [[nodiscard]] async::Completion load(); + + /// @brief The user's own views as last loaded or saved. + /// @return The document. + [[nodiscard]] table::ViewsDocument const& own() const noexcept { return _held->own.document; } + + /// @brief The shared views as last loaded or published. + /// @return The document; empty when the store does not share. + [[nodiscard]] table::ViewsDocument const& shared() const noexcept { return _held->shared.document; } + + /// @brief Whether the store keeps a shared part for everyone. + /// @return `states.store().shares()`. + [[nodiscard]] bool shares() const { return _held->states->store().shares(); } + + /// @brief Applies @p operation to the user's views and saves them. + /// + /// An operation that does not apply answers at once and saves nothing. A save that meets another window's + /// document reads it again and saves the operation over it once more: with that document's revision, or with an + /// empty `expected` when the store holds nothing, which a store that does not honour `kNoDocument` answers with + /// `Conflict`. A second conflict answers "Views could not be saved: another window changed them at the same + /// time". + /// @param operation The operation. + /// @return Nothing once saved; the words a status line shows otherwise. + [[nodiscard]] async::Completion change(table::ViewOperation operation) { + return start(table::ViewsPart::Own, std::move(operation)); + } + + /// @brief Applies @p operation to the shared views through the store's `publish`, under the same rule as `change`. + /// @param operation The operation. + /// @return Nothing once published; otherwise the words a status line shows, "This view could not be published:" + /// and the reason. + [[nodiscard]] async::Completion publish(table::ViewOperation operation) { + return start(table::ViewsPart::Shared, std::move(operation)); + } + + /// @brief Saves @p view among the user's views: an `AddView`, or a `ReplaceView` when a view of its name is in + /// the document the operation is applied to, which after a `Conflict` is the one stored now. + /// @param view The view. + /// @return Nothing once saved; the words a status line shows otherwise. + [[nodiscard]] async::Completion saveView(table::SavedView view) { + return start(table::ViewsPart::Own, table::AddView{view}, view); + } + + /// @brief Publishes @p view among the shared views, as `saveView` saves one among the user's. + /// @param view The view. + /// @return Nothing once published; otherwise "This view could not be published:" and the reason. + [[nodiscard]] async::Completion publishView(table::SavedView view) { + return start(table::ViewsPart::Shared, table::AddView{view}, view); + } + + /// @brief One of the user's own views. + /// @param name The view's name. + /// @return It, as last loaded or saved; null when there is none of that name. + [[nodiscard]] table::SavedView const* ownView(std::string_view name) const { return find(own(), name); } + + /// @brief One of the shared views. + /// @param name The view's name. + /// @return It, as last loaded or published; null when there is none of that name. + [[nodiscard]] table::SavedView const* sharedView(std::string_view name) const { return find(shared(), name); } + +private: + [[nodiscard]] static table::SavedView const* find(table::ViewsDocument const& document, std::string_view name); + + // What a failure to change @p part says: a publish's failure is said as one, whatever stopped it. + [[nodiscard]] static std::string failed(table::ViewsPart part, std::string const& reason); + + // The words of an exception a store's completion failed with. + [[nodiscard]] static std::string reasonOf(std::exception_ptr const& error); + + // One part's key, the document read or saved last, and its revision; nothing when nothing is stored. + struct Part { + table::TableStateKey key; + table::ViewsDocument document; + std::optional revision; + }; + + // What a change still running needs after the object is gone. + struct Held { + TableStates* states = nullptr; + exec::IExecutor* owner = nullptr; + Part own; + Part shared; + }; + + // A load waiting for its parts. + struct Settle { + async::Completion::Promise promise; + int waiting = 0; + std::string failure; + }; + + // One operation being saved to one part. + struct Saving { + std::shared_ptr held; + table::ViewsPart part = table::ViewsPart::Own; + table::ViewOperation operation; + async::Completion::Promise promise; + bool retried = false; + /// A view added or replaced, decided at each attempt against the document it is applied to. + std::optional upsert; + }; + + [[nodiscard]] static table::TableStateKey partOf(table::TableStateKey key, std::string part); + + [[nodiscard]] static Part& partIn(Held& held, table::ViewsPart part) { + return part == table::ViewsPart::Own ? held.own : held.shared; + } + + // Takes what the store holds for a part: its document and revision, or none. + [[nodiscard]] static std::optional take(Part& part, + std::optional const& stored); + + static void loadPart(std::shared_ptr const& held, Part Held::* member, + std::shared_ptr const& settle); + + [[nodiscard]] async::Completion start(table::ViewsPart part, table::ViewOperation operation, + std::optional upsert = std::nullopt); + + // Applies the operation to the part as held and sends it, expecting @p expected. + static void attempt(std::shared_ptr const& saving, std::string expected); + + static void answered(std::shared_ptr const& saving, table::ViewsDocument document, std::string json, + table::SaveResult const& result); + + // Reads the part again from the store itself, since the session's kept copy is the one that conflicted, keeps + // what it read, and sends the operation once more over it. + static void reload(std::shared_ptr const& saving); + + std::shared_ptr _held; +}; + +/// @brief The state a table starts from at mount, given its user's own views. +/// +/// With no stored state, the default view's layout, sort and filters, and its name as the state's `view`. With a +/// stored state and `defaultOnMount`, the stored state with the default view's sort and filters in place of its own; +/// its layout and `view` stay. Otherwise, and whenever the default names no view, the stored state as it is. The +/// result is fitted to the table as a stored state is. +/// @param stored The stored state; none when nothing is stored. +/// @param own The user's own views. +/// @return The state to apply; none when there is nothing to apply. +[[nodiscard]] MORPH_API std::optional stateAtMount(std::optional stored, + table::ViewsDocument const& own); + +} // namespace morph::ui diff --git a/include/morph/ui/testing/backend_conformance.hpp b/include/morph/ui/testing/backend_conformance.hpp index 0605206e8..7765eafa4 100644 --- a/include/morph/ui/testing/backend_conformance.hpp +++ b/include/morph/ui/testing/backend_conformance.hpp @@ -148,10 +148,12 @@ class ConformanceProbe { /// @param click How the click is modified. virtual void clickRow(Widget& table, std::size_t row, RowClick click) = 0; - /// @brief Clicks a column's header of a table as a user would. + /// @brief Clicks a column's header of a table as a user would, with `Shift` held for `HeaderClick::Shift`. /// @param table The table. /// @param column The column's index among the table's columns. - virtual void clickHeader(Widget& table, std::size_t column) = 0; + /// @param click Whether `Shift` is held. + // NOLINTNEXTLINE(google-default-arguments): every probe takes the same default, and the cases rely on it. + virtual void clickHeader(Widget& table, std::size_t column, HeaderClick click = HeaderClick::Plain) = 0; /// @brief The rows a table shows as selected. /// @param table The table. @@ -229,6 +231,90 @@ class ConformanceProbe { static_cast(spotlight); return nullptr; } + + /// @brief Opens a header's menu, or the table's menu, as a user would (a right click on the header, or the `⋯` + /// button), reads its entries, and closes it. + /// @param table The table. + /// @param column The column, or none for the table's menu. + /// @return The entries of the top level; none when the probe reads none. + [[nodiscard]] virtual std::vector headerMenu(Widget& table, std::optional column) { + static_cast(table); + static_cast(column); + return {}; + } + + /// @brief Opens a header's menu, or the table's menu, and chooses an entry as a user would, opening each submenu + /// on the path first. + /// @param table The table. + /// @param column The column, or none for the table's menu. + /// @param path The entry's index at each level, from the top. + virtual void chooseHeaderMenuEntry(Widget& table, std::optional column, + std::vector const& path) { + static_cast(table); + static_cast(column); + static_cast(path); + } + + /// @brief Moves a column as a user would: dragging its header, or the keys on a focused header. + /// @param table The table. + /// @param column The column's index among the table's columns. + /// @param position Its new place among the visible columns. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`column`, `position`): the column to move then where it goes, as the backend's `moveColumn` reads + virtual void moveColumn(Widget& table, std::size_t column, std::size_t position) { + static_cast(table); + static_cast(column); + static_cast(position); + } + + /// @brief The text a column's header draws: its label and its sort mark. + /// @param table The table. + /// @param column The column's index among the table's columns. + /// @return The text; empty when the probe reads none. + [[nodiscard]] virtual std::string headerText(Widget const& table, std::size_t column) { + static_cast(table); + static_cast(column); + return {}; + } + + /// @brief What assistive technology reads as a column header's name. + /// @param table The table. + /// @param column The column's index among the table's columns. + /// @return The name; empty when the probe reads none. + [[nodiscard]] virtual std::string headerName(Widget const& table, std::size_t column) { + static_cast(table); + static_cast(column); + return {}; + } + + /// @brief What assistive technology reads as a column header's description. + /// @param table The table. + /// @param column The column's index among the table's columns. + /// @return The description; empty when it has none or the probe reads none. + [[nodiscard]] virtual std::string headerDescription(Widget const& table, std::size_t column) { + static_cast(table); + static_cast(column); + return {}; + } + + /// @brief Presses a filterable column's filter button in its header, as a user would. + /// @param table The table. + /// @param column The column's index among the table's columns. + virtual void pressFilter(Widget& table, std::size_t column) { + static_cast(table); + static_cast(column); + } + + /// @brief Presses a column group's filter button in the group row, as a user would. + /// @param table The table. + /// @param group The group's index among the table's column groups. + virtual void pressGroupFilter(Widget& table, std::size_t group) { + static_cast(table); + static_cast(group); + } + + /// @brief What the backend's `copyText` last put on the clipboard, read back from where it wrote it. + /// @return The text; empty before any, or when the probe reads none. + [[nodiscard]] virtual std::string clipboardText() { return {}; } }; /// @brief One scripted case. @@ -1010,9 +1096,9 @@ struct Entry { .onSelectionChange = note("Table onSelectionChange"), .sort = [odd] { - return odd() ? std::optional{TableSort{ + return odd() ? std::vector{TableSort{ .column = 0, .direction = SortDirection::Descending}} - : std::nullopt; + : std::vector{}; }, .onSort = note("Table onSort"), .onActivate = note("Table onActivate")}, @@ -2825,22 +2911,22 @@ struct SelectionReport { /// @return `nullopt`, or what went wrong. [[nodiscard]] inline std::optional headerClickAsksToSort(ConformanceProbe& probe) { reactive::Signal> const rows{probe.runtime(), fourEntries()}; - reactive::Signal> shown{probe.runtime(), std::nullopt}; + reactive::Signal> shown{probe.runtime(), {}}; std::vector asked; - Mounted const view{probe.runtime(), probe.backend(), - ui::table( - {{.label = "Name", .sortable = true}, {.label = "Id"}}, [&rows] { return rows.get(); }, - [](Entry const& entry) { return Key{entry.id}; }, - [](reactive::Signal const& entry) { - return std::vector{ - ui::text({.text = [&entry] { return entry.get().label; }}), - ui::text({.text = [&entry] { return std::to_string(entry.get().id); }})}; - }, - TableOptions{.sort = [&shown] { return shown.get(); }, - .onSort = [&asked](std::size_t column) { asked.push_back(column); }})}; + Mounted const view{ + probe.runtime(), probe.backend(), + ui::table( + {{.label = "Name", .sortable = true}, {.label = "Id"}}, [&rows] { return rows.get(); }, + [](Entry const& entry) { return Key{entry.id}; }, + [](reactive::Signal const& entry) { + return std::vector{ui::text({.text = [&entry] { return entry.get().label; }}), + ui::text({.text = [&entry] { return std::to_string(entry.get().id); }})}; + }, + TableOptions{.sort = [&shown] { return shown.get(); }, + .onSort = [&asked](std::size_t column, HeaderClick) { asked.push_back(column); }})}; probe.settle(); Checks checks; - shown.set(TableSort{.column = 0, .direction = SortDirection::Descending}); + shown.set({TableSort{.column = 0, .direction = SortDirection::Descending}}); probe.settle(); checks.that(asked.empty(), "showing a sort asked to sort"); probe.clickHeader(view.root(), 0); @@ -4417,6 +4503,265 @@ struct MinColumnGridSpec { return checks.result(); } +/// @brief A table of entries under the given columns, each cell a Text of the entry's label and its column's index. +/// @param rows The entries; must outlive the node's mounts. +/// @param columns The columns. +/// @param options Sorting, menus and the rest. +/// @return The node. +[[nodiscard]] inline Node columnsTable(reactive::Signal> const& rows, + std::vector columns, TableOptions options) { + std::size_t const count = columns.size(); + return ui::table( + std::move(columns), [&rows] { return rows.get(); }, [](Entry const& entry) { return Key{entry.id}; }, + [count](reactive::Signal const& entry) { + std::vector cells; + cells.reserve(count); + for (std::size_t column = 0; column < count; ++column) { + cells.push_back( + ui::text({.text = [&entry, column] { return entry.get().label + std::to_string(column); }})); + } + return cells; + }, + std::move(options)); +} + +/// @brief A header click as a failure message shows it. +/// @param clicks The column and the kind of click of each report. +/// @return Such as `1:Shift,0:Plain`. +[[nodiscard]] inline std::string headerClicks(std::vector> const& clicks) { + std::string text; + for (auto const& [column, click] : clicks) { + text += + (text.empty() ? "" : ",") + std::to_string(column) + (click == HeaderClick::Shift ? ":Shift" : ":Plain"); + } + return text; +} + +/// @brief Case: a `Shift`-click on a sortable header reports `Shift`, and a plain click `Plain`. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional shiftClickReportsShift(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + std::vector> clicks; + Mounted const view{probe.runtime(), probe.backend(), + columnsTable(rows, {{.label = "Name", .sortable = true}, {.label = "Mass", .sortable = true}}, + {.onSort = [&clicks](std::size_t column, HeaderClick click) { + clicks.emplace_back(column, click); + }})}; + probe.settle(); + probe.clickHeader(view.root(), 1, HeaderClick::Shift); + probe.settle(); + probe.clickHeader(view.root(), 0, HeaderClick::Plain); + probe.settle(); + Checks checks; + checks.text("the header clicks reported", "1:Shift,0:Plain", headerClicks(clicks)); + return checks.result(); +} + +/// @brief Case: a chain of three keys marks every header with its direction and its place, and describes it to +/// assistive technology; a chain of one key marks its header with the direction alone, and a header not in +/// the chain has no description. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional sortChainMarksHeaders(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + reactive::Signal> chain{probe.runtime(), + {TableSort{.column = 1, .direction = SortDirection::Descending}, + TableSort{.column = 0, .direction = SortDirection::Ascending}, + TableSort{.column = 2, .direction = SortDirection::Ascending}}}; + Mounted const view{probe.runtime(), probe.backend(), + columnsTable(rows, + {{.label = "Name", .sortable = true}, + {.label = "Mass", .sortable = true}, + {.label = "Site", .sortable = true}}, + {.sort = [&chain] { return chain.get(); }})}; + probe.settle(); + Checks checks; + checks.text("Name's header in a chain of three", "Name \u25B22", probe.headerText(view.root(), 0)); + checks.text("Mass's header in a chain of three", "Mass \u25BC1", probe.headerText(view.root(), 1)); + checks.text("Site's header in a chain of three", "Site \u25B23", probe.headerText(view.root(), 2)); + checks.text("Name's description in a chain of three", "sorted ascending, key 2 of 3", + probe.headerDescription(view.root(), 0)); + chain.set({TableSort{.column = 0, .direction = SortDirection::Descending}}); + probe.settle(); + checks.text("Name's header in a chain of one", "Name \u25BC", probe.headerText(view.root(), 0)); + checks.text("Name's description in a chain of one", "sorted descending", probe.headerDescription(view.root(), 0)); + checks.text("Mass's description out of the chain", "", probe.headerDescription(view.root(), 1)); + return checks.result(); +} + +/// @brief Menus that report what was chosen: a header's `Sort ascending`, a separator and `Hide column`, and the +/// table's `Columns…`. +/// @param chosen Where each choice is recorded, as its column (`-` for none) and path. +/// @return The options' `menu` and `onMenu`. +[[nodiscard]] inline TableOptions menuOptions(std::vector& chosen) { + TableOptions options; + options.menu = [](std::optional column) { + if (!column) { + return std::vector{{.label = "Columns\u2026"}}; + } + return std::vector{{.label = "Sort ascending"}, {.separator = true}, {.label = "Hide column"}}; + }; + options.onMenu = [&chosen](std::optional column, std::vector const& path) { + std::string text = column ? std::to_string(*column) : std::string{"-"}; + for (std::size_t const index : path) { + text += "/" + std::to_string(index); + } + chosen.push_back(std::move(text)); + }; + return options; +} + +/// @brief Case: a header's menu shows its entries, and choosing one reports the header's column and the entry's path. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional headerMenuReportsColumnAndPath(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + std::vector chosen; + Mounted const view{ + probe.runtime(), probe.backend(), + columnsTable(rows, {{.label = "Name"}, {.label = "Mass"}, {.label = "Site"}}, menuOptions(chosen))}; + probe.settle(); + Checks checks; + std::vector const entries = probe.headerMenu(view.root(), 1); + checks.that(entries.size() == 3 && entries.at(0).label == "Sort ascending" && entries.at(1).separator && + entries.at(2).label == "Hide column", + "Mass's menu shows " + std::to_string(entries.size()) + + " entries, not Sort ascending, a separator and Hide column"); + probe.settle(); + probe.chooseHeaderMenuEntry(view.root(), 1, {2}); + probe.settle(); + checks.that(chosen == std::vector{"1/2"}, + "choosing Hide column in Mass's menu reported " + std::to_string(chosen.size()) + + " choices, not column 1 and path [2] once" + (chosen.empty() ? "" : ": " + chosen.front())); + return checks.result(); +} + +/// @brief Case: the table's menu is the menu with no column: choosing its entry reports none and the path. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional tableMenuHasNoColumn(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + std::vector chosen; + Mounted const view{probe.runtime(), probe.backend(), + columnsTable(rows, {{.label = "Name"}, {.label = "Mass"}}, menuOptions(chosen))}; + probe.settle(); + probe.chooseHeaderMenuEntry(view.root(), std::nullopt, {0}); + probe.settle(); + Checks checks; + checks.that(chosen == std::vector{"-/0"}, + "choosing the table menu's first entry reported " + std::to_string(chosen.size()) + + " choices, not no column and path [0] once" + (chosen.empty() ? "" : ": " + chosen.front())); + return checks.result(); +} + +/// @brief Case: a column the user moves reports its column and its new place. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional columnMoveReportsPlace(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + std::vector> moves; + Mounted const view{probe.runtime(), probe.backend(), + columnsTable(rows, {{.label = "Name"}, {.label = "Mass"}, {.label = "Site"}}, + {.onColumnMove = [&moves](std::size_t column, std::size_t position) { + moves.emplace_back(column, position); + }})}; + probe.settle(); + probe.moveColumn(view.root(), 0, 1); + probe.settle(); + Checks checks; + checks.that( + moves == std::vector>{{0, 1}}, + "moving Name to place 1 reported " + std::to_string(moves.size()) + " moves, not column 0 to place 1 once" + + (moves.empty() + ? "" + : ": " + std::to_string(moves.front().first) + " to " + std::to_string(moves.front().second))); + return checks.result(); +} + +/// @brief Case: a filtered column's header is named so for assistive technology, and an unfiltered one by its label. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional filteredHeaderIsNamed(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + Mounted const view{ + probe.runtime(), probe.backend(), + columnsTable(rows, {{.label = "Name", .filterable = true}, {.label = "Mass", .filterable = true}}, + {.onFilter = [](std::size_t) {}, .filtered = std::vector{0}})}; + probe.settle(); + Checks checks; + checks.text("the filtered header's name", "Name, filtered", probe.headerName(view.root(), 0)); + checks.text("the unfiltered header's name", "Mass", probe.headerName(view.root(), 1)); + return checks.result(); +} + +/// @brief Case: a filterable column's filter button reports its column once. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional filterButtonReportsColumn(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + std::vector pressed; + Mounted const view{probe.runtime(), probe.backend(), + columnsTable(rows, {{.label = "Name"}, {.label = "Mass", .filterable = true}}, + {.onFilter = [&pressed](std::size_t column) { pressed.push_back(column); }})}; + probe.settle(); + probe.pressFilter(view.root(), 1); + probe.settle(); + Checks checks; + checks.that( + pressed == std::vector{1}, + "pressing Mass's filter button reported " + std::to_string(pressed.size()) + " presses, not column 1 once"); + return checks.result(); +} + +/// @brief Case: a column group's filter button in the group row reports the group once. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional groupFilterButtonReportsGroup(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + std::vector pressed; + Mounted const view{ + probe.runtime(), probe.backend(), + columnsTable(rows, {{.label = "Name"}, {.label = "Mass"}, {.label = "Site"}}, + {.columnGroups = std::vector{{.label = "Place", .first = 1, .count = 2}}, + .onGroupFilter = [&pressed](std::size_t group) { pressed.push_back(group); }})}; + probe.settle(); + probe.pressGroupFilter(view.root(), 0); + probe.settle(); + Checks checks; + checks.that( + pressed == std::vector{0}, + "pressing Place's filter button reported " + std::to_string(pressed.size()) + " presses, not group 0 once"); + return checks.result(); +} + +/// @brief Case: `Ctrl+C` on a focused table reports a copy once. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional ctrlCReportsCopy(ConformanceProbe& probe) { + reactive::Signal> const rows{probe.runtime(), fourEntries()}; + int copies = 0; + Mounted const view{probe.runtime(), probe.backend(), + columnsTable(rows, {{.label = "Name"}}, {.onCopy = [&copies] { ++copies; }})}; + probe.settle(); + probe.press(view.root(), "Ctrl+C"); + probe.settle(); + Checks checks; + checks.that(copies == 1, "Ctrl+C on the table asked to copy " + std::to_string(copies) + " times, not once"); + return checks.result(); +} + +/// @brief Case: `copyText` puts its text on the clipboard, where the probe reads it back. +/// @param probe The backend under test. +/// @return `nullopt`, or what went wrong. +[[nodiscard]] inline std::optional copyTextReachesClipboard(ConformanceProbe& probe) { + Checks checks; + checks.that(probe.backend().copyText("a\tb"), "copyText reported no clipboard"); + probe.settle(); + checks.text("the clipboard", "a\tb", probe.clipboardText()); + return checks.result(); +} + } // namespace detail /// @brief The spotlight's cases, which every backend that runs guided tours passes. They are their own list, so a @@ -4555,7 +4900,7 @@ struct MinColumnGridSpec { /// loops over these with its own `ConformanceProbe`. /// @return The cases. [[nodiscard]] inline std::span conformanceCases() { - static std::array const cases{{ + static std::array const cases{{ {.name = "a Text shows its constant text", .run = detail::textShowsItsText}, {.name = "a bound Text updates once per batch and not for an equal write", .run = detail::boundTextUpdatesOncePerChange}, @@ -4640,6 +4985,21 @@ struct MinColumnGridSpec { {.name = "an unlabelled steps indicator still names its current step", .run = detail::unlabelledStepsNameTheirCurrentStep}, {.name = "a stack told it is the head bar keeps its children", .run = detail::headBarKeepsItsChildren}, + {.name = "table: a Shift-click on a sortable header reports Shift, a plain click Plain", + .run = detail::shiftClickReportsShift}, + {.name = "table: a chain of three keys marks every header with its place", + .run = detail::sortChainMarksHeaders}, + {.name = "table: a header's menu shows its entries and choosing one reports the column and the path", + .run = detail::headerMenuReportsColumnAndPath}, + {.name = "table: the table's menu is the menu with no column", .run = detail::tableMenuHasNoColumn}, + {.name = "table: a column moved by the user reports its column and new place", + .run = detail::columnMoveReportsPlace}, + {.name = "table: a filtered column's header is named so", .run = detail::filteredHeaderIsNamed}, + {.name = "table: Ctrl+C on a focused table reports a copy", .run = detail::ctrlCReportsCopy}, + {.name = "backend: copyText puts its text on the clipboard", .run = detail::copyTextReachesClipboard}, + {.name = "table: a filterable header's filter button reports its column", + .run = detail::filterButtonReportsColumn}, + {.name = "table: a group's filter button reports the group", .run = detail::groupFilterButtonReportsGroup}, }}; return cases; } diff --git a/include/morph/ui/testing/recording_backend.hpp b/include/morph/ui/testing/recording_backend.hpp index f70469b2b..8f12d685e 100644 --- a/include/morph/ui/testing/recording_backend.hpp +++ b/include/morph/ui/testing/recording_backend.hpp @@ -289,14 +289,20 @@ template return caret == MenuCaret::Down ? "Down" : caret == MenuCaret::UpDown ? "UpDown" : "None"; } -/// @brief A table's sort as the dump shows it: the column's index and the direction, or `none`. -/// @param sort The sort. -/// @return `:Ascending`, `:Descending` or `none`. -[[nodiscard]] inline std::string formatSort(std::optional const& sort) { - if (!sort) { +/// @brief A table's sort chain as the dump shows it: each key's column index and direction, most significant first, +/// or `none`. +/// @param chain The keys. +/// @return Such as `0:Ascending,2:Descending`, or `none` for an empty chain. +[[nodiscard]] inline std::string formatSort(std::vector const& chain) { + if (chain.empty()) { return "none"; } - return std::to_string(sort->column) + (sort->direction == SortDirection::Ascending ? ":Ascending" : ":Descending"); + std::string text; + for (TableSort const& key : chain) { + text += (text.empty() ? "" : ",") + std::to_string(key.column) + + (key.direction == SortDirection::Ascending ? ":Ascending" : ":Descending"); + } + return text; } /// @brief A text role's name. @@ -583,7 +589,11 @@ struct Callbacks { /// @brief From `TableWidget::setOnActivate`. std::function activate; /// @brief From `TableWidget::setOnSort`. - std::function sort; + std::function sort; + /// @brief From `TableWidget::setOnRetry`. + Action retry; + /// @brief From `TableWidget::setOnFocusOut`: called when focus moves from inside the table to outside it. + Action focusOut; /// @brief The drop handler's predicate, from `Widget::setDropHandler`. std::function accepts; /// @brief The drop handler, from `Widget::setDropHandler`. @@ -793,7 +803,36 @@ class RecordStore { /// @throws std::out_of_range for an id that names no live widget. void focus(int widgetId) { _log.push_back("focus " + label(at(widgetId))); - _focused = widgetId; + int const previous = std::exchange(_focused, widgetId); + if (previous == 0 || previous == widgetId) { + return; + } + // Focus that leaves a table and everything inside it tells the table, innermost first. + std::vector> leaving; + for (auto found = _records.find(previous); found != _records.end(); + found = _records.find(found->second.parent)) { + if (found->second.callbacks.focusOut && !within(widgetId, found->first)) { + leaving.push_back(found->second.callbacks.focusOut); + } + } + for (auto const& leave : leaving) { + leave(); + } + } + + /// @brief Whether a widget is a container or lies inside it. + /// @param widgetId The widget. + /// @param container The container. + /// @return `true` when @p container is @p widgetId or one of its ancestors. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`widgetId`, `container`): the widget then its candidate ancestor, as the name reads at each call + [[nodiscard]] bool within(int widgetId, int container) const { + for (auto found = _records.find(widgetId); found != _records.end(); + found = _records.find(found->second.parent)) { + if (found->first == container) { + return true; + } + } + return false; } /// @brief The widget that last took focus. @@ -2243,7 +2282,9 @@ class FakeTable final : public FakeContainer { : FakeContainer{std::move(store), std::move(kind), parent} { this->store().at(id()).onChildDestroyed = [this](int childId) { _rowKeys.erase(childId); + _viewRows.erase(childId); _headings.erase(childId); + std::erase_if(_loads, [childId](auto const& entry) { return entry.first.first == childId; }); remark(); }; } @@ -2265,11 +2306,13 @@ class FakeTable final : public FakeContainer { /// @brief Records property `columns`, each as its escaped caption, a colon and its width, then `;align=` and /// `;valign=` where the column's alignment is not the default (`Start` across, `Center` down), and - /// `;sortable=true` for a sortable column, which `RecordingBackend::clickHeader` reports, and - /// `;wrap=false` for a column that keeps its text cells to one line, and `;shrink=true` for a stretch - /// column that may be narrower than its header. + /// `;sortable=true` for a sortable column, which `RecordingBackend::clickHeader` reports, + /// `;filterable=true` for a column with a filter button, which `RecordingBackend::clickFilter` presses, + /// `;wrap=false` for a column that keeps its text cells to one line, `;shrink=true` for a stretch column + /// that may be narrower than its header, and `;unit=` with the column's unit when it has one. /// @param columns The columns, in order. void setColumns(std::vector const& columns) override { + _columns = columns; _sortable.clear(); for (TableColumn const& column : columns) { _sortable.push_back(column.sortable); @@ -2285,12 +2328,18 @@ class FakeTable final : public FakeContainer { if (column.sortable) { text += ";sortable=true"; } + if (column.filterable) { + text += ";filterable=true"; + } if (!column.wrap) { text += ";wrap=false"; } if (column.shrink) { text += ";shrink=true"; } + if (!column.unit.empty()) { + text += ";unit=" + formatItem(column.unit); + } return text; })); } @@ -2341,7 +2390,8 @@ class FakeTable final : public FakeContainer { return row.has_value() && _headings.contains(*row); } - /// @brief Records the row's property `rowSpans`: `column:rows` pairs joined by commas, `none` for an empty list. + /// @brief Records the row's property `rowSpans`: `column:rows` pairs joined by commas, a span across columns as + /// `column:rowsxcolumns` (`0:2x3`), `none` for an empty list. /// @param row One of this table's rows. /// @param spans The row's effective spans. /// @throws std::logic_error when @p row is not this table's child. @@ -2353,10 +2403,24 @@ class FakeTable final : public FakeContainer { std::string text; for (RowSpan const& span : spans) { text += (text.empty() ? "" : ",") + std::to_string(span.column) + ":" + std::to_string(span.rows); + if (span.columns != 1) { + text += "x" + std::to_string(span.columns); + } } store().set(rowId, "rowSpans", text.empty() ? std::string{"none"} : text); } + /// @brief Records the row's property `summary` (`"true"`). + /// @param row One of this table's rows. + /// @throws std::logic_error when @p row is not this table's child. + void setRowSummary(Widget& row) override { + int const rowId = store().idOf(row); + if (store().at(rowId).parent != id()) { + throw std::logic_error{"RecordingBackend: setRowSummary of a widget that is not this table's row"}; + } + store().set(rowId, "summary", "true"); + } + /// @brief Records the row's property `tone` (`none` for no tone). /// @param row One of this table's rows. /// @param tone The tone, or none. @@ -2367,6 +2431,39 @@ class FakeTable final : public FakeContainer { throw std::logic_error{"RecordingBackend: setRowTone of a widget that is not this table's row"}; } store().set(rowId, "tone", tone ? enumName(*tone) : std::string{"none"}); + if (auto const key = _rowKeys.find(rowId); key != _rowKeys.end()) { + _rowTones.insert_or_assign(key->second, tone ? enumName(*tone) : std::string{"none"}); + } + } + + /// @brief The last tone `setRowTone` set on the row with a key. + /// @param key The row's key. + /// @return The tone's name, `none` for no tone; empty before any. + [[nodiscard]] std::string rowTone(Key const& key) const { + auto const found = _rowTones.find(key); + return found == _rowTones.end() ? std::string{} : found->second; + } + + /// @brief Records the row's marks by the row's key, which `RecordingBackend::rowMarks` reads. + /// @param row One of this table's rows. + /// @param marks The marks. + /// @throws std::logic_error when @p row is not this table's child. + void setRowMarks(Widget& row, RowMarks const& marks) override { + int const rowId = store().idOf(row); + if (store().at(rowId).parent != id()) { + throw std::logic_error{"RecordingBackend: setRowMarks of a widget that is not this table's row"}; + } + if (auto const key = _rowKeys.find(rowId); key != _rowKeys.end()) { + _rowMarks.insert_or_assign(key->second, marks); + } + } + + /// @brief The last marks `setRowMarks` set on the row with a key. + /// @param key The row's key. + /// @return The marks; none before any. + [[nodiscard]] std::optional rowMarks(Key const& key) const { + auto const found = _rowMarks.find(key); + return found == _rowMarks.end() ? std::nullopt : std::optional{found->second}; } /// @brief Records property `selectColumn`. @@ -2392,6 +2489,7 @@ class FakeTable final : public FakeContainer { /// @brief Requests the rows with @p keys, and records property `selection` as the rows it marks. /// @param keys The selected keys. void setSelection(std::vector const& keys) override { + _viewExcept.reset(); _requested = keys; set("selection", marked()); } @@ -2403,23 +2501,288 @@ class FakeTable final : public FakeContainer { remark(); } + /// @brief Marks every row but those of @p except until the next `setSelection`, and records property + /// `selection` as the rows it marks. + /// @param except The keys left out. + void setSelectionView(std::vector const& except) override { + _viewExcept = except; + set("selection", marked()); + } + + /// @brief Stores the handler `RecordingBackend::chooseStatusEntry` calls. + /// @param onStatusEntry The handler. + void setOnStatusEntry(std::function onStatusEntry) override { + _onStatusEntry = std::move(onStatusEntry); + } + + /// @brief The handler `setOnStatusEntry` stored. + /// @return It; empty when none. + [[nodiscard]] std::function const& onStatusEntry() const noexcept { return _onStatusEntry; } + /// @brief Stores the handler `RecordingBackend::selectRows` calls. /// @param onSelectionChange The handler. void setOnSelectionChange(std::function, SelectionChange)> onSelectionChange) override { callbacks().selection = std::move(onSelectionChange); } + /// @brief Stores what `Ctrl+A` calls in place of selecting the rows held. + /// @param onSelectAll The handler; empty to select the rows held. + void setOnSelectAll(std::function onSelectAll) override { _onSelectAll = std::move(onSelectAll); } + + /// @brief The handler `setOnSelectAll` stored. + /// @return It; empty when none. + [[nodiscard]] std::function const& onSelectAll() const noexcept { return _onSelectAll; } + /// @brief Stores the handler `RecordingBackend::activateRow` calls. /// @param onActivate The handler. void setOnActivate(std::function onActivate) override { callbacks().activate = std::move(onActivate); } - /// @brief Records property `sort`: the column's index and direction, or `none`. - /// @param sort The sort shown. - void setSort(std::optional sort) override { set("sort", formatSort(sort)); } + /// @brief Records property `sort`: each key's column index and direction, or `none`. + /// @param chain The sort chain shown. + void setSort(std::vector const& chain) override { + _chain = chain; + set("sort", formatSort(chain)); + } /// @brief Stores the handler `RecordingBackend::clickHeader` calls. /// @param onSort The handler. - void setOnSort(std::function onSort) override { callbacks().sort = std::move(onSort); } + void setOnSort(std::function onSort) override { + callbacks().sort = std::move(onSort); + } + + /// @brief Stores the menus `RecordingBackend::menuOf` reads and `RecordingBackend::chooseMenu` chooses from. + /// @param entries The entries of a column's menu, or the table's. + /// @param onChoose The handler for a chosen entry. + void setMenu(std::function(std::optional)> entries, + std::function, std::vector)> onChoose) override { + _menu = std::move(entries); + _onMenu = std::move(onChoose); + } + + /// @brief Stores the cell menu `RecordingBackend::rightClickCell` opens and `RecordingBackend::chooseCellMenu` + /// chooses from, and whose entries' chords `RecordingBackend::press` runs on the focused cell. + /// @param entries The entries of a cell's menu. + /// @param chosen The handler for a chosen entry. + void setCellMenu(std::function(Key const&, std::size_t)> entries, + std::function const&)> chosen) override { + _cellMenu = std::move(entries); + _cellChosen = std::move(chosen); + } + + /// @brief Stores the chords that ask for the focused cell's entries, which `RecordingBackend::press` checks. + /// @param chords The chords. + void setCellMenuKeys(std::vector const& chords) override { _cellMenuKeys = chords; } + + /// @brief The chords `setCellMenuKeys` gave. + /// @return They; empty before any. + [[nodiscard]] std::vector const& cellMenuKeys() const noexcept { return _cellMenuKeys; } + + /// @brief How many times the cell menu's entries were asked for. + /// @return The count. + [[nodiscard]] std::size_t cellMenuAsks() const noexcept { return _cellMenuAsks; } + + /// @brief Stores the visible columns, which the drivers check a column against. + /// @param visible The visible columns, in layout order. + void setVisibleColumns(std::vector const& visible) override { _visible = visible; } + + /// @brief Stores the handler `RecordingBackend::moveColumn` calls. + /// @param handler The handler. + void setOnColumnMove(std::function handler) override { + _onColumnMove = std::move(handler); + } + + /// @brief Stores the handler `RecordingBackend::resizeColumn` calls. + /// @param handler The handler. + void setOnColumnResize(std::function)> handler) override { + _onColumnResize = std::move(handler); + } + + /// @brief Stores the handler `RecordingBackend::clickFilter` calls. + /// @param handler The handler. + void setOnFilter(std::function handler) override { _onFilter = std::move(handler); } + + /// @brief Records property `filtered`, the columns as a list such as `[0,2]`. + /// @param columns The filtered columns. + void setFiltered(std::vector const& columns) override { + _filtered = columns; + set("filtered", formatList(columns, [](std::size_t column) { return std::to_string(column); })); + } + + /// @brief Records property `columnGroups`, each group as `label:first+count`, such as `[Company:0+3]`, with + /// `;filtered=true` for a filtered group; `:`, `+` and `;` in a label are escaped as well as a list item's + /// characters. + /// @param groups The groups. + void setColumnGroups(std::vector const& groups) override { + _groups = groups; + set("columnGroups", formatList(groups, [](TableColumnGroup const& group) { + std::string const label = escape( + group.label, [](char character) { return std::string_view{"=,[]:+;"}.contains(character); }); + return label + ":" + std::to_string(group.first) + "+" + std::to_string(group.count) + + (group.filtered ? ";filtered=true" : ""); + })); + } + + /// @brief Records the property `bands`: each run as `level:label|unit@first+count`, `;pinned` for a pinned run, + /// joined by commas; `|unit` only for a run with a unit. + /// @param runs The runs. + void setBands(std::vector const& runs) override { + _bands = runs; + set("bands", formatList(runs, [](BandRun const& run) { + std::string const label = escape( + run.label, [](char character) { return std::string_view{"=,[]:+;@|"}.contains(character); }); + return std::to_string(run.level) + ":" + label + (run.unit.empty() ? "" : "|" + run.unit) + "@" + + std::to_string(run.first) + "+" + std::to_string(run.count) + (run.pinned ? ";pinned" : ""); + })); + } + + /// @brief The runs `setBands` last gave. + /// @return They. + [[nodiscard]] std::vector const& bands() const noexcept { return _bands; } + + /// @brief Stores the handler `RecordingBackend::clickGroupFilter` calls. + /// @param handler The handler. + void setOnGroupFilter(std::function handler) override { _onGroupFilter = std::move(handler); } + + /// @brief Stores the handler `RecordingBackend::pressCopy` and `Ctrl+C` call. + /// @param onCopy The handler. + void setOnCopy(std::function onCopy) override { _onCopy = std::move(onCopy); } + + /// @brief Whether a user can reach @p column's header: it is one of the columns and, once the visible columns + /// were told, one of them. + /// @param column The column. + /// @return True when its header is drawn. + [[nodiscard]] bool headerShown(std::size_t column) const { + return column < _columns.size() && (_visible.empty() || std::ranges::find(_visible, column) != _visible.end()); + } + + /// @brief How many columns are visible: as many as were told, or every column before any were. + /// @return The count. + [[nodiscard]] std::size_t visibleCount() const noexcept { + return _visible.empty() ? _columns.size() : _visible.size(); + } + + /// @brief The visible place of @p column: its place among the visible columns, or its index before any were told. + /// @param column The column. + /// @return The place. + [[nodiscard]] std::size_t placeOf(std::size_t column) const { + if (_visible.empty()) { + return column; + } + return static_cast(std::distance(_visible.begin(), std::ranges::find(_visible, column))); + } + + /// @brief The text a column's header draws: its label, then its sort key's mark (`sortMarkText`). + /// @param column The column. + /// @return The text. + [[nodiscard]] std::string headerText(std::size_t column) const { + std::string text = column < _columns.size() ? _columns.at(column).label : std::string{}; + for (std::size_t place = 0; place < _chain.size(); ++place) { + if (_chain.at(place).column == column) { + text += sortMarkText(_chain.at(place).direction, place + 1, _chain.size()); + } + } + return text; + } + + /// @brief A column header's accessible description: its sort key's (`sortDescription`), or empty. + /// @param column The column. + /// @return The description. + [[nodiscard]] std::string headerDescription(std::size_t column) const { + for (std::size_t place = 0; place < _chain.size(); ++place) { + if (_chain.at(place).column == column) { + return sortDescription(_chain.at(place).direction, place + 1, _chain.size()); + } + } + return {}; + } + + /// @brief A column header's accessible name: its label, followed by `, filtered` while it has a filter. + /// @param column The column. + /// @return The name. + [[nodiscard]] std::string headerName(std::size_t column) const { + std::string name = column < _columns.size() ? _columns.at(column).label : std::string{}; + if (column < _columns.size() && _columns.at(column).filterable && + std::ranges::find(_filtered, column) != _filtered.end()) { + name += ", filtered"; + } + return name; + } + + /// @brief The entries of a menu, as `setMenu` gives them. + /// @param column The column, or none for the table's menu. + /// @return The entries; none when the table has no menus. + [[nodiscard]] std::vector menuEntries(std::optional column) const { + return _menu ? _menu(column) : std::vector{}; + } + + /// @brief The entries of a cell's menu, as `setCellMenu` gives them. + /// @param key The cell's row. + /// @param column The cell's column. + /// @return The entries; none when the table has no cell menu. + [[nodiscard]] std::vector cellMenuEntries(Key const& key, std::size_t column) const { + if (!_cellMenu) { + return {}; + } + ++_cellMenuAsks; + return _cellMenu(key, column); + } + + /// @brief The handler `setCellMenu` gave for a chosen entry. + /// @return It; empty when none. + [[nodiscard]] std::function const&)> const& cellChosen() + const { + return _cellChosen; + } + + /// @brief The focused cell's row and column, as `setFocusCell` last placed it, its row by the view index + /// `setRowIndex` gave a current row. + /// @return The cell; none before any `setFocusCell`, or while no current row is at its view row. + [[nodiscard]] std::optional> focusedCellKey() const { + if (!_focusSet) { + return std::nullopt; + } + for (auto const& [rowId, viewRow] : _viewRows) { + if (viewRow != _focusCell.first) { + continue; + } + if (auto const key = _rowKeys.find(rowId); key != _rowKeys.end()) { + return std::pair{key->second, _focusCell.second}; + } + } + return std::nullopt; + } + + /// @brief The handler `setMenu` gave for a chosen entry. + /// @return It; empty when none. + [[nodiscard]] std::function, std::vector)> const& onMenu() const { + return _onMenu; + } + + /// @brief The handler `setOnColumnMove` stored. + /// @return It; empty when none. + [[nodiscard]] std::function const& onColumnMove() const { return _onColumnMove; } + + /// @brief The handler `setOnColumnResize` stored. + /// @return It; empty when none. + [[nodiscard]] std::function)> const& onColumnResize() const { + return _onColumnResize; + } + + /// @brief The handler `setOnFilter` stored. + /// @return It; empty when none. + [[nodiscard]] std::function const& onFilter() const { return _onFilter; } + + /// @brief The handler `setOnGroupFilter` stored. + /// @return It; empty when none. + [[nodiscard]] std::function const& onGroupFilter() const { return _onGroupFilter; } + + /// @brief How many groups `setColumnGroups` gave. + /// @return The count. + [[nodiscard]] std::size_t groupCount() const noexcept { return _groups.size(); } + + /// @brief The handler `setOnCopy` stored. + /// @return It; empty when none. + [[nodiscard]] std::function const& onCopy() const { return _onCopy; } /// @brief Whether the column at @p column is sortable, as `setColumns` gave it. /// @param column The column's index. @@ -2452,6 +2815,400 @@ class FakeTable final : public FakeContainer { } } + /// @brief Records property `status` as `counts|state|retry|message|shown`, each text escaped. + /// @param status The status line. + void setStatus(TableStatus const& status) override { + _status = status; + set("status", formatText(status.counts) + "|" + formatText(status.state) + "|" + formatBool(status.retry) + + "|" + formatText(status.message) + "|" + formatBool(status.shown)); + } + + /// @brief Stores the handler `RecordingBackend::retryTable` calls. + /// @param onRetry The handler. + void setOnRetry(std::function onRetry) override { callbacks().retry = std::move(onRetry); } + + /// @brief Records a cell's load state, which `RecordingBackend::cellLoad` reads, and the row's property + /// `load` (`Loaded`, `Unloaded` or `Failed`). + /// @param row One of this table's rows. + /// @param column The cell's column. + /// @param load The state. + /// @throws std::logic_error when @p row is not this table's child. + void setCellLoad(Widget& row, std::size_t column, CellLoad load) override { + int const rowId = store().idOf(row); + if (store().at(rowId).parent != id()) { + throw std::logic_error{"RecordingBackend: setCellLoad of a widget that is not this table's row"}; + } + _loads.insert_or_assign(std::pair{rowId, column}, load); + store().set(rowId, "load" + std::to_string(column), formatCellLoad(load)); + } + + /// @brief Records a cell's accent, which `RecordingBackend::cellAccent` reads, and the row's property + /// `accent`: the tone's name or `-`, the tooltip, and `invalid` or `valid`, joined by `|`. + /// @param row One of this table's rows. + /// @param column The cell's column. + /// @param accent The accent. + /// @throws std::logic_error when @p row is not this table's child. + void setCellAccent(Widget& row, std::size_t column, CellAccent const& accent) override { + int const rowId = store().idOf(row); + if (store().at(rowId).parent != id()) { + throw std::logic_error{"RecordingBackend: setCellAccent of a widget that is not this table's row"}; + } + _accents.insert_or_assign(std::pair{rowId, column}, accent); + std::string const tone = accent.tone ? std::to_string(static_cast(*accent.tone)) : std::string{"-"}; + store().set(rowId, "accent" + std::to_string(column), + tone + "|" + formatText(accent.tooltip) + "|" + (accent.invalid ? "invalid" : "valid")); + } + + /// @brief Records the column window, which `windowColumns`, `totalWidth` and `pinnedShown` read, and the + /// properties `columnWindow` (the indices, comma-separated), `totalWidth` and `pinnedShown`. + /// @param columns The columns. + /// @param offsets Their offsets. + /// @param widths Their widths. + /// @param totalWidth Every visible column's width together. + /// @param pinned How many of @p columns are pinned. + void setColumnWindow( + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): overrides `Table::setColumnWindow`; the declaration says how its spans are told apart + std::span columns, std::span offsets, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): overrides `Table::setColumnWindow`; the declaration says how its totals are told apart + std::span widths, int totalWidth, std::size_t pinned) override { + static_cast(offsets); + static_cast(widths); + _window = std::vector(columns.begin(), columns.end()); + _windowSet = true; + _totalWidth = totalWidth; + _pinnedShown = pinned; + std::string text; + for (std::size_t const column : columns) { + text += (text.empty() ? "" : ",") + std::to_string(column); + } + set("columnWindow", text); + set("totalWidth", std::to_string(totalWidth)); + set("pinnedShown", std::to_string(pinned)); + } + + /// @brief Stores the handler `RecordingBackend::scrollTableColumns` calls. + /// @param handler The handler. + void setOnHorizontalRange(std::function handler) override { _onHorizontal = std::move(handler); } + + /// @brief Records property `horizontalOffset`, which `RecordingBackend::horizontalOffset` reads. + /// @param scrollX The offset. + void setHorizontalOffset(int scrollX) override { + _horizontalOffset = scrollX; + set("horizontalOffset", std::to_string(scrollX)); + } + + /// @brief Stores the handler `RecordingBackend::selectTableRange` calls. + /// @param handler The handler. + void setOnSelectRange(std::function handler) override { + _onSelectRange = std::move(handler); + } + + /// @brief Records property `focusCell` as `:`, which `RecordingBackend::focusCell` reads, and adds + /// the cell to the ones `RecordingBackend::focusCells` lists, and the key of the row at that view row now + /// to the ones `RecordingBackend::focusKeys` lists. + /// @param viewRow The row. + /// @param column The column. + void setFocusCell(std::size_t viewRow, std::size_t column) override { + _focusCell = {viewRow, column}; + _focusSet = true; + _focusCells.emplace_back(viewRow, column); + std::optional named; + for (int const child : store().at(id()).children) { + auto const& props = store().at(child).props; + auto const found = props.find("viewRow"); + auto const key = _rowKeys.find(child); + if (found != props.end() && found->second == std::to_string(viewRow) && key != _rowKeys.end()) { + named = key->second; + } + } + _focusKeys.push_back(std::move(named)); + set("focusCell", std::to_string(viewRow) + ":" + std::to_string(column)); + } + + /// @brief Stores the handler `RecordingBackend::measureColumn` calls. + /// @param handler The handler. + void setOnColumnMeasured(std::function handler) override { + _onMeasured = std::move(handler); + } + + /// @brief Stores the handler `RecordingBackend::focusMove` calls. + /// @param handler The handler. + void setOnFocusMove(std::function handler) override { _onFocusMove = std::move(handler); } + + /// @brief Stores the handler `RecordingBackend::typeInto` calls. + /// @param onText The handler. + void setOnText(std::function onText) override { _onText = std::move(onText); } + + /// @brief The handler `setOnText` stored. + /// @return It; empty when none. + [[nodiscard]] std::function const& onText() const noexcept { return _onText; } + + /// @brief Stores the handler `RecordingBackend::clickCell` calls. + /// @param onClick The handler. + void setOnCellClick(std::function onClick) override { + _onCellClick = std::move(onClick); + } + + /// @brief The handler `setOnCellClick` stored. + /// @return It; empty when none. + [[nodiscard]] std::function const& onCellClick() const noexcept { + return _onCellClick; + } + + /// @brief Stores the handler `RecordingBackend::focusOut` calls, which focus moving from inside the table to a + /// widget outside it calls too. + /// @param onFocusOut The handler. + void setOnFocusOut(std::function onFocusOut) override { callbacks().focusOut = std::move(onFocusOut); } + + /// @brief Records the row's property `editor:`: the editor widget's id, empty for none. + /// @param row One of this table's rows. + /// @param column The cell's column. + /// @param editor The editor, a child of @p row, or null. + /// @throws std::logic_error when @p row is not this table's child, or @p editor not the row's. + void setCellEditor(Widget& row, std::size_t column, Widget* editor) override { + int const rowId = store().idOf(row); + if (store().at(rowId).parent != id()) { + throw std::logic_error{"RecordingBackend: setCellEditor of a widget that is not this table's row"}; + } + std::string shown; + if (editor != nullptr) { + int const editorId = store().idOf(*editor); + if (store().at(editorId).parent != rowId) { + throw std::logic_error{"RecordingBackend: setCellEditor of an editor that is not the row's child"}; + } + shown = std::to_string(editorId); + } + store().set(rowId, "editor:" + std::to_string(column), shown); + } + + /// @brief Records property `cellSelection`: `r+,c+`, `c` + /// counting + /// visible positions, or empty for none. + /// @param rect The rectangle, or nothing. + void setCellSelection(std::optional> rect) override { + set("cellSelection", rect ? "r" + std::to_string(rect->at(0)) + "+" + std::to_string(rect->at(1)) + ",c" + + std::to_string(rect->at(2)) + "+" + std::to_string(rect->at(3)) + : std::string{}); + } + + /// @brief Stores the handler `RecordingBackend::selectCells` calls. + /// @param onSelect The handler. + void setOnCellSelect(std::function onSelect) override { + _onCellSelect = std::move(onSelect); + } + + /// @brief Calls the handler `setOnCellSelect` stored, as a drag from cell to cell would. + /// @param anchorRow The anchor's view row. + /// @param anchorPosition The anchor's visible position. + /// @param focusRow The focus's view row. + /// @param focusPosition The focus's visible position. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): two corners, each a row and a position. + void selectCells(std::size_t anchorRow, std::size_t anchorPosition, std::size_t focusRow, + std::size_t focusPosition) { + if (_onCellSelect) { + auto const handler = _onCellSelect; + handler(anchorRow, anchorPosition, focusRow, focusPosition); + } + } + + /// @brief Records the row's property `marks:`: `r`, `m`, `e`, `s` and `u` for the marks set, in that + /// order, empty for none. + /// @param row One of this table's rows. + /// @param column The cell's column. + /// @param marks The marks. + /// @throws std::logic_error when @p row is not this table's child. + void setCellMarks(Widget& row, std::size_t column, CellMarks const& marks) override { + int const rowId = store().idOf(row); + if (store().at(rowId).parent != id()) { + throw std::logic_error{"RecordingBackend: setCellMarks of a widget that is not this table's row"}; + } + std::string shown; + shown += marks.readOnly ? "r" : ""; + shown += marks.modified ? "m" : ""; + shown += marks.error ? "e" : ""; + shown += marks.stale ? "s" : ""; + shown += marks.muted ? "u" : ""; + store().set(rowId, "marks:" + std::to_string(column), shown); + } + + /// @brief Records the row's property `modified`. + /// @param row One of this table's rows. + /// @param modified Whether the row draws its modified mark. + /// @throws std::logic_error when @p row is not this table's child. + void setRowModified(Widget& row, bool modified) override { + int const rowId = store().idOf(row); + if (store().at(rowId).parent != id()) { + throw std::logic_error{"RecordingBackend: setRowModified of a widget that is not this table's row"}; + } + store().set(rowId, "modified", formatBool(modified)); + } + + /// @brief Records property `counts` as `/`, which `RecordingBackend::lastCounts` reads. + /// @param rows The rows, or nothing. + /// @param columns The visible columns. + void setCounts(std::optional rows, std::size_t columns) override { + _counts = {rows, columns}; + set("counts", (rows ? std::to_string(*rows) : std::string{"unknown"}) + "/" + std::to_string(columns)); + } + + /// @brief Records property `scrolledToRow`. + /// @param viewRow The row. + void scrollToRow(std::size_t viewRow) override { set("scrolledToRow", std::to_string(viewRow)); } + + /// @brief Records property `highlightedRow`, `none` for no mark. + /// @param viewRow The row, or nothing. + void setHighlightedRow(std::optional viewRow) override { + set("highlightedRow", viewRow ? std::to_string(*viewRow) : std::string{"none"}); + } + + /// @brief Records the cell's property `column`, `none` for a pooled cell. + /// @param row One of this table's rows. + /// @param cell One of the row's children. + /// @param column The column, or nothing. + /// @throws std::logic_error when @p row is not this table's child, or @p cell not the row's. + void setCellColumn(Widget& row, Widget& cell, std::optional column) override { + int const rowId = store().idOf(row); + int const cellId = store().idOf(cell); + if (store().at(rowId).parent != id() || store().at(cellId).parent != rowId) { + throw std::logic_error{"RecordingBackend: setCellColumn of a widget that is not a cell of this table"}; + } + store().set(cellId, "column", column ? std::to_string(*column) : std::string{"none"}); + } + + /// @brief Records the row's property `viewRow`. + /// @param row One of this table's rows. + /// @param viewRow The row's view index. + /// @throws std::logic_error when @p row is not this table's child. + void setRowIndex(Widget& row, std::size_t viewRow) override { + int const rowId = store().idOf(row); + if (store().at(rowId).parent != id()) { + throw std::logic_error{"RecordingBackend: setRowIndex of a widget that is not this table's row"}; + } + _viewRows[rowId] = viewRow; + store().set(rowId, "viewRow", std::to_string(viewRow)); + } + + /// @brief The measure the backend was given, `TableMeasure{}` unless `RecordingBackend::setTableMeasure` set one. + /// @return It. + [[nodiscard]] TableMeasure tableMeasure() const override { return _measure ? *_measure : TableMeasure{}; } + + /// @brief Shares the backend's measure, which `tableMeasure` answers. + /// @param measure The measure; null for the default. + void measureBy(std::shared_ptr measure) { _measure = std::move(measure); } + + /// @brief Calls the handler `setOnHorizontalRange` stored, as a backend's scroll would. + /// @param scrollX The offset. + /// @param viewport The viewport's width. + void scrollColumns(int scrollX, int viewport) { + if (_onHorizontal) { + _onHorizontal(scrollX, viewport); + } + } + + /// @brief Calls the handler `setOnSelectRange` stored, as a Shift+click would, or a Ctrl+Shift+click with + /// `Extend`. + /// @param anchor The anchor's view row. + /// @param focus The end's view row. + /// @param change Whether the range replaces the selection or is added to it. + void selectRange(std::size_t anchor, std::size_t focus, SelectionChange change = SelectionChange::Replace) { + if (_onSelectRange) { + _onSelectRange(anchor, focus, change); + } + } + + /// @brief Calls the handler `setOnColumnMeasured` stored, as a cell's layout would. + /// @param column The column. + /// @param measure What was measured. + void measure(std::size_t column, ColumnMeasure const& measure) { + if (_onMeasured) { + _onMeasured(column, measure); + } + } + + /// @brief Calls the handler `setOnFocusMove` stored, as a key would. + /// @param move The move. + void moveFocus(FocusMove move) { + if (_onFocusMove) { + _onFocusMove(move); + } + } + + /// @brief The column window last set. + /// @return Its columns; empty before any. + [[nodiscard]] std::vector const& windowColumns() const noexcept { return _window; } + + /// @brief The total width last set. + /// @return It; 0 before any. + [[nodiscard]] int totalWidth() const noexcept { return _totalWidth; } + + /// @brief How many leading columns of the last window are pinned. + /// @return The count. + [[nodiscard]] std::size_t pinnedShown() const noexcept { return _pinnedShown; } + + /// @brief The header cells drawn: one per column of the window once one is set, one per column before. + /// @return The count. + [[nodiscard]] std::size_t headerCells() const noexcept { return _windowSet ? _window.size() : _columns.size(); } + + /// @brief The last horizontal offset set. + /// @return It, or nothing when never set. + [[nodiscard]] std::optional horizontalOffset() const noexcept { return _horizontalOffset; } + + /// @brief The focused cell last set. + /// @return Its view row and column; `{0, 0}` before any. + [[nodiscard]] std::pair focusCell() const noexcept { return _focusCell; } + + /// @brief Every focused cell set, oldest first. + /// @return Their view rows and columns. + [[nodiscard]] std::vector> const& focusCells() const noexcept { + return _focusCells; + } + + /// @brief For every focused cell set, the key of the row the table held at that view row when it was set. + /// @return The keys, oldest first; none where no row was at that view row. + [[nodiscard]] std::vector> const& focusKeys() const noexcept { return _focusKeys; } + + /// @brief The counts last set. + /// @return The rows (or nothing) and the columns. + [[nodiscard]] std::pair, std::size_t> lastCounts() const noexcept { return _counts; } + + /// @brief The status line last set. + /// @return It; the default before any `setStatus`. + [[nodiscard]] TableStatus const& status() const noexcept { return _status; } + + /// @brief The columns last set. + /// @return They; empty before any `setColumns`. + [[nodiscard]] std::vector const& columns() const noexcept { return _columns; } + + /// @brief A current row's cell's load state, as `setCellLoad` last set it. + /// @param key The row's key. + /// @param column The cell's column. + /// @return The state; `Loaded` when none was set. + /// @throws std::logic_error when no current row has @p key. + [[nodiscard]] CellLoad cellLoad(Key const& key, std::size_t column) const { + std::optional const row = rowOf(key); + if (!row) { + throw std::logic_error{"RecordingBackend: cellLoad of " + formatKey(key) + ", which Table#" + + std::to_string(id()) + " has no row for"}; + } + auto const found = _loads.find(std::pair{*row, column}); + return found == _loads.end() ? CellLoad::Loaded : found->second; + } + + /// @brief A current row's cell's accent, as `setCellAccent` last set it. + /// @param key The row's key. + /// @param column The cell's column. + /// @return The accent; `CellAccent{}` when none was set. + /// @throws std::logic_error when no current row has @p key. + [[nodiscard]] CellAccent cellAccent(Key const& key, std::size_t column) const { + std::optional const row = rowOf(key); + if (!row) { + throw std::logic_error{"RecordingBackend: cellAccent of " + formatKey(key) + ", which Table#" + + std::to_string(id()) + " has no row for"}; + } + auto const found = _accents.find(std::pair{*row, column}); + return found == _accents.end() ? CellAccent{} : found->second; + } + /// @brief The selection mode last set. /// @return The mode; `None` until `setSelectionMode` runs. [[nodiscard]] SelectionMode mode() const noexcept { return _mode; } @@ -2482,6 +3239,7 @@ class FakeTable final : public FakeContainer { /// input left it; nothing is logged. /// @param keys Keys of current rows. void select(std::vector const& keys) { + _viewExcept.reset(); _requested = keys; remark(); } @@ -2541,6 +3299,14 @@ class FakeTable final : public FakeContainer { /// @return The keys. [[nodiscard]] std::vector markedKeys() const { std::vector keys; + if (_viewExcept) { + for (Key const& key : rowKeys()) { + if (!std::ranges::contains(*_viewExcept, key)) { + keys.push_back(key); + } + } + return keys; + } for (Key const& key : _requested.value_or(std::vector{})) { if ((rowOf(key).has_value() || _existing.contains(key)) && !headingKey(key)) { keys.push_back(key); @@ -2568,9 +3334,68 @@ class FakeTable final : public FakeContainer { std::unordered_set _existing; // Engaged once `setSelection` ran or the user selected. std::optional> _requested; + // Engaged while the selection is of the view: every row but these keys is marked. + std::optional> _viewExcept; + // The last marks of each row, by its key. + std::map _rowMarks; + std::map _rowTones; + std::function _onStatusEntry; // The row a Shift-click's range starts from: the last row clicked without Shift. std::optional _anchor; std::function _onVisibleRangeChanged; + std::function _onSelectAll; + std::vector _chain; + std::function(std::optional)> _menu; + std::function, std::vector)> _onMenu; + std::function(Key const&, std::size_t)> _cellMenu; + std::function const&)> _cellChosen; + std::vector _cellMenuKeys; + mutable std::size_t _cellMenuAsks = 0; // how many times the cell menu's entries were asked for + std::map _viewRows; // row id -> view index, as setRowIndex told it + bool _focusSet = false; // whether setFocusCell ran + std::vector _visible; + std::function _onColumnMove; + std::function)> _onColumnResize; + std::function _onFilter; + std::vector _filtered; + std::vector _groups; + std::vector _bands; + std::function _onGroupFilter; + std::function _onCopy; + TableStatus _status; + std::vector _columns; + std::map, CellLoad> _loads; // (row id, column) -> state, as setCellLoad told it + std::map, CellAccent> + _accents; // (row id, column) -> accent, as setCellAccent told it + std::vector _window; // the column window, as setColumnWindow last gave it + bool _windowSet = false; + int _totalWidth = 0; + std::size_t _pinnedShown = 0; + std::optional _horizontalOffset; + std::pair _focusCell; + std::vector> _focusCells; + std::vector> _focusKeys; + std::pair, std::size_t> _counts; + std::function _onHorizontal; + std::function _onSelectRange; + std::function _onMeasured; + std::function _onFocusMove; + std::function _onCellSelect; + std::function _onText; + std::function _onCellClick; + std::shared_ptr _measure; + + [[nodiscard]] static std::string formatCellLoad(CellLoad load) { + switch (load) { + case CellLoad::Unloaded: + return "Unloaded"; + case CellLoad::Failed: + return "Failed"; + case CellLoad::Loaded: + default: + return "Loaded"; + } + } }; } // namespace detail @@ -2656,7 +3481,9 @@ class RecordingBackend final : public IViewBackend { return std::make_unique(_store, "Busy", parent); } [[nodiscard]] std::unique_ptr createTable(ContainerWidget* parent) override { - return std::make_unique(_store, "Table", parent); + auto table = std::make_unique(_store, "Table", parent); + table->measureBy(_tableMeasure); + return table; } [[nodiscard]] std::unique_ptr createDateTimeInput(ContainerWidget* parent, DateMode mode, int offsetMinutes) override { @@ -2909,7 +3736,8 @@ class RecordingBackend final : public IViewBackend { /// and stops when the field has a submit handler, and goes on after the commit when it has none; a `Checkbox`'s /// `Space` toggles it; a segmented `Select`'s `Left` and `Right` choose the previous or the next option, stopping /// at the ends; a `Table`'s `Enter` activates its first marked row, and stops whether or not one is marked; a - /// `Multiple` table's `Ctrl+A` selects every row, or clears them when every row is selected, as `Extend`. Then + /// `Multiple` table's `Ctrl+A` calls its select-all handler when it has one (`setOnSelectAll`), and otherwise + /// selects every row, or clears them when every row is selected, as `Extend`. Then /// the chords of its ancestors, innermost first. A handler that destroys the focused widget stops the key there. /// Like every helper it acts only when a user could reach @p widgetId. /// @param widgetId The widget focus is on. @@ -3288,18 +4116,579 @@ class RecordingBackend final : public IViewBackend { invoke(record.callbacks.selection, std::move(keys), change); } - /// @brief Clicks a column's header as the user would: a sortable column's reaches `onSort` with its index; any - /// other header does nothing, since a user can click it. + /// @brief A plain click on a row: `clickRow` with `RowClick::Only`. + /// @param widgetId The table. + /// @param key The row's key. + void clickRow(int widgetId, Key const& key) { clickRow(widgetId, key, RowClick::Only); } + + /// @brief A `Ctrl`+click on a row: `clickRow` with `RowClick::Toggle`. + /// @param widgetId The table. + /// @param key The row's key. + void ctrlClickRow(int widgetId, Key const& key) { clickRow(widgetId, key, RowClick::Toggle); } + + /// @brief The user's select-all on a `Multiple` table (`Ctrl+A`, the select-all box): the handler + /// `setOnSelectAll` stored. + /// @param widgetId The table. + /// @throws std::logic_error when the widget is not a table or has no select-all handler. + void selectAll(int widgetId) { + detail::Record const& record = expectKind(widgetId, "selectAll", {"Table"}); + auto const* const table = dynamic_cast(record.widget); + if (table == nullptr || !table->onSelectAll()) { + throw std::logic_error{"RecordingBackend: selectAll of Table#" + std::to_string(widgetId) + + ", which has no select-all handler"}; + } + if (reachable(record)) { + std::function const selectAll = table->onSelectAll(); + selectAll(); + } + } + + /// @brief Chooses an entry the status line shows: the handler `setOnStatusEntry` stored, with its id. + /// @param widgetId The table. + /// @param entry The entry's id. + /// @throws std::logic_error when the widget is not a table, has no handler, or its status shows no such entry. + void chooseStatusEntry(int widgetId, std::string const& entry) { + detail::Record const& record = expectKind(widgetId, "chooseStatusEntry", {"Table"}); + auto const* const table = dynamic_cast(record.widget); + bool const shown = + table != nullptr && (std::ranges::contains(table->status().entries, entry, &StatusEntry::id) || + std::ranges::contains(table->status().standingEntries, entry, &StatusEntry::id)); + if (!shown || !table->onStatusEntry()) { + throw std::logic_error{"RecordingBackend: chooseStatusEntry of " + entry + " on Table#" + + std::to_string(widgetId) + ", whose status line shows no such entry"}; + } + if (reachable(record)) { + std::function const choose = table->onStatusEntry(); + choose(entry); + } + } + + /// @brief Clicks a column's header as the user would: a sortable column's reaches `onSort` with its index and + /// @p click; any other header does nothing, since a user can click it. /// @param widgetId The table. /// @param column The column's index among the columns `setColumns` gave. - /// @throws std::logic_error when the widget is not a table. + /// @param click Whether `Shift` is held. + /// @throws std::logic_error when the widget is not a table, or the column's header is not drawn. // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) - void clickHeader(int widgetId, std::size_t column) { + void clickHeader(int widgetId, std::size_t column, HeaderClick click = HeaderClick::Plain) { detail::Record const& record = expectKind(widgetId, "clickHeader", {"Table"}); + auto const& table = shownHeader(record, widgetId, column, "clickHeader"); + if (table.sortable(column) && reachable(record)) { + invoke(record.callbacks.sort, column, click); + } + } + + /// @brief The entries of a header's menu, or of the table's menu, as a user opening it would see them. + /// @param widgetId The table. + /// @param column The column, or none for the table's menu. + /// @return The entries; none when the table has no menus or a user cannot reach it. + /// @throws std::logic_error when the widget is not a table, or the column's header is not drawn. + [[nodiscard]] std::vector menuOf(int widgetId, std::optional column) { + detail::Record const& record = expectKind(widgetId, "menuOf", {"Table"}); + detail::FakeTable const& table = column ? shownHeader(record, widgetId, *column, "menuOf") : fakeTable(record); + return reachable(record) ? table.menuEntries(column) : std::vector{}; + } + + /// @brief Chooses an entry of a header's menu, or of the table's menu, by its labels from the top, as a user + /// opening each submenu on the way would. Nothing is reported for a disabled entry, an entry inside a + /// disabled one, or an entry with a submenu. + /// @param widgetId The table. + /// @param column The column, or none for the table's menu. + /// @param labels The entry's label at each level, from the top; not empty. + /// @throws std::logic_error when the widget is not a table, the column's header is not drawn, or a label names + /// no entry of its level. + void chooseMenu(int widgetId, std::optional column, std::vector const& labels) { + std::vector const entries = menuOf(widgetId, column); + detail::Record const& record = _store->at(widgetId); + std::vector const* level = &entries; + std::vector path; + bool enabled = true; + MenuEntry const* entry = nullptr; + for (std::string_view const label : labels) { + auto const found = std::ranges::find_if(*level, [label](MenuEntry const& candidate) { + return !candidate.separator && !candidate.heading && candidate.label == label; + }); + if (found == level->end()) { + throw std::logic_error{"RecordingBackend: chooseMenu of '" + std::string{label} + "', which Table#" + + std::to_string(widgetId) + "'s menu does not have"}; + } + path.push_back(static_cast(std::distance(level->begin(), found))); + enabled = enabled && found->enabled; + entry = &*found; + level = &found->items; + } + if (entry != nullptr && enabled && entry->items.empty() && reachable(record)) { + invoke(fakeTable(record).onMenu(), column, std::move(path)); + } + } + + /// @brief Opens a cell's menu as a right click on the cell would: in a table that selects, a row that is not + /// selected becomes the selection alone, reported as `Replace`; then the entries are asked for, which + /// focuses the cell. + /// @param widgetId The table. + /// @param key The cell's row. + /// @param column The cell's column: an index into the table's columns. + /// @return The entries; none when the table has no cell menu or a user cannot reach it. + /// @throws std::logic_error when the widget is not a table, or no current row has @p key. + [[nodiscard]] std::vector rightClickCell(int widgetId, Key const& key, std::size_t column) { + detail::Record const& record = expectKind(widgetId, "rightClickCell", {"Table"}); + auto* const table = dynamic_cast(record.widget); + std::optional const rowId = table == nullptr ? std::nullopt : table->rowOf(key); + if (!rowId.has_value()) { + throw std::logic_error{"RecordingBackend: rightClickCell of " + detail::formatKey(key) + " of Table#" + + std::to_string(widgetId) + ", which has no such row"}; + } + if (!reachable(record) || !reachable(_store->at(*rowId))) { + return {}; + } + if (table->mode() != SelectionMode::None && !table->headingKey(key) && + !std::ranges::contains(table->markedKeys(), key)) { + table->selectByUser({key}); + invoke(record.callbacks.selection, std::vector{key}, SelectionChange::Replace); + } + return exists(widgetId) ? table->cellMenuEntries(key, column) : std::vector{}; + } + + /// @brief How many times a table's cell menu entries were asked for: by an opened menu or by a key. + /// @param widgetId The table. + /// @return The count. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::size_t cellMenuAsks(int widgetId) { return fakeTable(widgetId, "cellMenuAsks").cellMenuAsks(); } + + /// @brief Chooses an entry of a cell's menu by its labels from the top, as a user opening it on the cell and each + /// submenu on the way would. Nothing is reported for a disabled entry, an entry inside a disabled one, or + /// an entry with a submenu. + /// @param widgetId The table. + /// @param key The cell's row. + /// @param column The cell's column. + /// @param labels The entry's label at each level, from the top; not empty. + /// @throws std::logic_error when the widget is not a table, or a label names no entry of its level. + void chooseCellMenu(int widgetId, Key const& key, std::size_t column, + std::vector const& labels) { + detail::Record const& record = expectKind(widgetId, "chooseCellMenu", {"Table"}); + std::vector const entries = fakeTable(record).cellMenuEntries(key, column); + std::vector const* level = &entries; + std::vector path; + bool enabled = true; + MenuEntry const* entry = nullptr; + for (std::string_view const label : labels) { + auto const found = std::ranges::find_if(*level, [label](MenuEntry const& candidate) { + return !candidate.separator && !candidate.heading && candidate.label == label; + }); + if (found == level->end()) { + throw std::logic_error{"RecordingBackend: chooseCellMenu of '" + std::string{label} + + "', which Table#" + std::to_string(widgetId) + "'s cell menu does not have"}; + } + path.push_back(static_cast(std::distance(level->begin(), found))); + enabled = enabled && found->enabled; + entry = &*found; + level = &found->items; + } + if (entry != nullptr && enabled && entry->items.empty() && reachable(record)) { + invoke(fakeTable(record).cellChosen(), key, column, path); + } + } + + /// @brief Moves a column as a user dragging its header would: `onColumnMove` gets the column and @p position, + /// unless the column is at that place already or the place is past the last visible column. + /// @param widgetId The table. + /// @param column The column. + /// @param position Its new place among the visible columns. + /// @throws std::logic_error when the widget is not a table, or the column's header is not drawn. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) + void moveColumn(int widgetId, std::size_t column, std::size_t position) { + detail::Record const& record = expectKind(widgetId, "moveColumn", {"Table"}); + detail::FakeTable const& table = shownHeader(record, widgetId, column, "moveColumn"); + if (reachable(record) && table.placeOf(column) != position && position < table.visibleCount()) { + invoke(table.onColumnMove(), column, position); + } + } + + /// @brief Resizes a column as a user dragging its header's trailing edge would, or double-clicking it. + /// @param widgetId The table. + /// @param column The column. + /// @param units The width in `Sizing` units, or none for the double click. + /// @throws std::logic_error when the widget is not a table, or the column's header is not drawn. + void resizeColumn(int widgetId, std::size_t column, std::optional units) { + detail::Record const& record = expectKind(widgetId, "resizeColumn", {"Table"}); + detail::FakeTable const& table = shownHeader(record, widgetId, column, "resizeColumn"); + if (reachable(record)) { + invoke(table.onColumnResize(), column, units); + } + } + + /// @brief Presses a filterable column's filter button; another column's header has none, so nothing happens. + /// @param widgetId The table. + /// @param column The column. + /// @throws std::logic_error when the widget is not a table, or the column's header is not drawn. + void clickFilter(int widgetId, std::size_t column) { + detail::Record const& record = expectKind(widgetId, "clickFilter", {"Table"}); + detail::FakeTable const& table = shownHeader(record, widgetId, column, "clickFilter"); + if (reachable(record) && table.columns().at(column).filterable) { + invoke(table.onFilter(), column); + } + } + + /// @brief Presses a column group's filter button in the group header row. + /// @param widgetId The table. + /// @param group The group's index among those `setColumnGroups` gave. + /// @throws std::logic_error when the widget is not a table, or it draws no such group. + void clickGroupFilter(int widgetId, std::size_t group) { + detail::Record const& record = expectKind(widgetId, "clickGroupFilter", {"Table"}); + detail::FakeTable const& table = fakeTable(record); + if (group >= table.groupCount()) { + throw std::logic_error{"RecordingBackend: clickGroupFilter of group " + std::to_string(group) + + ", which Table#" + std::to_string(widgetId) + " does not draw"}; + } + if (reachable(record)) { + invoke(table.onGroupFilter(), group); + } + } + + /// @brief Asks to copy as `Ctrl+C` on the focused table does. + /// @param widgetId The table. + /// @throws std::logic_error when the widget is not a table. + void pressCopy(int widgetId) { + detail::Record const& record = expectKind(widgetId, "pressCopy", {"Table"}); + if (reachable(record)) { + invoke(fakeTable(record).onCopy()); + } + } + + /// @brief The text a column's header draws: its label, then its sort key's mark. + /// @param widgetId The table. + /// @param column The column. + /// @return The text. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::string headerText(int widgetId, std::size_t column) { + return fakeTable(expectKind(widgetId, "headerText", {"Table"})).headerText(column); + } + + /// @brief Whether a column's header is drawn: the column is one of the table's and, once the visible columns were + /// told, one of them. + /// @param widgetId The table. + /// @param column The column. + /// @return True when its header is drawn. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] bool headerShown(int widgetId, std::size_t column) { + return fakeTable(expectKind(widgetId, "headerShown", {"Table"})).headerShown(column); + } + + /// @brief A column header's accessible description: its sort key's, or empty. + /// @param widgetId The table. + /// @param column The column. + /// @return The description. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::string headerDescription(int widgetId, std::size_t column) { + return fakeTable(expectKind(widgetId, "headerDescription", {"Table"})).headerDescription(column); + } + + /// @brief A column header's accessible name: its label, and `, filtered` while it has a filter. + /// @param widgetId The table. + /// @param column The column. + /// @return The name. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::string headerName(int widgetId, std::size_t column) { + return fakeTable(expectKind(widgetId, "headerName", {"Table"})).headerName(column); + } + + /// @brief Records the text as the clipboard's, which `clipboardText` reads, unless `setClipboard(false)` took + /// the clipboard away. + /// @param text The text. + /// @return Whether the backend has a clipboard: true unless `setClipboard(false)`. + bool copyText(std::string_view text) override { + if (!_hasClipboard) { + return false; + } + _clipboard = std::string{text}; + return true; + } + + /// @brief The clipboard's text, as `copyText` last recorded it. + /// @return The text; nothing while `setClipboard(false)` took the clipboard away. + [[nodiscard]] std::optional pasteText() override { + return _hasClipboard ? std::optional{_clipboard} : std::nullopt; + } + + /// @brief Gives the backend a clipboard, as it has from the start, or takes it away, as a platform without + /// one would: `copyText` then writes nothing and returns false. + /// @param available Whether there is a clipboard. + void setClipboard(bool available) { _hasClipboard = available; } + + /// @brief The last text `copyText` was given. + /// @return It; empty before any. + [[nodiscard]] std::string clipboardText() const { return _clipboard; } + + /// @brief Chooses "Retry" on a table's status line. + /// @param widgetId The table. + /// @throws std::logic_error when the widget is not a table. + void retryTable(int widgetId) { + detail::Record const& record = expectKind(widgetId, "retryTable", {"Table"}); + if (reachable(record)) { + invoke(record.callbacks.retry); + } + } + + /// @brief The last marks the mount set on a table's row. + /// @param widgetId The table. + /// @param key The row's key. + /// @return The marks; none before any `setRowMarks` of that row. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::optional rowMarks(int widgetId, Key const& key) { + detail::Record const& record = expectKind(widgetId, "rowMarks", {"Table"}); auto const* const table = dynamic_cast(record.widget); - if (table != nullptr && table->sortable(column) && reachable(record)) { - invoke(record.callbacks.sort, column); + return table == nullptr ? std::nullopt : table->rowMarks(key); + } + + /// @brief The last tone the mount set on a table's row, by the row's key. + /// @param widgetId The table. + /// @param key The row's key. + /// @return The tone's name, `none` for no tone; empty before any `setRowTone` of that row. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::string rowTone(int widgetId, Key const& key) { + detail::Record const& record = expectKind(widgetId, "rowTone", {"Table"}); + auto const* const table = dynamic_cast(record.widget); + return table == nullptr ? std::string{} : table->rowTone(key); + } + + /// @brief A table's status line, as the mount last set it. + /// @param widgetId The table. + /// @return The status; the default before any `setStatus`. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] TableStatus tableStatus(int widgetId) { + detail::Record const& record = expectKind(widgetId, "tableStatus", {"Table"}); + auto const* const table = dynamic_cast(record.widget); + return table == nullptr ? TableStatus{} : table->status(); + } + + /// @brief A table's columns, as the mount last set them. + /// @param widgetId The table. + /// @return The columns; empty before any `setColumns`. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::vector tableColumns(int widgetId) { + detail::Record const& record = expectKind(widgetId, "tableColumns", {"Table"}); + auto const* const table = dynamic_cast(record.widget); + return table == nullptr ? std::vector{} : table->columns(); + } + + /// @brief Scrolls a table sideways as the user would: the handler `setOnHorizontalRange` stored gets the offset + /// and the viewport's width. + /// @param widgetId The table. + /// @param scrollX The offset. + /// @param viewport The viewport's width. + /// @throws std::logic_error when the widget is not a table. + void scrollTableColumns(int widgetId, int scrollX, int viewport) { + fakeTable(widgetId, "scrollTableColumns").scrollColumns(scrollX, viewport); + } + + /// @brief Moves a table's focused cell as a key would. + /// @param widgetId The table. + /// @param move The move. + /// @throws std::logic_error when the widget is not a table. + void focusMove(int widgetId, FocusMove move) { fakeTable(widgetId, "focusMove").moveFocus(move); } + + /// @brief Types printable text on a table's focused cell, as a key with no editor open does: calls the handler + /// `TableWidget::setOnText` stored, if any. + /// @param widgetId The table. + /// @param text The text. + /// @throws std::logic_error when the widget is not a table. + void typeInto(int widgetId, std::string text) { + detail::FakeTable const& table = fakeTable(widgetId, "typeInto"); + if (reachable(_store->at(widgetId)) && table.onText()) { + std::function const handler = table.onText(); + handler(std::move(text)); + } + } + + /// @brief Clicks a table's cell: calls the handler `TableWidget::setOnCellClick` stored with `false`, and for a + /// double click then again with `true`, as a backend does. + /// @param widgetId The table. + /// @param viewRow The cell's view row. + /// @param column The cell's column: an index into the table's columns. + /// @param doubleClick Whether the click is a double click. + /// @throws std::logic_error when the widget is not a table. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): a row and a column, as every cell driver takes them. + void clickCell(int widgetId, std::size_t viewRow, std::size_t column, bool doubleClick = false) { + detail::FakeTable const& table = fakeTable(widgetId, "clickCell"); + if (!reachable(_store->at(widgetId)) || !table.onCellClick()) { + return; + } + std::function const handler = table.onCellClick(); + handler(viewRow, column, false); + if (doubleClick) { + handler(viewRow, column, true); + } + } + + /// @brief Selects a rectangle of cells as a drag from one cell to another does: calls the handler + /// `TableWidget::setOnCellSelect` stored, if any. + /// @param tableId The table. + /// @param anchorRow The anchor's view row. + /// @param anchorPosition The anchor's place among the visible columns. + /// @param focusRow The focus's view row. + /// @param focusPosition The focus's place among the visible columns. + /// @throws std::logic_error when the widget is not a table. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): two corners, each a row and a position. + void selectCells(int tableId, std::size_t anchorRow, std::size_t anchorPosition, std::size_t focusRow, + std::size_t focusPosition) { + detail::FakeTable& table = fakeTable(tableId, "selectCells"); + if (reachable(_store->at(tableId))) { + table.selectCells(anchorRow, anchorPosition, focusRow, focusPosition); + } + } + + /// @brief Moves focus out of a table and everything inside it: calls the handler `TableWidget::setOnFocusOut` + /// stored, if any. + /// @param widgetId The table. + /// @throws std::logic_error when the widget is not a table. + void focusOut(int widgetId) { + detail::Record const& record = expectKind(widgetId, "focusOut", {"Table"}); + invoke(record.callbacks.focusOut); + } + + /// @brief Selects a range of view rows as a Shift+click over rows the backend holds no keys for would: the + /// handler `setOnSelectRange` stored gets the two rows and @p change, `Replace` unless the range is added + /// to the selection as a Ctrl+Shift+click adds it. + /// @param widgetId The table. + /// @param anchor The anchor's view row. + /// @param focus The end's view row. + /// @param change Whether the range replaces the selection or is added to it. + /// @throws std::logic_error when the widget is not a table. + void selectTableRange(int widgetId, std::size_t anchor, std::size_t focus, + SelectionChange change = SelectionChange::Replace) { + fakeTable(widgetId, "selectTableRange").selectRange(anchor, focus, change); + } + + /// @brief Reports the width a cell of a column measured, as a backend's layout would. + /// @param widgetId The table. + /// @param column The column: an index into the table's columns. + /// @param width The width. + /// @throws std::logic_error when the widget is not a table. + void measureColumn(int widgetId, std::size_t column, int width) { + fakeTable(widgetId, "measureColumn").measure(column, ColumnMeasure{.natural = width, .least = width}); + } + + /// @brief Reports what a column's header and cells measured, as a backend's layout would. + /// @param widgetId The table. + /// @param column The column: an index into the table's columns. + /// @param measure What was measured. + /// @throws std::logic_error when the widget is not a table. + void measureColumn(int widgetId, std::size_t column, ColumnMeasure const& measure) { + fakeTable(widgetId, "measureColumn").measure(column, measure); + } + + /// @brief A table's column window, as the mount last set it. + /// @param widgetId The table. + /// @return Its columns, pinned first; empty before any. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::vector windowColumns(int widgetId) { + return fakeTable(widgetId, "windowColumns").windowColumns(); + } + + /// @brief A table's total width, as the mount last set it. + /// @param widgetId The table. + /// @return The width; 0 before any. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] int totalWidth(int widgetId) { return fakeTable(widgetId, "totalWidth").totalWidth(); } + + /// @brief How many leading columns of a table's last column window the mount marked pinned. + /// @param widgetId The table. + /// @return The count. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::size_t pinnedShown(int widgetId) { return fakeTable(widgetId, "pinnedShown").pinnedShown(); } + + /// @brief The header cells a table draws: the column window's once one is set, every column's before. + /// @param widgetId The table. + /// @return The count. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::size_t headerCells(int widgetId) { return fakeTable(widgetId, "headerCells").headerCells(); } + + /// @brief Sets the measure every table of this backend answers `TableWidget::tableMeasure` with, before a mount. + /// @param measure The measure. + void setTableMeasure(TableMeasure const& measure) { *_tableMeasure = measure; } + + /// @brief A table's horizontal offset, as the mount last moved it. + /// @param widgetId The table. + /// @return The offset, or nothing when the mount never moved it. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::optional horizontalOffset(int widgetId) { + return fakeTable(widgetId, "horizontalOffset").horizontalOffset(); + } + + /// @brief A table's focused cell, as the mount last set it. + /// @param widgetId The table. + /// @return Its view row and column. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::pair focusCell(int widgetId) { + return fakeTable(widgetId, "focusCell").focusCell(); + } + + /// @brief Every focused cell the mount set on a table, oldest first. + /// @param widgetId The table. + /// @return Their view rows and columns. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::vector> focusCells(int widgetId) { + return fakeTable(widgetId, "focusCells").focusCells(); + } + + /// @brief For every focused cell the mount set on a table, the key of the row at that view row when it was set. + /// @param widgetId The table. + /// @return The keys, oldest first; none where no row was at that view row. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::vector> focusKeys(int widgetId) { + return fakeTable(widgetId, "focusKeys").focusKeys(); + } + + /// @brief A table's counts, as the mount last set them. + /// @param widgetId The table. + /// @return The rows (nothing when unknown) and the visible columns. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::pair, std::size_t> lastCounts(int widgetId) { + return fakeTable(widgetId, "lastCounts").lastCounts(); + } + + /// @brief A cell's load state in a table whose rows come from a `TableSource`. + /// @param widgetId The table. + /// @param rowKey The row's key. + /// @param column The cell's column: an index into the table's columns. + /// @return The state `setCellLoad` last gave the cell; `Loaded` when none. + /// @throws std::logic_error when the widget is not a table, or none of its current rows has @p rowKey. + [[nodiscard]] CellLoad cellLoad(int widgetId, Key const& rowKey, std::size_t column) { + detail::Record const& record = expectKind(widgetId, "cellLoad", {"Table"}); + auto const* const table = dynamic_cast(record.widget); + if (table == nullptr) { + throw std::logic_error{"RecordingBackend: cellLoad of a widget that is not a table"}; } + return table->cellLoad(rowKey, column); + } + + /// @brief A cell's accent in a table whose rows come from a `TableSource`. + /// @param widgetId The table. + /// @param rowKey The row's key. + /// @param column The cell's column: an index into the table's columns. + /// @return The accent `setCellAccent` last gave the cell; `CellAccent{}` when none. + /// @throws std::logic_error when the widget is not a table, or none of its current rows has @p rowKey. + [[nodiscard]] CellAccent cellAccent(int widgetId, Key const& rowKey, std::size_t column) { + detail::Record const& record = expectKind(widgetId, "cellAccent", {"Table"}); + auto const* const table = dynamic_cast(record.widget); + if (table == nullptr) { + throw std::logic_error{"RecordingBackend: cellAccent of a widget that is not a table"}; + } + return table->cellAccent(rowKey, column); + } + + /// @brief The widget of a current row of a table. + /// @param widgetId The table. + /// @param rowKey The row's key. + /// @return The row's widget id; nothing when no current row has @p rowKey. + /// @throws std::logic_error when the widget is not a table. + [[nodiscard]] std::optional tableRow(int widgetId, Key const& rowKey) { + detail::Record const& record = expectKind(widgetId, "tableRow", {"Table"}); + auto const* const table = dynamic_cast(record.widget); + if (table == nullptr) { + throw std::logic_error{"RecordingBackend: tableRow of a widget that is not a table"}; + } + return table->rowOf(rowKey); } /// @brief Activates a row of a table (Enter or a double click). @@ -3415,6 +4804,11 @@ class RecordingBackend final : public IViewBackend { } private: + // The fake behind a table, for a helper that drives it; throws as `expectKind` does. + detail::FakeTable& fakeTable(int widgetId, std::string_view helper) { + return dynamic_cast(*expectKind(widgetId, helper, {"Table"}).widget); + } + // The fake behind a text field's record. static detail::FakeTextInput& textInput(detail::Record const& record) { return dynamic_cast(*record.widget); @@ -3431,6 +4825,7 @@ class RecordingBackend final : public IViewBackend { } } + // NOLINTNEXTLINE(readability-function-cognitive-complexity): matches a chord against the widget's own keys, then its table's, then its cells'; each tier has the checks the one before leaves bool ownKey(int widgetId, std::string const& chord) { detail::Record const& record = _store->at(widgetId); bool const enter = chord == "Enter"; @@ -3455,11 +4850,24 @@ class RecordingBackend final : public IViewBackend { commit(widgetId); return false; } + if (record.kind == "Table" && chord == "Ctrl+C") { + auto const* const table = dynamic_cast(record.widget); + if (table == nullptr || !table->onCopy()) { + return false; + } + invoke(table->onCopy()); + return true; + } if (record.kind == "Table" && chord == "Ctrl+A") { auto* const table = dynamic_cast(record.widget); if (table == nullptr || table->mode() != SelectionMode::Multiple) { return false; } + if (table->onSelectAll()) { + std::function const selectAll = table->onSelectAll(); + selectAll(); + return true; + } std::vector keys = table->allOrNone(); table->select(keys); invoke(record.callbacks.selection, std::move(keys), SelectionChange::Extend); @@ -3473,9 +4881,45 @@ class RecordingBackend final : public IViewBackend { } return true; } + if (record.kind == "Table") { + return cellKey(record, chord); + } return false; } + // A chord of the table's cell menu keys runs the focused cell's menu entry that declares it: the first enabled one + // without a submenu, in the order the menu lists them, a submenu's entries after the entry that opens it. Any + // other chord asks for nothing. + static bool cellKey(detail::Record const& record, std::string const& chord) { + auto const* const table = dynamic_cast(record.widget); + std::optional> const cell = + table == nullptr ? std::nullopt : table->focusedCellKey(); + if (!cell || !table->cellChosen() || !std::ranges::contains(table->cellMenuKeys(), chord)) { + return false; + } + std::vector const entries = table->cellMenuEntries(cell->first, cell->second); + std::vector path; + std::function const&)> const find = [&](std::vector const& level) { + for (std::size_t at = 0; at < level.size(); ++at) { + MenuEntry const& entry = level.at(at); + if (entry.separator || entry.heading || !entry.enabled) { + continue; + } + path.push_back(at); + if (entry.items.empty() ? entry.keys == chord : find(entry.items)) { + return true; + } + path.pop_back(); + } + return false; + }; + if (!find(entries)) { + return false; + } + invoke(table->cellChosen(), cell->first, cell->second, path); + return true; + } + // A helper applies to some kinds only; using it on another kind is a mistake in the test, not a user action. detail::Record& expectKind(int widgetId, std::string_view helper, std::initializer_list kinds) { detail::Record& record = _store->at(widgetId); @@ -3576,7 +5020,31 @@ class RecordingBackend final : public IViewBackend { } } + // The fake table behind a table's record. + static detail::FakeTable const& fakeTable(detail::Record const& record) { + auto const* const table = dynamic_cast(record.widget); + if (table == nullptr) { + throw std::logic_error{"RecordingBackend: Table#" + std::to_string(record.id) + " is not a table"}; + } + return *table; + } + + // The fake table, once a user could reach the column's header: a hidden column's is not drawn. + static detail::FakeTable const& shownHeader(detail::Record const& record, int widgetId, std::size_t column, + std::string_view helper) { + detail::FakeTable const& table = fakeTable(record); + if (!table.headerShown(column)) { + throw std::logic_error{"RecordingBackend: " + std::string{helper} + " of column " + + std::to_string(column) + ", whose header Table#" + std::to_string(widgetId) + + " does not draw"}; + } + return table; + } + std::shared_ptr _store = std::make_shared(); + std::string _clipboard; + bool _hasClipboard = true; + std::shared_ptr _tableMeasure = std::make_shared(); std::optional _pageWidth; std::shared_ptr> _pages = std::make_shared>(); std::unordered_set _components; diff --git a/include/morph/ui/theme.hpp b/include/morph/ui/theme.hpp index 2a9295ef7..1f776a39f 100644 --- a/include/morph/ui/theme.hpp +++ b/include/morph/ui/theme.hpp @@ -284,6 +284,15 @@ inline constexpr std::array kNonNegativePaths = { /// @return The reason, such as `input.paddingX: must not be negative`, or nothing when no such dimension is negative. [[nodiscard]] MORPH_API std::optional dimensionProblem(TokenSet const& resolved); +/// @brief The number tokens of the set that are opacities: below 0 or above 1 draws nothing a theme could mean. +inline constexpr std::array kOpacityPaths = {"opacity.stale", "opacity.muted"}; + +/// @brief Why a resolved theme gives an opacity outside 0 to 1. +/// @param resolved The resolved tokens. +/// @return The reason, such as `opacity.muted: must be between 0 and 1`, or nothing when every opacity of the set +/// is in range. +[[nodiscard]] MORPH_API std::optional opacityProblem(TokenSet const& resolved); + /// @brief Why a resolved theme strokes an outline in a style that is not drawn. /// @param resolved The resolved tokens. /// @return The reason, or nothing when every stroke style of the set is `solid` or `dashed`. @@ -349,7 +358,7 @@ struct ThemeTokenSpec { /// @brief The closed `ui-theme/1` token set, with the `MorphUi` defaults: the colour roles, the opacity and the /// spacing scale (`space.0` to `space.5`, one per spacing step) the built-in components read, and the semantic /// sets (`ok`, `warn`, `err`, `info` with `bg`, `border` and `dot`). -inline constexpr std::array kThemeTokens = {{ +inline constexpr auto kThemeTokens = std::to_array({ {.path = "color.surface", .kind = ThemeTokenKind::Color, .color = "#ffffff", .number = 0.0}, {.path = "color.text", .kind = ThemeTokenKind::Color, .color = "#1d1d1f", .number = 0.0}, {.path = "color.muted", .kind = ThemeTokenKind::Color, .color = "#6e6e73", .number = 0.0}, @@ -481,6 +490,14 @@ inline constexpr std::array kThemeTokens = {{ // The 1 px rule under a table's header, in the header's last pixel row. Transparent: a theme that draws a header // band says how it closes. {.path = "color.table.headerRule", .kind = ThemeTokenKind::Color, .color = "#00000000", .number = 0.0}, + // A table row an action of this session is working on: the bar at its leading edge, after the selection's. + {.path = "color.table.busy", .kind = ThemeTokenKind::Color, .color = "#1565c0", .number = 0.0}, + // A table row another user holds: the wash over its cells, translucent so the cells read through it. + {.path = "color.table.locked", .kind = ThemeTokenKind::Color, .color = "#8e8e9338", .number = 0.0}, + // A table's summary row: the surface it is drawn on, translucent so the row's own background reads through it. + {.path = "color.table.summary", .kind = ThemeTokenKind::Color, .color = "#8e8e931f", .number = 0.0}, + // The opacity of a table row kept in view although it no longer matches the filter, from 0 to 1. + {.path = "opacity.muted", .kind = ThemeTokenKind::Number, .color = "", .number = 0.55}, // How the outline of a button, a badge and an input is stroked on a surface: solid, or dashed. Read per surface. {.path = "border.style", .kind = ThemeTokenKind::Stroke, @@ -543,7 +560,7 @@ inline constexpr std::array kThemeTokens = {{ .family = "", .stroke = "", .keyword = "accent"}, -}}; +}); /// @brief A `shadow` of the set, resolved. struct ThemeShadow { diff --git a/include/morph/ui/value.hpp b/include/morph/ui/value.hpp index 23ecaf2ad..7a6e70941 100644 --- a/include/morph/ui/value.hpp +++ b/include/morph/ui/value.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -273,7 +274,9 @@ class Value { return *mine == *other.asList(); } if (ValueRecord const* const mine = asRecord()) { - return *mine == *other.asRecord(); + // One shared record is equal to itself without a walk of its fields: a table's row records are compared + // per cell on every pass. + return mine == other.asRecord() || *mine == *other.asRecord(); } return _data == other._data; } @@ -567,8 +570,22 @@ namespace detail { /// A timestamp has no structural form — it is a string — so it is read through the typed overload. /// @param json The JSON value. /// @return The value, or the reason it is refused. -[[nodiscard]] inline std::expected valueFromJson(Json const& json) { +[[nodiscard]] inline std::expected valueFromJson(Json const& json); + +namespace detail { + +/// @brief What a structural read makes of a JSON number with a fraction or an exponent; null refuses it. +using FractionReader = Value (*)(double number); + +/// @brief `valueFromJson` and `tableValueFromJson`, which differ only in @p fraction. +/// @param json The JSON value. +/// @param fraction What a number with a fraction or an exponent becomes; null refuses it, since an exact value is +/// never written as a double. +/// @return The value, or the reason it is refused. +// NOLINTNEXTLINE(misc-no-recursion): arrays and objects are read element by element. +[[nodiscard]] inline std::expected structuralFromJson(Json const& json, FractionReader fraction) { struct Visitor { + FractionReader fraction; std::expected operator()(std::nullptr_t) const { return Value{}; } std::expected operator()(bool flag) const { return Value{flag}; } std::expected operator()(std::uint64_t number) const { @@ -579,16 +596,18 @@ namespace detail { } std::expected operator()(std::int64_t number) const { return Value{number}; } std::expected operator()(double number) const { - static_cast(number); - return std::unexpected( - std::string{R"(a number with a fraction is not exact; write a decimal as {"num", "den", "dp"})"}); + if (fraction == nullptr) { + return std::unexpected( + std::string{R"(a number with a fraction is not exact; write a decimal as {"num", "den", "dp"})"}); + } + return fraction(number); } std::expected operator()(std::string const& text) const { return Value{text}; } std::expected operator()(Json::array_t const& array) const { ValueList items; items.reserve(array.size()); for (Json const& element : array) { - auto item = valueFromJson(element); + auto item = structuralFromJson(element, fraction); if (!item) { return item; } @@ -602,7 +621,7 @@ namespace detail { } ValueRecord fields; for (auto const& [name, member] : object) { - auto field = valueFromJson(member); + auto field = structuralFromJson(member, fraction); if (!field) { return field; } @@ -611,7 +630,26 @@ namespace detail { return Value{std::move(fields)}; } }; - return std::visit(Visitor{}, json.data); + return std::visit(Visitor{.fraction = fraction}, json.data); +} + +/// @brief Reads a value from its JSON form as `valueFromJson` does, except that a number with a fraction or an +/// exponent is kept: it becomes the decimal its shortest round-trip text in fixed notation spells +/// (`std::to_chars` with `std::chars_format::fixed`, read by `table::parseDecimal`), so `0.0001` is the +/// decimal 0.0001 with 4 places; where no decimal holds it (more than 18 places, a numerator past int64) it +/// becomes its shortest text, such as `1e+300`. +/// +/// The reply of a query cache entry that holds a record opaquely, a table's page, is read so: its `Number` cells +/// are such numbers, and the strict rule would refuse the whole page. Every other reply keeps the strict rule. +/// Defined in the library, beside the cache that reads it, so this header needs no table header. +/// @param json The JSON value. +/// @return The value, or the reason it is refused. +[[nodiscard]] MORPH_API std::expected tableValueFromJson(Json const& json); + +} // namespace detail + +inline std::expected valueFromJson(Json const& json) { + return detail::structuralFromJson(json, nullptr); } /// @brief Reads a value from its JSON form as a value of @p type. diff --git a/include/morph/ui/view.hpp b/include/morph/ui/view.hpp index cf28b0b36..c7a675bbc 100644 --- a/include/morph/ui/view.hpp +++ b/include/morph/ui/view.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -17,6 +18,7 @@ #include "../reactive/runtime.hpp" #include "../reactive/signal.hpp" +#include "../table/bands.hpp" #include "../util/datetime.hpp" #include "alignment.hpp" #include "badge_style.hpp" @@ -27,6 +29,7 @@ #include "input_emphasis.hpp" #include "page_layout.hpp" #include "text_align.hpp" +#include "value.hpp" /// @file /// @brief The toolkit-agnostic view tree: props, node kinds and their builders. @@ -373,6 +376,85 @@ struct TableSort { [[nodiscard]] bool operator==(TableSort const& other) const = default; }; +/// @brief How a click on a sortable header, or `Enter` or `Space` on a focused one, was modified. +enum class HeaderClick : std::uint8_t { + Plain, ///< No modifier: sort by the column alone. + Shift, ///< `Shift` held: add the column to the sort chain, or flip its direction where it is in it. +}; + +/// @brief The mark a header draws after its label for one key of the sort chain. +/// @param direction The key's direction. +/// @param place The key's place in the chain, from 1. +/// @param count How many keys the chain holds. +/// @return `" ▲"` or `" ▼"` for a chain of one key, else the arrow followed by @p place, such as `" ▲2"`. +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`place`, `count`): a chain position then the chain length, passed by name at the three call sites +[[nodiscard]] inline std::string sortMarkText(SortDirection direction, std::size_t place, std::size_t count) { + std::string mark = direction == SortDirection::Ascending ? " ▲" : " ▼"; + if (count != 1) { + mark += std::to_string(place); + } + return mark; +} + +/// @brief A sorted header's accessible description, for one key of the sort chain; both backends set it from this +/// and nothing else. +/// @param direction The key's direction. +/// @param place The key's place in the chain, from 1. +/// @param count How many keys the chain holds. +/// @return `"sorted ascending"` or `"sorted descending"` for a chain of one key, else, for example, +/// `"sorted ascending, key 2 of 3"`. +[[nodiscard]] inline std::string sortDescription(SortDirection direction, std::size_t place, std::size_t count) { + std::string text = direction == SortDirection::Ascending ? "sorted ascending" : "sorted descending"; + if (count != 1) { + text += ", key " + std::to_string(place) + " of " + std::to_string(count); + } + return text; +} + +/// @brief A column group's header, drawn over its columns while they stand side by side in the layout. +struct TableColumnGroup { + /// @brief The group's caption. + std::string label; + /// @brief The visible place of its first column in the table's arrangement. + std::size_t first = 0; + /// @brief How many visible columns, from `first`, it stands over. + std::size_t count = 0; + /// @brief Whether the group has a filter: its filter button is drawn filled. + bool filtered = false; + + /// @brief Member-wise equality. + /// @param other The group to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(TableColumnGroup const& other) const = default; +}; + +/// @brief One entry of a menu as a `MenuWidget` shows it. +struct MenuEntry { + /// @brief The caption. + std::string label; + /// @brief The icon's name in the theme's icon map; empty shows none. + std::string icon; + /// @brief The chord shown beside the label; empty shows none. + std::string keys; + /// @brief Engaged: a checkable entry with this mark; `nullopt`: not checkable. + std::optional checked; + /// @brief Whether the entry can be chosen, or its submenu opened. + bool enabled = true; + /// @brief The submenu; empty for an entry that is chosen. + std::vector items; + /// @brief Whether the entry is a line between entries: never chosen, never opened, and its other fields empty. + bool separator = false; + /// @brief A muted line of help shown with the entry; empty shows none. + std::string description; + /// @brief Whether the entry is a label that is not a command: drawn as muted text, exposed as static text, never + /// chosen or opened. Its other fields are empty. + bool heading = false; + + /// @brief Memberwise equality, submenus included. + /// @return Whether every field matches. + bool operator==(MenuEntry const&) const = default; +}; + /// @brief How much space a widget asks for along one dimension, in backend units (a character cell on the TUI). struct Sizing { /// @brief The sizing rule. @@ -485,8 +567,9 @@ struct Common { /// @brief The stable identifier an automated test finds the widget by; empty means none. Set once. std::string testId; /// @brief The name a focus request after mount finds the widget by (`Mounted::focus`), such as a document - /// element's id; empty means none. Set once. - std::string focusId; + /// element's id; empty means none. Bound, the widget is found by the name it has now: an element in a + /// table cell a pooled cell shows for another row takes that row's name. + Prop focusId; /// @brief Text shown while the pointer rests on the widget; empty shows none. Prop tooltip; /// @brief The named token set of the theme that styles this node and everything inside it; empty is the @@ -829,15 +912,19 @@ struct Column { bool holder = false; }; -/// @brief A table cell that covers rows below its own: the cell of @ref column in the row that gives it, extended -/// down over @ref rows rows counting that row. +/// @brief A table cell that covers cells below and beside its own: the cell of @ref column in the row that gives it, +/// extended down over @ref rows rows counting that row, and right over @ref columns visible columns counting +/// its own. struct RowSpan { /// @brief The column's index in the table's columns; the select column is not one. std::size_t column = 0; /// @brief How many rows the cell covers, the row that gives it included; 1 covers nothing. std::size_t rows = 1; + /// @brief How many columns the cell covers by visible position, its own included; 1 covers nothing beside it. The + /// giver cuts it where a column the span names was moved away or hidden (`cutColumns`). + std::size_t columns = 1; - /// @brief Whether two spans name the same column and count. + /// @brief Whether two spans name the same column and counts of rows and columns. /// @param other The other span. /// @return True when equal. [[nodiscard]] bool operator==(RowSpan const& other) const noexcept = default; @@ -1197,6 +1284,120 @@ struct Virtualization { /// @brief How many rows beyond the visible range, on each side, keep a realized widget so a small scroll does /// not have to realize a widget on every frame; set once. std::size_t overscan = 10; + /// @brief Above this many visible columns, a table over a `TableSource` realizes only the columns in or near the + /// horizontal viewport; set once. + std::size_t columnThreshold = 40; + /// @brief Above this many cells (rows times visible columns), such a table windows both its rows and its columns; + /// set once. + std::size_t cellThreshold = 20'000; + /// @brief How many columns beyond the horizontal viewport, on each side, keep realized cells; set once. + std::size_t columnOverscan = 4; + /// @brief The most cells one pass of a table's windows builds or binds to another row or column; the rest draw + /// blank at their column's width and are realized over the following turns; set once. + std::size_t realizePerFrame = 240; +}; + +/// @brief Which of a table's columns show, in which order, how many are pinned, and the widths the user set. +struct TableArrangement { + /// @brief Indices into `Table::columns`, in layout order; empty shows every column in its own order. + std::vector visible; + /// @brief How many of the leading visible columns stay in view whatever the horizontal scroll. + std::size_t pinned = 0; + /// @brief Widths the user set, in `Sizing` units, by index into `Table::columns`; measurement does not change such + /// a width. + std::map widths; + + /// @brief Member-wise equality. + /// @param other The arrangement to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(TableArrangement const& other) const = default; +}; + +/// @brief One part of a header band as the backend draws it: a run of the band's columns that stand together in the +/// layout, on one side of the pinned edge. +struct BandRun { + /// @brief The band's level, 0 for the outermost. + std::size_t level = 0; + /// @brief The band's text. + std::string label; + /// @brief The unit shown after the label; empty for none. + std::string unit; + /// @brief The visible position of the run's first column (not an index into `Table::columns`). + std::size_t first = 0; + /// @brief How many visible columns the run covers, from `first`. + std::size_t count = 0; + /// @brief Whether the run lies in the pinned part. + bool pinned = false; + + /// @brief Member-wise equality. + /// @param other The run to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(BandRun const& other) const = default; +}; + +/// @brief The row a linked chart highlights: its key, and the view row the server has it at. +struct TableHighlight { + /// @brief The row's key. + Key key; + /// @brief Its view row when the highlight was set. + std::size_t row = 0; + + /// @brief Member-wise equality. + /// @param other The highlight to compare with. + /// @return `true` when key and row match. + [[nodiscard]] bool operator==(TableHighlight const& other) const = default; +}; + +/// @brief A cell by its row's key and its column's id. +struct CellRef { + /// @brief The row's key. + Key key; + /// @brief The column's id (`TableColumn::id`). + std::string column; + + /// @brief Member-wise equality. + /// @param other The cell to compare with. + /// @return `true` when key and column match. + [[nodiscard]] bool operator==(CellRef const& other) const = default; +}; + +/// @brief A rectangle of cells by its two corners: the rows between the corners' keys' view positions and the columns +/// between their ids' places in the layout, both ends included. A sort or a column move keeps the corners, so +/// the rectangle they span may change, as a spreadsheet's does. +struct CellRange { + /// @brief The corner the selection started from. + CellRef anchor; + /// @brief The corner it was extended to. + CellRef focus; + + /// @brief Member-wise equality. + /// @param other The range to compare with. + /// @return `true` when both corners match. + [[nodiscard]] bool operator==(CellRange const& other) const = default; +}; + +/// @brief A grid's focused cell as the mount shows it: a row by key, or by view position while the row there is not +/// fetched yet, and a column by id. +struct GridFocus { + /// @brief The row's key; empty while the row at `viewRow` is not fetched yet (a placeholder). + std::optional key; + /// @brief The row's view position: read only while `key` is empty. + std::size_t viewRow = 0; + /// @brief The column's id (`TableColumn::id`). + std::string column; + + /// @brief Member-wise equality. + /// @param other The focus to compare with. + /// @return `true` when key, view row and column match. + [[nodiscard]] bool operator==(GridFocus const& other) const = default; +}; + +/// @brief What a table's key handler did with a chord. +enum class KeyOutcome : std::uint8_t { + Handled, ///< The table took the key. + Ignored, ///< The table did not take it. + FocusNext, ///< Focus leaves the table for the next control of the focus chain. + FocusPrevious, ///< Focus leaves the table for the previous control of the focus chain. }; /// @brief One widget per row of a keyed collection, updated in place when a row with the same key changes. @@ -1217,8 +1418,216 @@ struct ForEach { bool divided = false; }; +class TableRows; + +/// @brief Whether a cell's value is here, for a table mounted over a `TableSource`: read from the row's +/// `TableRows::unloadedLevels` and the level of the cell's column. +enum class CellLoad : std::uint8_t { + Loaded, ///< The value is here, or the column has no level. + Unloaded, ///< The column's level has not loaded for the row: a placeholder of a fixed width. + Failed, ///< The column's level failed to load for the row: an error mark of the same width. +}; + +/// @brief What a table cell shows beside its text: its tone, its tooltip, and whether its value could not be read. +struct CellAccent { + /// @brief The cell's tone: the theme's tone surface under its selection and focus marks; disengaged for none. + std::optional tone; + /// @brief The cell's tooltip, and its accessible description; empty for none. + std::string tooltip; + /// @brief Whether the value could not be read as the column's kind: the backend draws its error mark in place of + /// the text, and `tooltip` says so. + bool invalid = false; + + /// @brief Member-wise equality. + /// @param other The accent to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(CellAccent const& other) const = default; +}; + +/// @brief A table cell with an accent: a node a `TableSource::cellView` or `defaultCellView` returns. Mounted as a +/// cell of a source table, its content is the cell and its accent is bound in the cell's own scope and told +/// to `TableWidget::setCellAccent`; mounted anywhere else, its content is mounted and the accent is not read. +struct AccentedCell { + /// @brief The cell's content. Must not be null. + Node content; + /// @brief The accent. + Prop accent; +}; + +/// @brief What marks one cell of an editable table: read-only, changed since the record was loaded, not encoding, +/// being +/// saved, or being recomputed. +struct CellMarks { + /// @brief The cell takes no edit: drawn on the theme's read-only cell surface. + bool readOnly = false; + /// @brief The cell's value differs from the loaded one: the theme's modified mark. + bool modified = false; + /// @brief The cell's draft does not encode, or the server refused it: the theme's error mark. + bool error = false; + /// @brief The cell's value is being saved, or is the last one known: drawn stale. + bool stale = false; + /// @brief The cell's value is being recomputed: drawn muted. + bool muted = false; + + /// @brief Member-wise equality. + /// @param other The marks to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(CellMarks const& other) const = default; +}; + +/// @brief A table cell with marks: a node a `TableSource::cellView` returns. Mounted as a cell of a source table, its +/// content is the cell and its marks are bound in the cell's own scope and told to `TableWidget::setCellMarks` +/// on every change and whenever the cell is attached to a row; mounted anywhere else, its content is mounted +/// and the marks are not read. Its content may be an `AccentedCell`, whose accent is bound in the same scope. +struct MarkedCell { + /// @brief The cell's content. Must not be null. + Node content; + /// @brief The marks. + Prop marks; +}; + +/// @brief What marks a whole row: it is being worked on, it is locked by someone else, or it is kept in view although +/// it no longer matches the filter. A row's marks do not vary by cell, so its row look carries them. +struct RowMarks { + /// @brief An action of this session is working on the row. + bool busy = false; + /// @brief Another user holds the row; it cannot be edited here. + bool locked = false; + /// @brief The row is retained and the filter rejects it: it draws muted. + bool unmatched = false; + /// @brief What the row's tooltip says of its marks; empty for none. + std::string tooltip; + + /// @brief Member-wise equality. + /// @param other The marks to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(RowMarks const& other) const = default; +}; + +/// @brief Rows whose keys an action changed, for the mount to move what it holds by key: its focus and its +/// highlighted row. A generation the mount has applied is not applied again. +struct KeyMoves { + /// @brief Increases with each set of moves; 0 holds none. + std::uint64_t generation = 0; + /// @brief Each row's old key, then its new one. + std::vector> moves; + + /// @brief Member-wise equality. + /// @param other The moves to compare with. + /// @return `true` when generation and moves match. + [[nodiscard]] bool operator==(KeyMoves const& other) const = default; +}; + +/// @brief A row's own parts beyond its cells, for a table mounted over a `TableSource`: built once per realized row +/// key, bound in the row's scope. Nothing per cell is carried here. +struct TableRowLook { + /// @brief The row's tone, bound in the row's scope; disengaged for none. + std::optional>> tone; + /// @brief The row's marks, bound in the row's scope; disengaged for a table whose rows carry none. + std::optional> marks; + /// @brief The row's accessible name, bound in the row's scope; disengaged names the row by its key. + std::optional> label; + /// @brief Whether some cell of the row changed since the record was loaded, bound in the row's scope: the row + /// header's modified mark (`TableWidget::setRowModified`); disengaged for a table whose rows carry none. + std::optional> modified; + /// @brief The cells of this row that cover the rows below, bound in the row's scope; disengaged for none. + std::optional>> spans; + /// @brief Non-null: the row is a heading, this node its one cell spanning every column; no cell is built for it. + Node heading; + /// @brief Whether the row is a summary row: drawn on the theme's summary surface, never selected, activated, + /// focused for an edit or pasted into (`TableWidget::setRowSummary`). Its cells are built as any row's. + bool summary = false; + /// @brief What the row's parts need kept alive while the row is realized, such as the scope they are bound in; + /// the mount holds it with the row. + std::shared_ptr keep; +}; + +/// @brief Where a table's rows come from when they come by view index: the rows, and cells as the mount builds them. +/// +/// The mount realizes the rows in and near view. A realized row holds a signal the mount keeps equal to its record, +/// and one cell per column, each with a signal of its own set to the same record: the cell's view is built once from +/// it, and a change of the row re-evaluates only the cells whose record changed. +struct TableSource { + /// @brief The rows, by view index. Must not be null. + std::shared_ptr rows; + /// @brief One cell's view for the column at an index into `Table::columns` (which holds every column and does + /// not change with the layout), built once per cell widget from a signal the mount sets to the record of + /// the row the cell shows. Must not be empty. + std::function const& row)> cellView; + /// @brief The row's own parts, built once per realized row key from a signal the mount keeps equal to its + /// record; empty for none. + std::function const& row)> rowView; + /// @brief The default cell, shared by every column whose `ownCell` entry is `false`: built once per cell from a + /// signal holding the column it shows (an index into `Table::columns`, which the mount sets when it moves + /// a pooled cell to another column of the same `TextRole`) and one the mount sets to the row's record. + /// Empty: every column's cells come from `cellView`. + std::function const& column, reactive::Signal const& row)> + defaultCellView; + /// @brief Per `Table::columns` index, whether the column's cells come from `cellView`, pooled per column, rather + /// than from `defaultCellView`, pooled per role; a missing entry reads as `true`. + std::vector ownCell; + /// @brief Column ids named to every `TableRows::visible` call, whatever the column window holds: what the row's + /// own parts read. The ids of the columns in the window, and what their cells read, are added per call. + std::vector alwaysFetched; + /// @brief Per `Table::columns` index, the row fields that column's cell reads beside its own id, named to + /// `TableRows::visible` while the column is in the window; a missing entry reads as none. + std::vector> cellReads; + /// @brief Per `Table::columns` index, the level of that column; empty, or an empty entry: the column has none. + std::vector levels; + /// @brief Whether the rows are windowed whatever their count, as a server's rows are. `false` realizes every row + /// while the view holds fewer than `Virtualization::threshold`, as a short table over a document's rows + /// does, and only then draws `TableRowLook::spans`. + bool alwaysWindowed = true; + /// @brief Per `Table::columns` index, whether that column's cells each show one row only: their view shares state + /// with the row's own parts, so when a realized row is given to another key they are destroyed and built + /// for it rather than rebound by their signal. Set it for a column whose cell reads state its row declares; + /// each such cell then costs a build where a rebind would do. A missing entry reads as `false`: the + /// column's cells are rebound to any row. + std::vector rowScopedCells; +}; + +/// @brief A choice the status line offers beside its text, as a button the user may choose. +struct StatusEntry { + /// @brief What the choice reports through `Table::onStatusEntry`. + std::string id; + /// @brief The button's text. + std::string label; + + /// @brief Member-wise equality. + /// @param other The entry to compare with. + /// @return `true` when id and label match. + [[nodiscard]] bool operator==(StatusEntry const& other) const = default; +}; + +/// @brief A table's status line: its counts, the state of its fetches and levels, and the latest message. +struct TableStatus { + /// @brief The leading part: the rows counted, or empty while no total is known. + std::string counts; + /// @brief A failed level or fetch; empty when none. + std::string state; + /// @brief Whether the state offers "Retry", which calls `Table::onRetry`. + bool retry = false; + /// @brief The latest refusal or notice; empty when none. + std::string message; + /// @brief The choices the message offers, after it. + std::vector entries; + /// @brief What stays on the line while its cause lasts, as rows being saved; empty when nothing does. + std::string standing; + /// @brief The choices `standing` offers, after it. + std::vector standingEntries; + /// @brief Whether the line takes space. + bool shown = false; + + /// @brief Member-wise equality. + /// @param other The status to compare with. + /// @return `true` when every member matches. + [[nodiscard]] bool operator==(TableStatus const& other) const = default; +}; + /// @brief One column of a `Table`. struct TableColumn { + /// @brief The column's id; empty for a table built from C++ with no ids. + std::string id; /// @brief The header caption. std::string label; /// @brief The column's width request. A `Stretch` column starts from its content (the larger of its header and its @@ -1240,6 +1649,12 @@ struct TableColumn { Align valign = Align::Center; /// @brief Whether a click on the column's header asks to sort by it (`Table::onSort`). bool sortable = false; + /// @brief The unit the column's values are in, which the header shows after the label (`headerText`) and names + /// in its accessible name (`headerAccessibleName`); empty for none. + std::string unit; + /// @brief Whether the column's header draws a filter button (`Table::onFilter`), filled while `Table::filtered` + /// names the column. + bool filterable = false; /// @brief Whether the column's text cells may break across lines. With `false` each is drawn on one line and cut /// at the column's width with an ellipsis, such as a value with its unit in a narrow column. bool wrap = true; @@ -1277,15 +1692,133 @@ struct Table { bool selectColumn = false; /// @brief The accessible name of the select column's header box. Prop selectAllLabel = std::string{"Select all"}; - /// @brief The column whose header shows the sort, and its direction; none marks no header. The table never + /// @brief The sort chain the headers show, most significant key first; empty marks no header. The table never /// orders its rows itself: they come in the order shown. - Prop> sort; - /// @brief Called with a sortable column's index when the user asks to sort by it (a click on its header). - std::function onSort; + Prop> sort; + /// @brief Called with a sortable column's index when the user asks to sort by it (a click on its header, or + /// `Enter` or `Space` on it), and whether `Shift` was held. + std::function onSort; + /// @brief The entries of a header's menu, given its column (an index into `columns`), or of the table's menu, + /// given none. Empty: no header or table menu. + std::function(std::optional)> menu; + /// @brief Called with the menu's column (none for the table's menu) and the chosen entry's path, an index per + /// level from the top. + std::function, std::vector)> onMenu; + /// @brief Called when the user moves a column's header (a drag, or `Ctrl+Shift+Left` or `Right`), with the + /// column (an index into `columns`) and its new place among the arrangement's visible columns. + std::function onColumnMove; + /// @brief Called when the user drags a header's trailing edge, with the column and its new width in `Sizing` + /// units, or none for a double click on the edge, which gives the column its declared width again. + /// Empty: the edges cannot be dragged. + std::function units)> onColumnResize; + /// @brief Called with a filterable column's index when the user presses its header's filter button. + std::function onFilter; + /// @brief The columns that have a filter, by index into `columns`: their filter buttons are drawn filled and + /// their headers named "{label}, filtered". + Prop> filtered; + /// @brief The column groups whose header row is drawn over their columns; empty draws no group row. + Prop> columnGroups; + /// @brief Called with a group's index into `columnGroups` when the user presses its filter button. + std::function onGroupFilter; + /// @brief The header bands over the columns, outermost first, nested at most `table::kMaxBandLevels` levels; set + /// once. The mount draws each over the runs of its columns the column window shows (`bandRuns`); empty + /// draws none. A table over a `TableSource` only. + std::vector bands; + /// @brief Called when the user asks to copy (`Ctrl+C` on the focused table). + std::function onCopy; /// @brief Called with a row's key when the user activates it (Enter or a double click). std::function onActivate; /// @brief Visibility, enablement, layout, drag-and-drop. Common common{}; + /// @brief When set, `rows` is ignored and rows come by view index from the source; set once. + std::optional source; + /// @brief The status line; the default takes no space. + Prop status; + /// @brief Called when the user chooses the status line's "Retry". + std::function onRetry; + /// @brief Which columns show, their order, the pinned count and the user's widths; a table over a `TableSource` + /// only. The default shows every column, none pinned. + Prop arrangement; + /// @brief The row a linked chart highlights, set once a keyed reply has given its view row: the mount scrolls to + /// it, marks it and follows its key through later changes of the rows. Disengaged: no mark. A table over a + /// `TableSource` only; it never changes the selection or the keyboard focus. + Prop> highlight; + /// @brief Called with a range gesture the backend cannot resolve itself, as the view rows of its anchor and its + /// end and the kind of change; a table over a `TableSource` only. + std::function onSelectRange; + /// @brief The focused cell, which the mount keeps realized whatever the windows; disengaged leaves focus where the + /// user put it. A table over a `TableSource` only, focusing a row the mount has realized. + Prop> focus; + /// @brief Called with the cell the user's keys moved focus to, once its row is fetched. + std::function)> onFocusCell; + /// @brief Called, in place of `onSelectionChange`, when the user asks a `Multiple` table to select every row + /// (`Ctrl+A`): the handler selects the whole view, rows the backend does not hold included. Empty: the + /// backend selects the rows it holds and reports them through `onSelectionChange`. + std::function onSelectAll; + /// @brief The entries of a cell's menu, given its row's key and its column (an index into `columns`), asked for + /// each time the menu opens (a right click, the menu key or a long press on the cell), which focuses the + /// cell, and for a key of `cellMenuKeys` the user presses while the table has the focus, for the focused + /// cell. The mount reads each entry's bound parts once, untracked, and runs the chosen entry's `onSelect`. + /// Empty: no cell menu. + std::function(Key const& row, std::size_t column)> cellMenu; + /// @brief The chords `cellMenu`'s entries may declare in `keys`: while the table has the focus, a key that is one + /// of them asks for the focused cell's entries and runs the one that declares it; any other key never asks. + std::vector cellMenuKeys; + /// @brief The caller's entries of a header's menu, given its column, read when the menu opens: shown after + /// `menu`'s own entries for that column and a separator, and run by the mount when chosen. An entry hidden + /// by its `visible` is left out, and with no entry shown nothing is added. Empty: `menu`'s entries alone. + std::function(std::size_t column)> headerEntries; + /// @brief Whether the header's sort, filter and arrangement gestures are offered, read each time a header's menu + /// opens: while false, every entry `menu` gives for a column is disabled. The gestures' handlers are still + /// called, for the caller to refuse; the table's own menu (`menu` with no column) and `headerEntries` are + /// left as given. + Prop headerEnabled = true; + /// @brief Engaged: the selection is every row of the view less these keys, which the mount gives the backend + /// through `setSelectionView` on each change; when it disengages the mount sets `selection` again. + Prop>> selectionView; + /// @brief Rows an action gave new keys: the mount's focus and highlighted row follow a row from its old key to + /// its new one, and focus the change that removed the old key already moved to the row at its index is + /// taken back to the new key. A table over a `TableSource` only. + Prop keyMoves; + /// @brief Called with the id of the status line's entry the user chose. + std::function onStatusEntry; + /// @brief Engaged: the table's focus is a grid's. The mount shows the cell it names, at its key's view position + /// now, or at `GridFocus::viewRow` while it names no key, and keeps that row realized, fetched or not; a + /// click or a `FocusMove` goes to `onGridFocus` and does not move the mount's own focus. A table over a + /// `TableSource` only. + std::optional>> gridFocus; + /// @brief Called, while `gridFocus` is engaged, with the cell a click or a `FocusMove` resolves to; its key is + /// empty when that row is not fetched yet. + std::function onGridFocus; + /// @brief Called with the cell the user double-clicked. + std::function onActivateCell; + /// @brief Called with the cell the user clicked once, after the click moved focus (a fetched row's only). + std::function onClickCell; + /// @brief Called when focus leaves the table's widget and everything inside it, an open editor included. + std::function onFocusOut; + /// @brief Engaged: the cell whose editor is open, or none. While it names a cell, the mount builds `editor` for + /// it once, mounts it in that cell's row, draws it over the cell and focuses it; a change unmounts it. A + /// table over a `TableSource` only. + std::optional>> editing; + /// @brief Builds the editor of the cell `editing` names. + std::function editor; + /// @brief Called with each chord of `keyChords` pressed while focus is in the table; the outcome says whether the + /// table took it, or whether focus leaves the table along the focus chain. + std::function onKey; + /// @brief The chords `onKey` takes, declared to the backend again on each change. + Prop> keyChords; + /// @brief Called with printable text typed while a cell has focus and no editor is open. + std::function onText; + /// @brief Engaged: the table selects cells, not rows, and this is the selected rectangle, or none. The mount shows + /// it at its corners' view positions and visible places now, so a sort or a column move redraws the + /// rectangle the same corners span; a corner whose row is not in the view, or whose column is hidden, shows + /// none, and the range is kept. The backend draws no row selection and reports no `onSelectionChange`. A + /// table over a `TableSource` only. + std::optional>> cellSelection; + /// @brief Called, while `cellSelection` is engaged, with the rectangle the user selected: a drag from cell to + /// cell, + /// a `Shift`+click, a row header's click or a column header's selection gesture. + std::function)> onCellSelect; }; /// @brief A date, or a date and time, edited in a display zone and reported as an instant. @@ -1752,7 +2285,7 @@ struct NodeData { std::variant + PageRegion, AccentedCell, MarkedCell> kind; }; @@ -1774,6 +2307,30 @@ template /// @return The node. [[nodiscard]] inline Node text(Text spec) { return detail::makeNode(std::move(spec)); } +/// @brief A table cell with an accent. +/// @param content The cell's content; must not be null. +/// @param accent The accent. +/// @return The node. +/// @throws std::invalid_argument when @p content is null. +[[nodiscard]] inline Node accentedCell(Node content, Prop accent) { + if (content == nullptr) { + throw std::invalid_argument{"ui::accentedCell: the content must not be null"}; + } + return detail::makeNode(AccentedCell{.content = std::move(content), .accent = std::move(accent)}); +} + +/// @brief A table cell with marks. +/// @param content The cell's content; must not be null. +/// @param marks The marks. +/// @return The node. +/// @throws std::invalid_argument when @p content is null. +[[nodiscard]] inline Node markedCell(Node content, Prop marks) { + if (content == nullptr) { + throw std::invalid_argument{"ui::markedCell: the content must not be null"}; + } + return detail::makeNode(MarkedCell{.content = std::move(content), .marks = std::move(marks)}); +} + /// @brief A push button. /// @param spec The node. /// @return The node. @@ -1804,6 +2361,45 @@ template /// @return The node. [[nodiscard]] inline Node column(Column spec) { return detail::makeNode(std::move(spec)); } +/// @brief The layout of a table inside the column that takes its place, which holds the table's own layout. The table +/// fills the column across, and along it unless its height is fixed or a stretch: a share of a row is the +/// column's to take (a column's child takes none), and a row offers to fill its height to the column, not to +/// the table inside it, so a content height stretches within the column, which is as tall as the table is or as +/// its row makes it. Placement in the parent (`alignSelf`, `bleed`) is the column's alone. +/// @param placed The table's own layout. +/// @return The layout the table takes inside the column. +[[nodiscard]] inline LayoutHints wrappedTableLayout(LayoutHints placed) { + if (placed.width.kind == Sizing::Kind::Percent) { + placed.width = Sizing::stretch(1); + } + if (placed.height.kind == Sizing::Kind::Content) { + placed.height = Sizing::stretch(1); + } + placed.alignSelf.reset(); + placed.bleed = false; + return placed; +} + +/// @brief A table with other nodes under it, in a column that takes the table's place: the column takes the table's +/// visibility and layout, the table `wrappedTableLayout` within it, and every other common property stays on +/// the table alone, so its test id and the element id a focus request finds name the table. The column has no +/// gap, so a node that draws nothing in place (a dialog) adds no space. +/// @param placed The table's common properties; its layout becomes the one inside the column. +/// @param beside The nodes under the table, in order. +/// @param table Makes the table, after @p placed is changed. +/// @return The column. +[[nodiscard]] inline Node besideTable(Common& placed, std::vector beside, std::function const& table) { + Column wrapper; + wrapper.common.visible = placed.visible; + wrapper.common.layout = placed.layout; + placed.layout = wrappedTableLayout(placed.layout); + wrapper.children.push_back(table()); + for (Node& node : beside) { + wrapper.children.push_back(std::move(node)); + } + return column(std::move(wrapper)); +} + /// @brief Children laid out left to right. /// @param spec The node. /// @return The node. @@ -2042,14 +2638,96 @@ struct TableOptions { bool selectColumn = false; /// @brief The accessible name of the select column's header box. Prop selectAllLabel = std::string{"Select all"}; - /// @brief The column whose header shows the sort, and its direction. - Prop> sort; - /// @brief Called with a sortable column's index when the user asks to sort by it. - std::function onSort; + /// @brief The sort chain the headers show, most significant key first. + Prop> sort; + /// @brief Called with a sortable column's index when the user asks to sort by it, and whether `Shift` was held. + std::function onSort; + /// @brief The entries of a header's menu, given its column, or of the table's menu, given none. + std::function(std::optional)> menu; + /// @brief Called with the menu's column (none for the table's menu) and the chosen entry's path. + std::function, std::vector)> onMenu; + /// @brief Called with a column the user moved and its new place among the visible columns. + std::function onColumnMove; + /// @brief Called with a column the user resized and its width in units, or none to restore its declared width. + std::function units)> onColumnResize; + /// @brief Called with a filterable column's index when the user presses its filter button. + std::function onFilter; + /// @brief The columns that have a filter. + Prop> filtered; + /// @brief The column groups whose header row is drawn over their columns. + Prop> columnGroups; + /// @brief Called with a group's index when the user presses its filter button. + std::function onGroupFilter; + /// @brief The header bands over the columns (`Table::bands`). + std::vector bands; + /// @brief Called when the user asks to copy (`Ctrl+C` on the focused table). + std::function onCopy; /// @brief Called with a row's key when the user activates it. std::function onActivate; /// @brief Visibility, enablement, layout, drag-and-drop of the table. Common common{}; + /// @brief When set, the table's rows come by view index from the source, and the rows a builder is given are + /// ignored. + std::optional source; + /// @brief The status line; the default takes no space. + Prop status; + /// @brief Called when the user chooses the status line's "Retry". + std::function onRetry; + /// @brief Which columns show, their order, the pinned count and the user's widths. + Prop arrangement; + /// @brief The row a linked chart highlights; disengaged for none. + Prop> highlight; + /// @brief Called with a range gesture the backend cannot resolve itself, as two view rows and the kind of change. + std::function onSelectRange; + /// @brief The focused cell; disengaged leaves focus where the user put it. + Prop> focus; + /// @brief Called with the cell the user's keys moved focus to, once its row is fetched. + std::function)> onFocusCell; + /// @brief Called, in place of `onSelectionChange`, when the user asks a `Multiple` table to select every row + /// (`Ctrl+A`): the handler selects the whole view, rows the backend does not hold included. Empty: the + /// backend selects the rows it holds and reports them through `onSelectionChange`. + std::function onSelectAll; + /// @brief The entries of a cell's menu, given its row's key and its column; empty for no cell menu. + std::function(Key const& row, std::size_t column)> cellMenu; + /// @brief The chords `cellMenu`'s entries may declare; any other key never asks for a cell's entries. + std::vector cellMenuKeys; + /// @brief The caller's entries of a header's menu, given its column, shown after `menu`'s own. + std::function(std::size_t column)> headerEntries; + /// @brief Whether the header's sort, filter and arrangement entries are enabled. + Prop headerEnabled = true; + /// @brief Engaged: the selection is every row of the view less these keys, which the mount gives the backend + /// through `setSelectionView` on each change; when it disengages the mount sets `selection` again. + Prop>> selectionView; + /// @brief Rows an action gave new keys: the mount's focus and highlighted row follow a row from its old key to + /// its new one, and focus the change that removed the old key already moved to the row at its index is + /// taken back to the new key. A table over a `TableSource` only. + Prop keyMoves; + /// @brief Called with the id of the status line's entry the user chose. + std::function onStatusEntry; + /// @brief Engaged: the table's focus is a grid's (`Table::gridFocus`). + std::optional>> gridFocus; + /// @brief Called with the cell a click or a `FocusMove` resolves to, while `gridFocus` is engaged. + std::function onGridFocus; + /// @brief Called with the cell the user double-clicked. + std::function onActivateCell; + /// @brief Called with the cell the user clicked once (`Table::onClickCell`). + std::function onClickCell; + /// @brief Called when focus leaves the table and everything inside it. + std::function onFocusOut; + /// @brief Engaged: the cell whose editor is open, or none (`Table::editing`). + std::optional>> editing; + /// @brief Builds the editor of the cell `editing` names. + std::function editor; + /// @brief Called with each chord of `keyChords` pressed while focus is in the table. + std::function onKey; + /// @brief The chords `onKey` takes. + Prop> keyChords; + /// @brief Called with printable text typed while a cell has focus and no editor is open. + std::function onText; + /// @brief Engaged: the table selects cells, and this is the selected rectangle (`Table::cellSelection`). + std::optional>> cellSelection; + /// @brief Called with the rectangle the user selected (`Table::onCellSelect`). + std::function)> onCellSelect; }; /// @brief What a table's row view builds for one row: its cells, one per column, and its tone. @@ -2148,8 +2826,113 @@ template spec.selectAllLabel = std::move(options.selectAllLabel); spec.sort = std::move(options.sort); spec.onSort = std::move(options.onSort); + spec.menu = std::move(options.menu); + spec.onMenu = std::move(options.onMenu); + spec.onColumnMove = std::move(options.onColumnMove); + spec.onColumnResize = std::move(options.onColumnResize); + spec.onFilter = std::move(options.onFilter); + spec.filtered = std::move(options.filtered); + spec.columnGroups = std::move(options.columnGroups); + spec.onGroupFilter = std::move(options.onGroupFilter); + spec.bands = std::move(options.bands); + spec.onCopy = std::move(options.onCopy); + spec.onActivate = std::move(options.onActivate); + spec.common = std::move(options.common); + spec.source = std::move(options.source); + spec.status = std::move(options.status); + spec.onRetry = std::move(options.onRetry); + spec.arrangement = std::move(options.arrangement); + spec.highlight = std::move(options.highlight); + spec.onSelectRange = std::move(options.onSelectRange); + spec.focus = std::move(options.focus); + spec.onFocusCell = std::move(options.onFocusCell); + spec.onSelectAll = std::move(options.onSelectAll); + spec.cellMenu = std::move(options.cellMenu); + spec.cellMenuKeys = std::move(options.cellMenuKeys); + spec.headerEntries = std::move(options.headerEntries); + spec.headerEnabled = std::move(options.headerEnabled); + spec.selectionView = std::move(options.selectionView); + spec.keyMoves = std::move(options.keyMoves); + spec.onStatusEntry = std::move(options.onStatusEntry); + spec.gridFocus = std::move(options.gridFocus); + spec.onGridFocus = std::move(options.onGridFocus); + spec.onActivateCell = std::move(options.onActivateCell); + spec.onClickCell = std::move(options.onClickCell); + spec.onFocusOut = std::move(options.onFocusOut); + spec.editing = std::move(options.editing); + spec.editor = std::move(options.editor); + spec.onKey = std::move(options.onKey); + spec.keyChords = std::move(options.keyChords); + spec.onText = std::move(options.onText); + spec.cellSelection = std::move(options.cellSelection); + spec.onCellSelect = std::move(options.onCellSelect); + return detail::makeNode(std::move(spec)); +} + +/// @brief A table whose rows come by view index from a `TableSource`: the mount realizes the rows in and near view, +/// builds each cell from its column's view, and keeps a row's widget when the row moves. +/// @param columns The columns, in order. +/// @param source The rows, the cells and the row's own parts. +/// @param options Selection, sorting, the status line and `Common`; its `source` is replaced by @p source. +/// @return The node. +/// @throws std::invalid_argument when @p source has no rows or no cell view. +[[nodiscard]] inline Node table(std::vector columns, TableSource source, TableOptions options = {}) { + if (!source.rows || !source.cellView) { + throw std::invalid_argument{"ui::table: a table source needs its rows and its cell view"}; + } + Table spec{ + .columns = std::move(columns), + .rows = nullptr, + .showHeader = options.showHeader, + .virtualize = options.virtualize, + .selectionMode = options.selectionMode, + }; + spec.selection = std::move(options.selection); + spec.onSelectionChange = std::move(options.onSelectionChange); + spec.selectColumn = options.selectColumn; + spec.selectAllLabel = std::move(options.selectAllLabel); + spec.sort = std::move(options.sort); + spec.onSort = std::move(options.onSort); + spec.menu = std::move(options.menu); + spec.onMenu = std::move(options.onMenu); + spec.onColumnMove = std::move(options.onColumnMove); + spec.onColumnResize = std::move(options.onColumnResize); + spec.onFilter = std::move(options.onFilter); + spec.filtered = std::move(options.filtered); + spec.columnGroups = std::move(options.columnGroups); + spec.onGroupFilter = std::move(options.onGroupFilter); + spec.bands = std::move(options.bands); + spec.onCopy = std::move(options.onCopy); spec.onActivate = std::move(options.onActivate); spec.common = std::move(options.common); + spec.source = std::move(source); + spec.status = std::move(options.status); + spec.onRetry = std::move(options.onRetry); + spec.arrangement = std::move(options.arrangement); + spec.highlight = std::move(options.highlight); + spec.onSelectRange = std::move(options.onSelectRange); + spec.focus = std::move(options.focus); + spec.onFocusCell = std::move(options.onFocusCell); + spec.onSelectAll = std::move(options.onSelectAll); + spec.cellMenu = std::move(options.cellMenu); + spec.cellMenuKeys = std::move(options.cellMenuKeys); + spec.headerEntries = std::move(options.headerEntries); + spec.headerEnabled = std::move(options.headerEnabled); + spec.selectionView = std::move(options.selectionView); + spec.keyMoves = std::move(options.keyMoves); + spec.onStatusEntry = std::move(options.onStatusEntry); + spec.gridFocus = std::move(options.gridFocus); + spec.onGridFocus = std::move(options.onGridFocus); + spec.onActivateCell = std::move(options.onActivateCell); + spec.onClickCell = std::move(options.onClickCell); + spec.onFocusOut = std::move(options.onFocusOut); + spec.editing = std::move(options.editing); + spec.editor = std::move(options.editor); + spec.onKey = std::move(options.onKey); + spec.keyChords = std::move(options.keyChords); + spec.onText = std::move(options.onText); + spec.cellSelection = std::move(options.cellSelection); + spec.onCellSelect = std::move(options.onCellSelect); return detail::makeNode(std::move(spec)); } diff --git a/scripts/branch_partial_allowlist.json b/scripts/branch_partial_allowlist.json index ddfcb939b..a4077f5ab 100644 --- a/scripts/branch_partial_allowlist.json +++ b/scripts/branch_partial_allowlist.json @@ -109,7 +109,7 @@ }, { "file": "include/morph/core/bridge.hpp", - "line": 2227, + "line": 2229, "source": "if (_executeDeadline.count() <= 0 || !_timeoutScheduler) {", "reason": "The `!_timeoutScheduler` disjunct is unreachable by construction. `setExecuteDeadline` is the only writer of both `_executeDeadline` and `_timeoutScheduler`, and it creates `_timeoutScheduler` in the same call that makes `_executeDeadline` positive; nothing resets `_timeoutScheduler` to null afterwards (setting the deadline back to 0 only stops new calls from arming it, per that method's doc comment). So `_executeDeadline > 0 && !_timeoutScheduler` cannot hold once any positive deadline has been set." }, @@ -121,28 +121,28 @@ }, { "file": "src/ui/document.cpp", - "line": 1659, + "line": 1768, "source": "default:", "context": "download(cmd, fields, primary, path);", "reason": "The default arm is unreachable: the switch names every enumerator of CommandKind, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is DocumentParser::command's switch over the command kinds." }, { "file": "src/ui/document.cpp", - "line": 2069, + "line": 2220, "source": "default:", "context": "case Shape::Keys:", "reason": "The default arm is unreachable: the switch names every enumerator of detail::Shape, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is DocumentParser::entry's switch over a key's shape." }, { "file": "src/ui/document.cpp", - "line": 4630, + "line": 5535, "source": "default:", "context": "if (cmd.value) {", "reason": "The default arm is unreachable: the switch names every enumerator of CommandKind, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is DocumentValidator::checkCommand's switch." }, { "file": "src/ui/document.cpp", - "line": 4972, + "line": 5879, "source": "default: {", "reason": "The default arm is unreachable: the switch names every enumerator of NameCategory, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is ScopeResolver::ref's switch over what a name declares." }, @@ -162,7 +162,7 @@ }, { "file": "src/ui/expression.cpp", - "line": 1232, + "line": 1236, "source": "default:", "context": "return items;", "reason": "The default arm is unreachable: the switch names every enumerator of ExprKind, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is Evaluator::eval's switch." diff --git a/scripts/check_branch_coverage.py b/scripts/check_branch_coverage.py index 2b97cc516..72ba5a5c0 100644 --- a/scripts/check_branch_coverage.py +++ b/scripts/check_branch_coverage.py @@ -189,15 +189,21 @@ def parse_lcov(path, repo_root): return files -# The compiled half of morph::ui lives in src/ui and is scored with the headers under include/morph/ui, under the same -# floor: moving code from a header to a translation unit must not move it out of the gate. -COMPILED_UI_PREFIX = "src/ui/" +# The compiled halves of morph::ui, morph::table and morph::forms live in src/ and are scored with the +# headers under include/morph/, under the same floor: moving code from a header to a translation unit must +# not move it out of the gate. The other src/ directories are front ends (qt, qt_quick, tui, client), not scored here. +COMPILED_PREFIXES = { + "src/ui/": "include/morph/ui", + "src/table/": "include/morph/table", + "src/forms/": "include/morph/forms", +} def subsystem_of(path): """The FLOORS key a source path is scored under, or None when the gate does not score it.""" - if path.startswith(COMPILED_UI_PREFIX): - return "include/morph/ui" + for prefix, subsystem in COMPILED_PREFIXES.items(): + if path.startswith(prefix): + return subsystem if not path.startswith("include/morph/"): return None parts = path.split("/") @@ -744,10 +750,18 @@ def with_partial_line(arms=(True, False)): fail("a below-floor src/ui source was not scored under include/morph/ui", output) else: note("ok: src/ui sources are scored under the include/morph/ui floor") - if subsystem_of("src/ui/interpreter.cpp") != "include/morph/ui" or subsystem_of("src/tui/x.cpp") is not None: - fail("subsystem_of maps src/ui wrongly, or scores src/tui") + compiled = { + "src/ui/interpreter.cpp": "include/morph/ui", + "src/table/table.cpp": "include/morph/table", + "src/forms/forms.cpp": "include/morph/forms", + "src/tui/x.cpp": None, + "src/qt_quick/x.cpp": None, + } + wrong = {path: subsystem_of(path) for path, want in compiled.items() if subsystem_of(path) != want} + if wrong: + fail(f"subsystem_of maps a src/ path wrongly: {wrong}") else: - note("ok: subsystem_of maps src/ui and nothing else under src/") + note("ok: subsystem_of maps src/ui, src/table and src/forms to their headers, and nothing else under src/") # 5. A partial line is a line that RAN with an untaken arm -- not a line that # never ran. Conflating the two would let this gate report partials where diff --git a/scripts/coverage.sh b/scripts/coverage.sh index 3e664ee8b..0f41774c6 100644 --- a/scripts/coverage.sh +++ b/scripts/coverage.sh @@ -205,7 +205,7 @@ done <<< "$_MORPH_LADDER_RUNGS" # source-tree path named here, so moc output is excluded automatically — # no separate exclusion mechanism needed. Demo src/, system headers and # fetched dependencies are excluded the same way. -SOURCES=(include/morph src/ui) +SOURCES=(include/morph src/ui src/table src/forms) # examples/common only when this configure also built the ladder # (MORPH_BUILD_LADDER=ON -- see the "coverage leg only" Qt install step in # ci.yml), so this script still works unchanged for a plain diff --git a/src/forms/field_control.cpp b/src/forms/field_control.cpp new file mode 100644 index 000000000..4c47a5f62 --- /dev/null +++ b/src/forms/field_control.cpp @@ -0,0 +1,263 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::forms::detail::engine { + +std::string resultText(FormSession const& session) { + if (std::exception_ptr const error = session.lastError()) { + return "error: " + reactive::errorMessage(error); + } + std::optional const& reply = session.lastReply(); + return reply.has_value() ? "ok: " + *reply : std::string{}; +} + +std::optional draftInstant(std::string_view text, bool date, int offsetMinutes) { + std::optional local; + if (date) { + if (isIsoDate(text)) { + local = parseWallClock(std::string{text} + "T00:00"); + } + } else { + local = parseWallClock(text); + } + if (!local) { + return std::nullopt; + } + auto const utc = *local - std::chrono::minutes{date ? 0 : offsetMinutes}; + return time::Timestamp{time::DateTime{std::chrono::time_point_cast(utc)}}; +} + +std::string instantDraft(std::optional const& value, bool date, int offsetMinutes) { + if (!value || !value->hasValue()) { + return {}; + } + auto const instant = + std::chrono::floor((**value).value) + std::chrono::minutes{date ? 0 : offsetMinutes}; + std::string const text = formatWallClock(instant); + return date ? text.substr(0, 10) : text; +} + +ui::FieldState fieldState(FieldState const* field) { + return ui::FieldState{ + .readonly = [field] { return field->readonly().get(); }, + .required = [field] { return field->required().get(); }, + .errors = + [field] { + auto const& error = field->error().get(); + return error.has_value() ? std::vector{error->message} : std::vector{}; + }, + .stale = false, + .description = [field] { return field->help(); }, + }; +} + +ui::Common controlCommon(FieldState const* field) { + ui::Common common{}; + common.testId = "field_" + field->path(); + common.a11y.name = [field] { return field->label(); }; + return common; +} + +ui::Node optionSelect(FieldState* field, ui::SelectStyle style) { + return ui::select(ui::Select{ + .options = + [field] { + std::vector options; + for (ChoiceOption const& option : field->options()) { + options.push_back(ui::SelectOption{.key = ui::Key{option.valueJson}, .label = option.label}); + } + return options; + }, + .selected = [field] -> std::optional { + std::string_view const selected = trim(field->text().get()); + return selected.empty() ? std::nullopt : std::optional{ui::Key{std::string{selected}}}; + }, + .onSelect = + [field](ui::Key const& key) { + if (auto const* const value = std::get_if(&key)) { + field->text().set(*value); + } + }, + .onOpen = [field] { field->retryOptions(); }, + .style = style, + // The cell draws the caption, so the select is told its label and not to show it. + .label = [field] { return field->label(); }, + .showLabel = false, + .field = fieldState(field), + .common = controlCommon(field), + }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity) +ui::Node scalarControl(FormSession& session, FieldState& state) { + FieldState* const field = &state; + FieldSpec const& spec = state.spec(); + auto const textInput = [field](ui::TextInputMode mode, std::string unit = {}, ui::Prop decimals = -1) { + return ui::textInput(ui::TextInput{ + .value = [field] { return field->text().get(); }, + .onChange = [field](std::string text) { field->text().set(std::move(text)); }, + .onSubmit = {}, + .onCommit = {}, + .placeholder = [field] { return field->placeholder(); }, + .mode = mode, + .unit = std::move(unit), + .decimals = std::move(decimals), + .label = [field] { return field->label(); }, + .showLabel = false, + .field = fieldState(field), + .common = controlCommon(field), + }); + }; + // A number's input shows its unit and knows its entry places: an integer's 0, the chosen unit's, a plain + // number's display places, a decimal's declared ones; -1 where none is declared. A record's places + // (`FieldState::places`) replace the canonical unit's, or a plain number's, and no other unit's. + auto const numberInput = [&] { + if (spec.kind == FieldKind::Integer) { + return textInput(ui::TextInputMode::SingleLine, spec.unit, 0); + } + if (!spec.units.empty()) { + return textInput(ui::TextInputMode::SingleLine, spec.unit, [field] { + auto const& units = field->spec().units; + std::size_t const unit = std::min(field->unit().get(), units.size() - 1); + std::optional const places = field->places().get(); + return static_cast(unit == 0 && places.has_value() ? *places : units.at(unit).decimals); + }); + } + int decimals = -1; + if (spec.displayDecimals) { + decimals = static_cast(*spec.displayDecimals); + } else if (spec.decimalPlaces) { + decimals = static_cast(*spec.decimalPlaces); + } + return textInput(ui::TextInputMode::SingleLine, spec.unit, [field, decimals] { + std::optional const places = field->places().get(); + return places.has_value() ? static_cast(*places) : decimals; + }); + }; + auto const dateInput = [&](bool date) { + int const offset = date ? 0 : session.options().displayOffsetMinutes; + // The input shows and reads the session's pattern, which it follows; the draft text below stays ISO. + FormSession const* const owner = &session; + return ui::dateTimeInput(ui::DateTimeInput{ + .value = [field, date, offset] { return draftInstant(trim(field->text().get()), date, offset); }, + .onChange = + [field, date, offset](std::optional const& value) { + field->text().set(instantDraft(value, date, offset)); + }, + .mode = date ? ui::DateMode::Date : ui::DateMode::DateTime, + .offsetMinutes = offset, + .label = [field] { return field->label(); }, + .showLabel = false, + .field = fieldState(field), + .common = controlCommon(field), + .pattern = [owner, date] { return owner->pattern(date); }, + }); + }; + if (spec.kind == FieldKind::Multiline) { + return textInput(ui::TextInputMode::Multiline); + } + if (spec.kind == FieldKind::Integer || spec.kind == FieldKind::Number || spec.kind == FieldKind::Decimal) { + return numberInput(); + } + if (spec.kind == FieldKind::Quantity) { + if (spec.units.size() <= 1) { + return numberInput(); + } + std::vector units; + units.reserve(spec.units.size()); + for (std::size_t i = 0; i < spec.units.size(); ++i) { + units.push_back( + ui::SelectOption{.key = ui::Key{static_cast(i)}, .label = spec.units.at(i).display}); + } + ui::Common unitCommon{}; + unitCommon.testId = "unit_" + field->path(); + unitCommon.a11y.name = [field] { return field->label(); }; + return ui::row(ui::Row{ + .children = {textInput(ui::TextInputMode::SingleLine), + ui::select(ui::Select{ + .options = std::move(units), + .selected = [field] -> std::optional { + return ui::Key{static_cast(field->unit().get())}; + }, + .onSelect = + [field](ui::Key const& key) { + if (auto const* const index = std::get_if(&key); + index != nullptr && *index >= 0) { + field->switchUnit(static_cast(*index)); + } + }, + .style = ui::SelectStyle::Dropdown, + .field = {}, + .common = std::move(unitCommon), + })}, + .gap = 4, + }); + } + if (spec.kind == FieldKind::Boolean) { + return ui::checkbox(ui::Checkbox{ + .label = [field] { return field->label(); }, + .checked = [field] { return trim(field->text().get()) == "true"; }, + .onToggle = [field](bool checked) { field->text().set(checked ? "true" : "false"); }, + .field = fieldState(field), + .common = controlCommon(field), + }); + } + if (spec.kind == FieldKind::Enum) { + return optionSelect(field, spec.widget == "radio" ? ui::SelectStyle::Radio : ui::SelectStyle::Dropdown); + } + if (spec.kind == FieldKind::Choice) { + return ui::row(ui::Row{ + .children = + {optionSelect(field, spec.widget == "radio" ? ui::SelectStyle::Radio : ui::SelectStyle::Dropdown), + ui::busy(ui::Busy{.active = [field] { return field->optionsPending(); }, .label = std::string{}})}, + .gap = 4, + }); + } + if (spec.kind == FieldKind::DateTime || spec.kind == FieldKind::EpochDateTime) { + return dateInput(false); + } + if (spec.kind == FieldKind::Date || spec.kind == FieldKind::EpochDate) { + return dateInput(true); + } + if (spec.kind == FieldKind::Slider) { + return ui::slider(ui::Slider{ + .value = + [field] { + std::string_view const text = trim(field->text().get()); + std::int64_t value = field->spec().sliderMin; + std::from_chars(std::to_address(text.begin()), std::to_address(text.end()), value); + return value; + }, + .minimum = spec.sliderMin, + .maximum = spec.sliderMax, + .step = spec.sliderStep, + .onChange = [field](std::int64_t value) { field->text().set(std::to_string(value)); }, + .field = fieldState(field), + .common = controlCommon(field), + }); + } + return textInput(ui::TextInputMode::SingleLine); +} + +} // namespace morph::forms::detail::engine diff --git a/src/forms/form_session.cpp b/src/forms/form_session.cpp new file mode 100644 index 000000000..68851f131 --- /dev/null +++ b/src/forms/form_session.cpp @@ -0,0 +1,1545 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::forms::detail::engine { + +ValueContext const& SessionCore::values() const { + static_cast(_format.get()); + trackTexts(); + return _values; +} + +std::string const& SessionCore::pattern(bool date) const { + static_cast(_format.get()); + return date ? _options.datePattern : _options.dateTimePattern; +} + +void SessionCore::setFormat(render::NumericLocale locale, std::string datePattern, std::string dateTimePattern) { + _options.locale = locale; + _options.datePattern = std::move(datePattern); + _options.dateTimePattern = std::move(dateTimePattern); + _values.locale = locale; + _format.set(_format.peek() + 1); +} + +void SessionCore::setTranslations(render::TranslationProvider translations, std::string bcp47) { + _options.translations = std::move(translations); + _options.bcp47 = std::move(bcp47); + _values.translations = _options.translations; + _values.bcp47 = _options.bcp47; + _texts.set(_texts.peek() + 1); +} + +void SessionCore::markProgrammatic() const { + if (_programmatic) { + _programmatic(); + } +} + +async::Completion SessionCore::sharedChoices(std::string const& action, std::string request) { + std::string const key = action + '\n' + request; + auto [completion, promise] = async::Completion::makeSettleable(&_rt->owner()); + auto& fetches = *_fetches; + if (auto const found = fetches.find(key); found != fetches.end()) { + if (found->second->reply) { + promise.resolve(*found->second->reply); + } else { + found->second->waiting.push_back(std::move(promise)); + } + return std::move(completion); + } + auto fetch = std::make_shared(); + fetch->waiting.push_back(std::move(promise)); + fetches.emplace(key, fetch); + std::weak_ptr const weak = _fetches; + _choices(action, std::move(request)) + .then([fetch](std::string const& reply) { + fetch->reply = reply; + for (auto& waiter : std::exchange(fetch->waiting, {})) { + waiter.resolve(reply); + } + }) + .onError([fetch, weak, key](std::exception_ptr const& error) { + if (auto const held = weak.lock()) { + if (auto const found = held->find(key); found != held->end() && found->second == fetch) { + held->erase(found); + } + } + for (auto& waiter : std::exchange(fetch->waiting, {})) { + waiter.reject(error); + } + }); + return std::move(completion); +} + +} // namespace morph::forms::detail::engine + +namespace morph::forms { + +// NOLINTNEXTLINE(misc-no-recursion): an Object's or ObjectArray row's members are fields, to the model's depth. +FieldState::FieldState(detail::engine::SessionCore& core MORPH_LIFETIMEBOUND, + FieldSpec const& spec MORPH_LIFETIMEBOUND, std::string path, + std::vector> const* siblings, FieldState const* parent) + : _core{&core}, + _spec{&spec}, + _path{std::move(path)}, + _siblings{siblings}, + _parent{parent}, + _text{core.runtime(), std::string{}}, + _unit{core.runtime(), spec.entryUnit}, + _places{core.runtime(), std::optional{}}, + _engaged{core.runtime(), false}, + _opened{core.runtime(), false}, + _narrow{core.runtime(), std::optional>{}}, + _rows{core.runtime(), std::vector>{}}, + _encoded{core.runtime(), [this] { return computeEncoding(); }}, + _error{core.runtime(), + [this] -> std::optional { + Encoding const& encoding = _encoded.get(); + if (encoding.has_value() && !encoding->has_value()) { + return encoding->error(); + } + return std::nullopt; + }}, + _visible{core.runtime(), + [this] { + if (_spec->hidden) { + return false; + } + return _parent != nullptr || + visibleVerdict(_core->model().rules(), _spec->name, _core->lookup()) != Tri::False; + }}, + _readonly{core.runtime(), + [this] { + if (_spec->readOnly || _spec->computed || _spec->derived || + (_parent != nullptr && _parent->readonly().get())) { + return true; + } + return _parent == nullptr && + readonlyVerdict(_core->model().rules(), _spec->name, _core->lookup()) == Tri::True; + }}, + _required{core.runtime(), + [this] { + return _spec->required || + (_parent == nullptr && + requiredVerdict(_core->model().rules(), _spec->name, _core->lookup()) == Tri::True); + }}, + _offered{core.runtime(), [this] { + std::vector const& all = _fetched ? _fetched->get() : _spec->enumOptions; + std::optional> const& keep = _narrow.get(); + if (!keep.has_value()) { + return all; + } + std::vector kept; + for (ChoiceOption const& option : all) { + if (std::ranges::find(*keep, option.valueJson) != keep->end()) { + kept.push_back(option); + } + } + return kept; + }} { + if (_spec->kind == FieldKind::Object) { + for (FieldSpec const& child : _spec->children) { + _members.push_back(std::make_unique(core, child, _path + "." + child.name, &_members, this)); + } + } +} + +std::string FieldState::label() const { + _core->trackTexts(); + return resolveSlot(i18n::FieldSlot::Label, _spec->title); +} + +std::string FieldState::help() const { + _core->trackTexts(); + return resolveSlot(i18n::FieldSlot::Help, _spec->help); +} + +std::string FieldState::placeholder() const { + if (!_placeholderOverride.empty()) { + return _placeholderOverride; + } + if (_spec->placeholder.empty()) { + return defaultPlaceholder(*_spec); + } + _core->trackTexts(); + return resolveSlot(i18n::FieldSlot::Placeholder, _spec->placeholder); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object asks its members. +bool FieldState::blank() const { + if (_spec->kind == FieldKind::Object) { + if (_spec->truncated) { + return detail::engine::trim(_text.get()).empty(); + } + // NOLINTNEXTLINE(misc-no-recursion): each member answers for itself. + return std::ranges::all_of(_members, [](auto const& entry) { return entry->blank(); }); + } + if (_spec->kind == FieldKind::ObjectArray) { + if (_spec->truncated) { + return detail::engine::trim(_text.get()).empty() && !_engaged.get(); + } + return _rows.get().empty() && !_engaged.get(); + } + return detail::engine::trim(_text.get()).empty(); +} + +RuleOperand FieldState::ruleOperand() const { + Encoding const& encoding = _encoded.get(); + if (!encoding.has_value()) { + return RuleOperand{}; + } + if (!encoding->has_value()) { + return RuleOperand{.state = RuleOperand::State::Invalid, .value = {}}; + } + return RuleOperand{.state = RuleOperand::State::Valid, .value = (*encoding)->value}; +} + +void FieldState::narrowOptions(std::optional> keep) { + if (_narrow.peek() != keep) { + _narrow.set(std::move(keep)); + } +} + +void FieldState::openOptions() { + if (!_opened.peek()) { + _opened.set(true); + } + retryOptions(); +} + +void FieldState::retryOptions() { + if (_optionsQuery != nullptr && !_optionsQuery->pending() && _optionsQuery->error() != nullptr) { + _optionsQuery->refetch(); + } +} + +void FieldState::switchUnit(std::size_t index) { + std::size_t const current = _unit.peek(); + if (index >= _spec->units.size() || index == current || current >= _spec->units.size()) { + return; + } + UnitOption target = _spec->units.at(index); + if (index == 0 && _places.peek().has_value()) { + target.decimals = std::min(*_places.peek(), math::kMaxDecimalPlaces); + } + auto converted = convertDraft(_text.peek(), _spec->units.at(current), target, _core->values().locale); + _core->runtime().batch([&] { + _unit.set(index); + if (!detail::engine::trim(_text.peek()).empty()) { + _text.set(converted.value_or(std::string{})); + } + }); +} + +FieldState* FieldState::member(std::string_view name) const noexcept { + auto const found = std::ranges::find_if(_members, [&](auto const& entry) { return entry->spec().name == name; }); + return found == _members.end() ? nullptr : found->get(); +} + +std::uint64_t FieldState::addRow() { + if (_spec->kind != FieldKind::ObjectArray || _spec->truncated) { + return 0; + } + auto row = std::make_shared(*_core, *_spec, _path, _nextRowKey++, this); + row->start(); + std::uint64_t const key = row->key(); + _core->runtime().batch([&] { + _rows.mutate([&](auto& rows) { rows.push_back(std::move(row)); }); + _engaged.set(true); + }); + return key; +} + +std::uint64_t FieldState::insertRow(std::size_t position) { + if (_spec->kind != FieldKind::ObjectArray || _spec->truncated) { + return 0; + } + auto row = std::make_shared(*_core, *_spec, _path, _nextRowKey++, this); + row->start(); + std::uint64_t const key = row->key(); + _core->runtime().batch([&] { + _rows.mutate([&](auto& rows) { + auto const offset = static_cast(std::min(position, rows.size())); + rows.insert(rows.begin() + offset, std::move(row)); + }); + _engaged.set(true); + }); + return key; +} + +std::vector FieldState::removeRows(std::span keys) { + std::vector removed; + std::vector> const& rows = _rows.peek(); + for (std::size_t at = 0; at < rows.size(); ++at) { + if (std::ranges::contains(keys, rows.at(at)->key())) { + removed.push_back(RemovedRow{.position = at, .row = rows.at(at)}); + } + } + if (!removed.empty()) { + _rows.mutate([&](auto& held) { + std::erase_if(held, [&](auto const& row) { return std::ranges::contains(keys, row->key()); }); + }); + } + return removed; +} + +void FieldState::restoreRows(std::vector rows) { + if (rows.empty()) { + return; + } + _core->runtime().batch([&] { + _rows.mutate([&](auto& held) { + for (RemovedRow& removed : rows) { + auto const offset = static_cast(std::min(removed.position, held.size())); + held.insert(held.begin() + offset, std::move(removed.row)); + } + }); + _engaged.set(true); + }); +} + +std::string FieldState::snapshot() const { + std::string out; + appendSnapshot(out); + return out; +} + +bool FieldState::encodesLike(detail::engine::Json const* value) const { + if (_spec->truncated || _spec->kind == FieldKind::Object || _spec->kind == FieldKind::ObjectArray) { + return false; + } + bool const present = value != nullptr && !value->is_null(); + std::string draft = present ? decodeScalar(*_spec, *value, _core->values(), _places.peek()) : std::string{}; + std::size_t const unit = _spec->entryUnit; + if (unit != 0 && unit < _spec->units.size() && !draft.empty()) { + draft = convertDraft(draft, _spec->units.front(), _spec->units.at(unit), _core->values().locale) + .value_or(std::string{}); + } + Encoding const incoming = encodeScalar(*_spec, draft, unit, _core->values(), _places.peek()); + Encoding const& current = _encoded.peek(); + if (incoming.has_value() != current.has_value()) { + return false; + } + if (!incoming.has_value()) { + return true; + } + return incoming->has_value() && current->has_value() && (*incoming)->json == (*current)->json; +} + +std::expected FieldState::edit(detail::engine::Json const& value) { + if (!value.is_null() && !_spec->truncated) { + if (_spec->kind == FieldKind::Object && !value.is_object()) { + return std::unexpected(std::string{"an object field takes a JSON object"}); + } + if (_spec->kind == FieldKind::ObjectArray && !value.is_array()) { + return std::unexpected(std::string{"a list field takes a JSON array"}); + } + } + _core->runtime().batch([&] { load(&value); }); + return {}; +} + +// NOLINTNEXTLINE(misc-no-recursion,readability-function-cognitive-complexity) +void FieldState::load(detail::engine::Json const* value) { + using detail::engine::Json; + bool const present = value != nullptr && !value->is_null(); + if (_spec->truncated) { + _text.set(present ? detail::engine::toJson(*value) : std::string{}); + _engaged.set(present && value->is_array()); + return; + } + if (_spec->kind == FieldKind::Object) { + for (auto const& entry : _members) { + entry->load(present ? detail::engine::member(*value, entry->spec().name) : nullptr); + } + return; + } + if (_spec->kind == FieldKind::ObjectArray) { + std::vector> loaded; + if (present && value->is_array()) { + for (Json const& element : value->get_array()) { + auto row = std::make_shared(*_core, *_spec, _path, _nextRowKey++, this); + for (auto const& cell : row->fields()) { + cell->load(detail::engine::member(element, cell->spec().name)); + } + row->start(); + loaded.push_back(std::move(row)); + } + } + _rows.set(std::move(loaded)); + _engaged.set(present && value->is_array()); + return; + } + std::string draft = present ? decodeScalar(*_spec, *value, _core->values(), _places.peek()) : std::string{}; + std::size_t const unit = _spec->entryUnit; + if (unit != 0 && unit < _spec->units.size() && !draft.empty()) { + // The wire value is in the canonical unit; the draft is shown in the entry unit. + draft = convertDraft(draft, _spec->units.front(), _spec->units.at(unit), _core->values().locale) + .value_or(std::string{}); + } + _text.set(std::move(draft)); + _unit.set(unit); + _engaged.set(_spec->blankAs == BlankAs::Empty && present && value->is_string()); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object clears its members. +void FieldState::clear() { + _text.set(std::string{}); + _unit.set(_spec->entryUnit); + _engaged.set(false); + for (auto const& entry : _members) { + entry->clear(); + } + _rows.set({}); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object starts its members. +void FieldState::start() { + for (auto const& entry : _members) { + entry->start(); + } + if (_spec->blankAs == BlankAs::Empty) { + _engage = std::make_unique(_core->runtime(), [this] { + if (!detail::engine::trim(_text.get()).empty() && !_engaged.peek()) { + _engaged.set(true); + } + }); + } + if (_spec->kind == FieldKind::Choice && _spec->choice.has_value() && _core->choices()) { + reactive::Runtime& runtime = _core->runtime(); + // A row's member shares its fetches with every row asking the same: a column of rows over five materials + // fetches five times. + _optionsQuery = std::make_unique>( + runtime, + [this](std::string const& request) { + return inRow() ? _core->sharedChoices(_spec->choice->optionsAction, request) + : _core->choices()(_spec->choice->optionsAction, request); + }, + [this] { return optionsRequest(); }); + _fetched = std::make_unique>>(runtime, [this] { + std::optional const& reply = _optionsQuery->value(); + return reply.has_value() ? parseOptions(*reply, *_spec->choice) : std::vector{}; + }); + _clearStale = std::make_unique(runtime, [this] { clearStaleSelection(); }); + } +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's cells are fields. +void FieldState::appendSnapshot(std::string& out) const { + if (_spec->computed || _spec->derived) { + out += "=;"; + return; + } + std::string const& text = _text.peek(); + out += std::to_string(text.size()); + out += ':'; + out += text; + out += std::to_string(_unit.peek()); + out += _engaged.peek() ? '+' : '-'; + for (auto const& entry : _members) { + entry->appendSnapshot(out); + } + for (auto const& row : _rows.peek()) { + out += '#'; + for (auto const& cell : row->fields()) { + cell->appendSnapshot(out); + } + } + out += ';'; +} + +std::string FieldState::resolveSlot(i18n::FieldSlot slot, std::string const& literal) const { + auto const& translations = _core->options().translations; + std::string_view const locale = _core->options().bcp47; + auto const explicitKey = i18n::explicitFieldKey(_spec->i18nKey, slot); + if (_parent == nullptr) { + return render::resolveText(translations, locale, explicitKey, + i18n::fieldKey(_core->model().actionType(), _spec->name, slot), literal); + } + if (translations && explicitKey) { + if (auto hit = translations(*explicitKey, locale)) { + return *std::move(hit); + } + } + return literal; +} + +FieldState* FieldState::sibling(std::string_view name) const { + if (_siblings != nullptr) { + auto const found = + std::ranges::find_if(*_siblings, [&](auto const& entry) { return entry->spec().name == name; }); + if (found != _siblings->end()) { + return found->get(); + } + } + return _parent != nullptr ? _core->topLevel(name) : nullptr; +} + +std::optional FieldState::optionsRequest() const { + if (inRow() && !_opened.get()) { + return std::nullopt; + } + std::string body = "{"; + bool first = true; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): only a Choice asks, and a Choice has its spec. + for (std::string const& parent : _spec->choice.value().dependsOn) { + FieldState const* const source = sibling(parent); + if (source == nullptr) { + return std::nullopt; + } + Encoding const& encoding = source->encoded().get(); + if (!encoding.has_value() || !encoding->has_value()) { + return std::nullopt; + } + body += (first ? "" : ",") + detail::engine::quote(parent) + ":" + (*encoding)->json; + first = false; + } + return body + "}"; +} + +void FieldState::clearStaleSelection() { + if (_optionsQuery->pending() || _optionsQuery->error() != nullptr) { + return; + } + // An idle query (a parent is blank or does not encode) fetched nothing to judge the selection against. + std::optional const request = optionsRequest(); + if (!request.has_value()) { + return; + } + std::vector const& current = _fetched->get(); + std::string_view const selected = detail::engine::trim(_text.get()); + if (selected.empty() || + std::ranges::any_of(current, [&](ChoiceOption const& option) { return option.valueJson == selected; })) { + return; + } + _core->runtime().batch([&] { + _text.set(std::string{}); + _core->markProgrammatic(); + }); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object or a row encodes its members. +std::expected FieldState::encodeMembers( + std::span const> members) const { + std::string json = "{"; + bool first = true; + for (auto const& entry : members) { + Encoding const& encoding = entry->encoded().get(); + if (!encoding.has_value()) { + if (entry->spec().required) { + return std::unexpected(fieldError("incomplete", _core->values())); + } + continue; + } + if (!encoding->has_value()) { + return std::unexpected(encoding->error()); + } + json += (first ? "" : ",") + detail::engine::quote(entry->spec().name) + ":" + (*encoding)->json; + first = false; + } + return json + "}"; +} + +// NOLINTNEXTLINE(misc-no-recursion,readability-function-cognitive-complexity) +Encoding FieldState::computeEncoding() const { + if (_spec->truncated) { + std::string_view const draft = detail::engine::trim(_text.get()); + bool const array = _spec->kind == FieldKind::ObjectArray; + if (draft.empty() && !_engaged.get()) { + return (array && _spec->required) ? Encoding{WireValue{.json = "[]", .value = ui::Value{ui::ValueList{}}}} + : Encoding{}; + } + if (array && (draft == "[]" || draft.empty())) { + return WireValue{.json = "[]", .value = ui::Value{ui::ValueList{}}}; + } + return std::unexpected(fieldError("unrepresentable", _core->values())); + } + if (_spec->kind == FieldKind::Object) { + if (blank()) { + return std::nullopt; + } + auto json = encodeMembers(_members); + if (!json) { + return std::unexpected(json.error()); + } + return WireValue{.json = *std::move(json), .value = ui::Value{}}; + } + if (_spec->kind == FieldKind::ObjectArray) { + auto const& rows = _rows.get(); + if (rows.empty() && !_engaged.get() && !_spec->required) { + return std::nullopt; + } + std::string json = "["; + for (std::size_t i = 0; i < rows.size(); ++i) { + auto row = encodeMembers(rows.at(i)->fields()); + if (!row) { + return std::unexpected(row.error()); + } + json += (i == 0 ? "" : ",") + *row; + } + return WireValue{.json = json + "]", .value = ui::Value{}}; + } + return encodeScalar(*_spec, _text.get(), _unit.get(), _core->values(), _places.get()); +} + +FormSession::FormSession(reactive::Runtime& runtime MORPH_LIFETIMEBOUND, FormModel model, Submitter submit, + ChoiceFetcher choices, FormSessionOptions options) + : _core{std::make_unique(runtime, std::move(model), std::move(choices), + std::move(options))}, + _submit{std::move(submit)}, + _assembled{runtime, [this] { return assemble(); }}, + _ready{runtime, + [this] { + std::optional const& assembled = _assembled.get(); + if (!assembled.has_value()) { + return false; + } + auto const& accepts = _core->options().accepts; + return !accepts || accepts(*assembled); + }}, + _body{runtime, [this] { return _ready.get() ? _assembled.get() : std::optional{}; }}, + _mutation{runtime, [this](std::string body) { return _submit(_core->model().actionType(), std::move(body)); }}, + _attempts{runtime, std::uint64_t{0}}, + _loadGeneration{runtime, std::uint64_t{0}}, + _loads{runtime, std::uint64_t{0}}, + _refusals{runtime, std::map>{}}, + _deriveState{runtime, DeriveState::Current}, + _deriveFailing{runtime, false} { + if (!_submit) { + throw std::invalid_argument{"FormSession: a Submitter is required"}; + } + for (FieldSpec const& spec : _core->model().fields()) { + _fields.push_back(std::make_unique(*_core, spec, spec.name, &_fields, nullptr)); + } + _core->adopt(&_fields); + _core->onProgrammatic([this] { _lastSubmitted = _body.peek(); }); + for (std::size_t i = 0; i < _core->model().groups().size(); ++i) { + _collapsed.push_back(std::make_unique>(runtime, false)); + _tabs.push_back(std::make_unique>(runtime, std::size_t{0})); + } + for (auto const& field : _fields) { + field->start(); + } + markLoaded(); + _autoSubmit = std::make_unique(runtime, [this] { autoSubmit(); }); + _acceptSent = std::make_unique(runtime, [this, &runtime] { + static_cast(_mutation.successCount()); + runtime.untracked([&] { acceptSent(); }); + }); + _refused = std::make_unique(runtime, [this, &runtime] { + std::uint64_t const successes = _mutation.successCount(); + std::exception_ptr const error = _mutation.error(); + runtime.untracked([&] { takeFieldErrors(successes, error); }); + }); +} + +FormSessionOptions const& FormSession::trackedOptions() const { + _core->trackTexts(); + return _core->options(); +} + +std::optional FormSession::rowIndexOf(std::string_view digits) { + std::size_t parsed = 0; + char const* const end = std::to_address(digits.end()); + auto const result = std::from_chars(std::to_address(digits.begin()), end, parsed); + if (digits.empty() || result.ec != std::errc{} || result.ptr != end) { + return std::nullopt; + } + return parsed; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +FieldState& FormSession::field(std::string_view path) const { + FieldState* current = nullptr; + std::span const> scope = _fields; + std::string_view rest = path; + auto const missing = [&] { return std::out_of_range{"FormSession::field: no field '" + std::string{path} + "'"}; }; + while (!rest.empty()) { + auto const dot = rest.find('.'); + std::string_view segment = rest.substr(0, dot); + rest = dot == std::string_view::npos ? std::string_view{} : rest.substr(dot + 1); + std::optional index; + if (auto const bracket = segment.find('['); bracket != std::string_view::npos) { + if (!segment.ends_with(']')) { + throw missing(); + } + index = rowIndexOf(segment.substr(bracket + 1, segment.size() - bracket - 2)); + if (!index.has_value()) { + throw missing(); + } + segment = segment.substr(0, bracket); + } + std::optional key; + if (auto const hash = segment.find('#'); hash != std::string_view::npos && !index.has_value()) { + std::optional const parsed = rowIndexOf(segment.substr(hash + 1)); + if (!parsed.has_value()) { + throw missing(); + } + key = static_cast(*parsed); + segment = segment.substr(0, hash); + } + auto const found = + std::ranges::find_if(scope, [&](auto const& entry) { return entry->spec().name == segment; }); + if (found == scope.end()) { + throw missing(); + } + current = found->get(); + if (key.has_value()) { + auto const& rows = current->rows(); + auto const row = std::ranges::find(rows, *key, &RowState::key); + if (row == rows.end() || rest.empty()) { + throw missing(); + } + scope = (*row)->fields(); + } else if (index.has_value()) { + auto const& rows = current->rows(); + if (*index >= rows.size() || rest.empty()) { + throw missing(); + } + scope = rows.at(*index)->fields(); + } else { + scope = current->members(); + if (!rest.empty() && scope.empty()) { + throw missing(); + } + } + } + if (current == nullptr) { + throw missing(); + } + return *current; +} + +void FormSession::submit() { + // A hook ends an edit not yet committed (a grid's open cell editor), so the body sent holds it. + auto const hooks = _beforeSubmit; + for (auto const& [hookId, hook] : hooks) { + if (hook) { + hook(); + } + } + std::optional const body = _body.peek(); + if (!body.has_value()) { + return; + } + rememberSent(); + _lastSubmitted = body; + if (_mutation.run(*body)) { + _attempts.set(_attempts.peek() + 1); + } +} + +void FormSession::prefill(std::string_view bodyJson) { + auto const dom = detail::engine::parseJson(bodyJson); + if (!dom || !dom->is_object()) { + return; + } + runtime().batch([&] { + for (auto const& field : _fields) { + field->load(detail::engine::member(*dom, field->spec().name)); + } + _core->markProgrammatic(); + }); + markLoaded(); +} + +void FormSession::refill(std::string_view bodyJson) { + auto const dom = detail::engine::parseJson(bodyJson); + if (!dom || !dom->is_object()) { + return; + } + std::vector loaded; + runtime().batch([&] { + for (std::size_t index = 0; index < _fields.size(); ++index) { + FieldState& field = *_fields.at(index); + if (field.snapshot() != _loaded.at(index)) { + continue; + } + detail::engine::Json const* const incoming = detail::engine::member(*dom, field.spec().name); + // An automatic form's saved field is a finished edit only while the record differs from what the + // person typed: the record's form of the same value (`1.000` for `1`) is left out, so a refill + // never rewrites text the person may still be typing. + if (submitMode() == SubmitMode::Automatic && field.encodesLike(incoming)) { + continue; + } + field.load(incoming); + loaded.push_back(index); + } + _core->markProgrammatic(); + }); + for (std::size_t const index : loaded) { + _loaded.at(index) = _fields.at(index)->snapshot(); + reloaded(*_fields.at(index)); + } +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): a path and a JSON value; swapped, the path is not found. +void FormSession::assign(std::string_view path, std::string_view jsonValue) { + FieldState& target = field(path); + auto const dom = detail::engine::parseJson(jsonValue); + if (!dom) { + return; + } + runtime().batch([&] { + target.load(&*dom); + _core->markProgrammatic(); + }); + // A programmatic value is not an edit: the top-level field holding the target counts as loaded. + for (std::size_t index = 0; index < _fields.size(); ++index) { + std::string const& name = _fields.at(index)->spec().name; + if (path.starts_with(name) && + (path.size() == name.size() || path.at(name.size()) == '.' || path.at(name.size()) == '[')) { + _loaded.at(index) = _fields.at(index)->snapshot(); + reloaded(*_fields.at(index)); + } + } +} + +void FormSession::reset() { + runtime().batch([&] { + for (auto const& field : _fields) { + field->clear(); + } + _core->markProgrammatic(); + }); + markLoaded(); +} + +std::size_t FormSession::addBeforeSubmit(std::function hook) { + std::size_t const hookId = ++_nextHook; + _beforeSubmit.emplace_back(hookId, std::move(hook)); + return hookId; +} + +bool FormSession::modified(std::string_view path) const { + FieldState const* state = nullptr; + try { + state = &field(path); + } catch (std::out_of_range const&) { + return false; + } + return modified(*state); +} + +bool FormSession::rowModified(std::string_view arrayPath, std::uint64_t key) const { + RowState const* const row = rowOf(arrayPath, key); + if (row == nullptr) { + return false; + } + static_cast(_loadGeneration.get()); + if (addedSinceLoad(*row)) { + return true; + } + return std::ranges::any_of(row->fields(), [this](auto const& member) { return modified(*member); }); +} + +std::optional FormSession::refusal(std::string_view path) const { + auto const& held = _refusals.get(); + FieldState const* state = nullptr; + try { + state = &field(path); + } catch (std::out_of_range const&) { + return std::nullopt; + } + auto const found = held.find(state->path()); + if (found == held.end() || state->draft() != found->second.draft) { + return std::nullopt; + } + return found->second.message; +} + +void FormSession::revert(std::string_view path) { + if (auto const hash = path.rfind('#'); + hash != std::string_view::npos && path.find('.', hash) == std::string_view::npos) { + std::optional const key = rowIndexOf(path.substr(hash + 1)); + RowState const* const row = key ? rowOf(path.substr(0, hash), *key) : nullptr; + if (row == nullptr) { + return; + } + FieldState& array = field(path.substr(0, hash)); + runtime().batch([&] { + if (addedSinceLoad(*row)) { + array.removeRow(row->key()); + } else { + for (auto const& member : row->fields()) { + restoreLoaded(*member); + } + } + _core->markProgrammatic(); + }); + return; + } + FieldState* state = nullptr; + try { + state = &field(path); + } catch (std::out_of_range const&) { + return; + } + runtime().batch([&] { + restoreLoaded(*state); + _core->markProgrammatic(); + }); +} + +void FormSession::deriveWith(DeriveOptions options) { + _debounce.cancel(); + _derive = std::move(options); +} + +void FormSession::noteCommit() { + if (!_derive.evaluate && !_derive.derive) { + return; + } + if (_round) { + _round->stale = true; + return; + } + if (_derive.scheduler == nullptr) { + startRound(); + return; + } + _debounce = _derive.scheduler->after(_derive.debounce, _deriveScope.guard([this] { startRound(); })); +} + +void FormSession::recalculate() { + if (!_round && (_derive.evaluate || _derive.derive)) { + _debounce.cancel(); + startRound(); + } +} + +std::string FormSession::partialBody() const { + return runtime().untracked([&] { + std::string json = "{"; + bool first = true; + for (auto const& field : _fields) { + std::optional literal = partialOf(*field); + if (!literal) { + continue; + } + json += (first ? "" : ",") + detail::engine::quote(field->spec().name) + ":" + *literal; + first = false; + } + return json + "}"; + }); +} + +DeriveRound FormSession::captureRound() { + DeriveRound round; + round.sequence = ++_sequence; + round.body = partialBody(); + runtime().untracked([&] { + for (auto const& field : _fields) { + collectRowKeys(*field, round.rowKeys); + } + }); + return round; +} + +DeriveLoad FormSession::loadDerived(DeriveRound const& round, Derived const& reply) { + DeriveLoad load; + if (round.sequence < _derivedLoaded) { + return load; + } + _derivedLoaded = round.sequence; + std::vector targets; + std::vector values; + for (Derived::Value const& value : reply.values) { + Resolved const target = resolve(round, value.path); + if (target.kind == Resolved::Kind::Dropped) { + continue; + } + if (target.kind == Resolved::Kind::Missing || !target.field->spec().derived || + isComposite(target.field->spec())) { + load.refused.push_back(value.path); + continue; + } + auto dom = detail::engine::parseJson(value.value.str); + if (!dom) { + load.refused.push_back(value.path); + continue; + } + targets.push_back(target.field); + values.push_back(*std::move(dom)); + } + writeKeepingLoaded( + targets, + [&] { + for (std::size_t at = 0; at < targets.size(); ++at) { + targets.at(at)->load(&values.at(at)); + } + }, + false); + noteLoads(targets.size()); + load.loaded = targets.size(); + return load; +} + +DeriveLoad FormSession::loadDerived(DeriveRound const& round, std::string_view evaluatedBody) { + DeriveLoad load; + if (round.sequence < _evaluationLoaded) { + return load; + } + auto const dom = detail::engine::parseJson(evaluatedBody); + if (!dom || !dom->is_object()) { + return load; + } + _evaluationLoaded = round.sequence; + std::vector> writes; + runtime().untracked([&] { + for (auto const& field : _fields) { + collectComputed(round, *field, *dom, writes); + } + }); + std::vector targets; + targets.reserve(writes.size()); + for (auto const& write : writes) { + targets.push_back(write.first); + } + writeKeepingLoaded( + targets, + [&] { + for (auto const& [field, value] : writes) { + field->load(value); + } + }, + false); + noteLoads(writes.size()); + load.loaded = writes.size(); + return load; +} + +void FormSession::switchUnitsAsLoaded(std::span const> switches) { + if (switches.empty()) { + return; + } + std::vector targets; + for (auto const& entry : switches) { + targets.push_back(entry.first); + } + writeKeepingLoaded(targets, [&] { + for (auto const& [field, index] : switches) { + field->switchUnit(index); + } + }); +} + +std::string FormSession::groupTitle(std::size_t group) const { + FieldGroupSpec const& spec = detail::engine::elementAt(_core->model().groups(), group); + if (spec.implicit) { + return {}; + } + _core->trackTexts(); + return render::resolveText(_core->options().translations, _core->options().bcp47, std::nullopt, + i18n::groupKey(_core->model().actionType(), group), spec.title); +} + +void FormSession::rememberSent() { + runtime().untracked([&] { + if (_mutation.pending()) { + return; + } + // A success the accept effect has not yet seen belongs to the snapshots about to be replaced. + acceptSent(); + _sent.clear(); + for (auto const& field : _fields) { + _sent.push_back(field->snapshot()); + } + }); +} + +bool FormSession::endsEditOnSave(FieldState const& field) const { + if (_core->model().submitMode() == SubmitMode::Explicit) { + return true; + } + FieldSpec const& spec = field.spec(); + return !spec.truncated && spec.kind != FieldKind::Object && spec.kind != FieldKind::ObjectArray; +} + +void FormSession::acceptSent() { + std::uint64_t const successes = _mutation.successCount(); + if (successes == _acceptedSuccesses) { + return; + } + _acceptedSuccesses = successes; + // A reply that names field errors did not save the record: what was sent stays an edit. + if (!fieldErrorsOf(_mutation.lastResult()).empty()) { + _sent.clear(); + return; + } + for (std::size_t index = 0; index < _sent.size(); ++index) { + if (_fields.at(index)->snapshot() == _sent.at(index) && endsEditOnSave(*_fields.at(index))) { + _loaded.at(index) = _sent.at(index); + reloaded(*_fields.at(index)); + } + } + _sent.clear(); +} + +void FormSession::markLoaded() { + _loaded.clear(); + for (auto const& field : _fields) { + _loaded.push_back(field->snapshot()); + } + _loadedCells.clear(); + for (auto const& field : _fields) { + recordLoaded(*field); + } + _loadGeneration.set(_loadGeneration.peek() + 1); + _loads.set(_loads.peek() + 1); +} + +std::map> FormSession::fieldErrorsOf( + std::optional const& reply) const { + std::map> out; + auto const dom = reply ? detail::engine::parseJson(*reply) : std::nullopt; + detail::engine::Json const* const errors = dom ? detail::engine::member(*dom, "errors") : nullptr; + if (errors == nullptr || !errors->is_object()) { + return out; + } + for (auto const& [path, entry] : errors->get_object()) { + std::string message; + if (entry.is_string()) { + message = entry.get_string(); + } else if (entry.is_array() && !entry.get_array().empty() && entry.get_array().front().is_string()) { + message = entry.get_array().front().get_string(); + } + if (message.empty()) { + continue; + } + try { + FieldState const& state = field(path); + out.insert_or_assign(state.path(), Refused{.message = std::move(message), .draft = state.draft()}); + } catch (std::out_of_range const&) { // NOLINT(bugprone-empty-catch) + // A path the form has no field for is not shown at any field. + } + } + return out; +} + +void FormSession::takeFieldErrors(std::uint64_t successes, std::exception_ptr const& error) { + if (successes == _errorsSeenSuccesses && error == _refusalSeen) { + return; + } + bool const succeeded = successes != _errorsSeenSuccesses; + _errorsSeenSuccesses = successes; + _refusalSeen = error; + _refusals.set(succeeded ? fieldErrorsOf(_mutation.lastResult()) : std::map>{}); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields. +void FormSession::recordLoaded(FieldState const& state) { + FieldSpec const& spec = state.spec(); + if (spec.truncated) { + return; + } + // NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields, which the walk visits in turn. + runtime().untracked([&] { + if (spec.kind == FieldKind::Object) { + for (auto const& member : state.members()) { + recordLoaded(*member); + } + } else if (spec.kind == FieldKind::ObjectArray) { + for (auto const& row : state.rows()) { + _loadedCells.insert_or_assign(state.path() + "#" + std::to_string(row->key()), LoadedCell{}); + for (auto const& member : row->fields()) { + recordLoaded(*member); + } + } + } else { + _loadedCells.insert_or_assign(state.path(), LoadedCell{.text = state.draft(), .unit = state.unit().get()}); + } + }); +} + +void FormSession::noteLoads(std::size_t written) { + if (written > 0) { + _loads.set(_loads.peek() + 1); + } +} + +void FormSession::reloaded(FieldState const& state) { + std::string const& name = state.path(); + std::erase_if(_loadedCells, [&name](auto const& entry) { + std::string const& path = entry.first; + return path == name || (path.size() > name.size() && path.starts_with(name) && + (path.at(name.size()) == '.' || path.at(name.size()) == '#')); + }); + recordLoaded(state); + _loadGeneration.set(_loadGeneration.peek() + 1); + _loads.set(_loads.peek() + 1); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object's members are fields. +bool FormSession::modified(FieldState const& state) const { + FieldSpec const& spec = state.spec(); + if (spec.truncated || spec.kind == FieldKind::Object || spec.kind == FieldKind::ObjectArray || spec.computed || + spec.derived) { + return false; + } + static_cast(_loadGeneration.get()); + auto const found = _loadedCells.find(state.path()); + // A member of a row added since the load. + if (found == _loadedCells.end()) { + return true; + } + return state.draft() != found->second.text || state.unit().get() != found->second.unit; +} + +RowState const* FormSession::rowOf(std::string_view arrayPath, std::uint64_t key) const { + FieldState const* array = nullptr; + try { + array = &field(arrayPath); + } catch (std::out_of_range const&) { + return nullptr; + } + if (array->spec().kind != FieldKind::ObjectArray) { + return nullptr; + } + auto const& rows = array->rows(); + auto const found = std::ranges::find(rows, key, &RowState::key); + return found == rows.end() ? nullptr : found->get(); +} + +bool FormSession::addedSinceLoad(RowState const& row) const { + std::string const& first = row.fields().empty() ? std::string{} : row.fields().front()->path(); + // A member's path is `#.`: the row's own entry is the part before the member. + std::string const rowPath = first.substr(0, first.rfind('.')); + return !_loadedCells.contains(rowPath); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object's members are fields. +void FormSession::restoreLoaded(FieldState& state) { + FieldSpec const& spec = state.spec(); + if (spec.truncated || spec.kind == FieldKind::ObjectArray) { + return; + } + if (spec.kind == FieldKind::Object) { + for (auto const& member : state.members()) { + restoreLoaded(*member); + } + return; + } + auto const found = _loadedCells.find(state.path()); + state.text().set(found == _loadedCells.end() ? std::string{} : found->second.text); + state.unit().set(found == _loadedCells.end() ? spec.entryUnit : found->second.unit); +} + +std::optional FormSession::assemble() const { + std::string json = "{"; + bool first = true; + for (auto const& field : _fields) { + Encoding const& encoding = field->encoded().get(); + bool const required = field->required().get(); + std::string literal; + if (!encoding.has_value()) { + if (field->spec().blankAs == BlankAs::Empty && field->engaged().get() && !required) { + literal = R"("")"; + } else if (required) { + return std::nullopt; + } else { + continue; + } + } else if (!encoding->has_value()) { + return std::nullopt; + } else { + literal = (*encoding)->json; + } + json += (first ? "" : ",") + detail::engine::quote(field->spec().name) + ":" + literal; + first = false; + } + if (gatingVerdict(_core->model().rules(), _core->lookup()) == Tri::False) { + return std::nullopt; + } + return json + "}"; +} + +void FormSession::autoSubmit() { + if (_core->model().submitMode() != SubmitMode::Automatic) { + return; + } + // While a Choice's options are in flight its selection is unjudged: a parent just changed, and the selection + // may be one the new options no longer back. Waiting lets the stale selection be cleared first; the settled + // query wakes this Effect again. + if (std::ranges::any_of(_fields, [](auto const& field) { return field->optionsPending(); })) { + return; + } + // The submission is Exclusive: while one is in flight a new run would be refused and its body lost. Waiting + // here sends the latest body once the one in flight settles, which wakes this Effect again. + if (_mutation.pending()) { + return; + } + std::optional const& body = _body.get(); + if (!body.has_value() || body == _lastSubmitted) { + return; + } + _lastSubmitted = body; + rememberSent(); + std::string const toSend = *body; + runtime().untracked([&] { + if (_mutation.run(toSend)) { + _attempts.set(_attempts.peek() + 1); + } + }); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields. +std::optional FormSession::partialOf(FieldState const& field) { + FieldSpec const& spec = field.spec(); + // NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields, which the walk visits in turn. + auto const membersOf = [](std::span const> members) { + std::string json = "{"; + bool first = true; + for (auto const& member : members) { + if (std::optional literal = partialOf(*member)) { + json += (first ? "" : ",") + detail::engine::quote(member->spec().name) + ":" + *literal; + first = false; + } + } + return json + "}"; + }; + if (!spec.truncated && spec.kind == FieldKind::Object) { + std::string json = membersOf(field.members()); + return json == "{}" ? std::nullopt : std::optional{json}; + } + if (!spec.truncated && spec.kind == FieldKind::ObjectArray && !field.rows().empty()) { + std::string json = "["; + bool first = true; + for (auto const& row : field.rows()) { + json += (first ? "" : ",") + membersOf(row->fields()); + first = false; + } + return json + "]"; + } + Encoding const& encoding = field.encoded().get(); + if (encoding.has_value() && encoding->has_value()) { + return (*encoding)->json; + } + if (!encoding.has_value() && spec.blankAs == BlankAs::Empty && field.engaged().get()) { + return std::string{R"("")"}; + } + return std::nullopt; +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields. +void FormSession::collectRowKeys(FieldState const& field, + std::map, std::less<>>& out) { + FieldSpec const& spec = field.spec(); + if (spec.truncated) { + return; + } + if (spec.kind == FieldKind::Object) { + for (auto const& member : field.members()) { + collectRowKeys(*member, out); + } + } else if (spec.kind == FieldKind::ObjectArray) { + std::vector& keys = out[field.path()]; + for (auto const& row : field.rows()) { + keys.push_back(row->key()); + for (auto const& member : row->fields()) { + collectRowKeys(*member, out); + } + } + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per segment's form. +FormSession::Resolved FormSession::resolve(DeriveRound const& round, std::string_view path) const { + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. + return runtime().untracked([&] { + std::span const> scope = _fields; + FieldState* current = nullptr; + std::string_view rest = path; + while (!rest.empty()) { + auto const dot = rest.find('.'); + std::string_view segment = rest.substr(0, dot); + rest = dot == std::string_view::npos ? std::string_view{} : rest.substr(dot + 1); + std::optional index; + if (auto const bracket = segment.find('['); bracket != std::string_view::npos) { + if (!segment.ends_with(']')) { + return Resolved{}; + } + index = rowIndexOf(segment.substr(bracket + 1, segment.size() - bracket - 2)); + if (!index) { + return Resolved{}; + } + segment = segment.substr(0, bracket); + } + auto const found = + std::ranges::find_if(scope, [&](auto const& entry) { return entry->spec().name == segment; }); + if (found == scope.end()) { + return Resolved{}; + } + current = found->get(); + if (index) { + if (current->spec().kind != FieldKind::ObjectArray || rest.empty()) { + return Resolved{}; + } + auto const sent = round.rowKeys.find(current->path()); + if (sent == round.rowKeys.end() || *index >= sent->second.size()) { + return Resolved{}; + } + auto const& rows = current->rows(); + auto const row = std::ranges::find(rows, sent->second.at(*index), &RowState::key); + if (row == rows.end()) { + return Resolved{.kind = Resolved::Kind::Dropped, .field = nullptr}; + } + scope = (*row)->fields(); + } else { + scope = current->members(); + if (!rest.empty() && scope.empty()) { + return Resolved{}; + } + } + } + return current == nullptr ? Resolved{} : Resolved{.kind = Resolved::Kind::Found, .field = current}; + }); +} + +// NOLINTNEXTLINE(misc-no-recursion): an Object's members and a row's are fields. +void FormSession::collectComputed(DeriveRound const& round, FieldState& field, detail::engine::Json const& object, + std::vector>& out) { + FieldSpec const& spec = field.spec(); + if (spec.truncated) { + return; + } + detail::engine::Json const* const value = detail::engine::member(object, spec.name); + if (spec.kind == FieldKind::Object) { + if (value != nullptr && value->is_object()) { + for (auto const& member : field.members()) { + collectComputed(round, *member, *value, out); + } + } + return; + } + if (spec.kind == FieldKind::ObjectArray) { + auto const sent = round.rowKeys.find(field.path()); + if (value == nullptr || !value->is_array() || sent == round.rowKeys.end()) { + return; + } + auto const& elements = value->get_array(); + auto const& rows = field.rows(); + for (std::size_t at = 0; at < elements.size() && at < sent->second.size(); ++at) { + auto const row = std::ranges::find(rows, sent->second.at(at), &RowState::key); + if (row != rows.end() && elements.at(at).is_object()) { + for (auto const& member : (*row)->fields()) { + collectComputed(round, *member, elements.at(at), out); + } + } + } + return; + } + if (spec.computed) { + out.emplace_back(&field, value); + } +} + +bool FormSession::holdsLoaded(FieldState const& field) const { + auto const found = _loadedCells.find(field.path()); + return found != _loadedCells.end() && field.draft() == found->second.text && + field.unit().peek() == found->second.unit; +} + +// NOLINTNEXTLINE(misc-no-recursion): a stale round's settling starts the next round, which settles through its replies in turn. +void FormSession::startRound() { + _debounce.cancel(); + _round = InFlight{.round = captureRound()}; + _round->evaluated = !_derive.evaluate; + _round->derived = !_derive.derive; + _deriveState.set(DeriveState::Running); + std::uint64_t const sequence = _round->round.sequence; + std::string const body = _round->round.body; + if (_derive.evaluate) { + _derive.evaluate(body) + .then(_deriveScope.token(), + [this, sequence](std::string const& reply) { + if (_round && _round->round.sequence == sequence) { + static_cast(loadDerived(_round->round, std::string_view{reply})); + } + settled(sequence, true, false); + }) + .onError(_deriveScope.token(), + [this, sequence](std::exception_ptr const&) { settled(sequence, true, true); }); + } + if (_derive.derive) { + _derive.derive(R"({"body":)" + body + "}") + .then(_deriveScope.token(), + [this, sequence](std::string const& reply) { + bool failed = false; + if (_round && _round->round.sequence == sequence) { + Derived values; + if (auto const error = glz::read(values, reply)) { + failed = true; + } else { + DeriveLoad const load = loadDerived(_round->round, values); + if (!load.refused.empty() && _derive.refused) { + _derive.refused(load.refused); + } + } + } + settled(sequence, false, failed); + }) + .onError(_deriveScope.token(), + [this, sequence](std::exception_ptr const&) { settled(sequence, false, true); }); + } + if (_round->evaluated && _round->derived) { + settled(sequence, true, false); + } +} + +// NOLINTNEXTLINE(misc-no-recursion): a stale round's settling starts the next round, which settles through its replies in turn. +void FormSession::settled(std::uint64_t sequence, bool evaluation, bool failed) { + if (!_round || _round->round.sequence != sequence) { + return; + } + (evaluation ? _round->evaluated : _round->derived) = true; + _round->failed = _round->failed || failed; + if (!_round->evaluated || !_round->derived) { + return; + } + bool const stale = _round->stale; + bool const anyFailed = _round->failed; + _round.reset(); + _deriveState.set(anyFailed ? DeriveState::Failed : DeriveState::Current); + _deriveFailing.set(anyFailed); + if (stale) { + startRound(); + } +} + +} // namespace morph::forms diff --git a/src/qt_quick/CMakeLists.txt b/src/qt_quick/CMakeLists.txt index e8fe1c92b..4b9a5143d 100644 --- a/src/qt_quick/CMakeLists.txt +++ b/src/qt_quick/CMakeLists.txt @@ -72,6 +72,7 @@ qt_add_qml_module(morph_qt_quick_qml qml/MorphTableRow.qml qml/MorphTableRowBackground.qml qml/MorphTableHeaderBackground.qml + qml/MorphTableHeaderEdge.qml qml/MorphDateTimeInput.qml qml/MorphSlider.qml qml/MorphFilePicker.qml diff --git a/src/qt_quick/backend.cpp b/src/qt_quick/backend.cpp index b24ff68b5..634f6c7ff 100644 --- a/src/qt_quick/backend.cpp +++ b/src/qt_quick/backend.cpp @@ -1,9 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 +#include +#include #include #include #include #include +#include +#include +#include #include #include "qt_quick/context.hpp" @@ -21,6 +26,27 @@ void Backend::setOnWidthClass(std::function onWidthCla _context->setOnWidthClass(std::move(onWidthClass)); } +bool Backend::copyText(std::string_view text) { + QClipboard* const clipboard = QGuiApplication::clipboard(); + if (clipboard == nullptr) { + return false; + } + clipboard->setText(detail::toQString(text)); + return true; +} + +std::optional Backend::pasteText() { + QClipboard const* const clipboard = QGuiApplication::clipboard(); + if (clipboard == nullptr) { + return std::nullopt; + } + QString const text = clipboard->text(); + if (text.isEmpty()) { + return std::nullopt; + } + return text.toStdString(); +} + Backend::~Backend() = default; QQuickItem* Backend::itemOf(ui::Widget const& widget) noexcept { diff --git a/src/qt_quick/kinds.hpp b/src/qt_quick/kinds.hpp index a616bcd6d..305d83c4f 100644 --- a/src/qt_quick/kinds.hpp +++ b/src/qt_quick/kinds.hpp @@ -1,12 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once +#include #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -14,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -223,6 +228,10 @@ class MenuImpl final : public ItemWidget { /// entries. [[nodiscard]] bool choosable(std::vector const& entries, std::vector const& path); +/// A menu's entries as MorphMenu reads them: `[{label, icon, keys, checked, enabled, items, separator, description, +/// heading}]`, each submenu's entries in its `items`. +[[nodiscard]] QVariantList menuEntries(std::vector const& entries); + class SpacerImpl final : public ItemWidget { public: SpacerImpl(Context& context, ui::ContainerWidget* parent); @@ -684,18 +693,106 @@ class TableImpl final : public ContainerItemWidget { void setSelectColumn(bool shown) override; void setSelectAllLabel(std::string_view label) override; void setRowLabel(ui::Widget& row, std::string_view label) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setRowMarks(ui::Widget& row, ui::RowMarks const& marks) override; void setRowHeading(ui::Widget& row) override; + void setRowSummary(ui::Widget& row) override; /// Throws std::logic_error when @p row is not one of this table's rows. void setRowSpans(ui::Widget& row, std::vector const& spans) override; void setSelection(std::vector const& keys) override; void setOnSelectionChange( std::function, ui::SelectionChange)> onSelectionChange) override; void setOnActivate(std::function onActivate) override; - void setSort(std::optional sort) override; - void setOnSort(std::function onSort) override; + /// Each header of the chain carries its mark (`ui::sortMarkText`) and its accessible description + /// (`ui::sortDescription`), which MorphTable reads as `sortMarks` and `sortDescriptions`, by column. + void setSort(std::vector const& chain) override; + void setOnSort(std::function onSort) override; + /// A menu opens through MorphTable's `menu` event: its entries are asked for then, and handed to MorphTable's + /// `showMenu`, which shows them in a button-style MorphMenu's popup under the header or the `⋯`. + void setMenu(std::function(std::optional)> entries, + std::function, std::vector)> onChoose) override; + /// A cell's menu opens through its row's `cellMenu` event (a right click or a long press on the cell, or the menu + /// key on the focused cell): its entries are asked for then, and handed to MorphTable's `showCellMenu`, which + /// shows them in the header menu's popup under the cell; a choice comes back as `menuChoose` with the column + /// `kCellMenuColumn`. A key the table leaves is offered to the focused cell's entries through `cellKey`. + void setCellMenu( + std::function(ui::Key const&, std::size_t)> entries, + std::function const&)> chosen) override; + void setCellMenuKeys(std::vector const& chords) override { _cellMenuKeys = chords; } + void setVisibleColumns(std::vector const& visible) override; + void setOnColumnMove(std::function handler) override; + /// MorphTable reports the header's width in pixels; its padding is taken off and the rest rounded to units of + /// `Theme.unitWidth` here. + void setOnColumnResize(std::function)> handler) override; + void setOnFilter(std::function handler) override; + void setFiltered(std::vector const& columns) override; + void setColumnGroups(std::vector const& groups) override; + void setBands(std::vector const& runs) override; + void setOnGroupFilter(std::function handler) override; + void setOnCopy(std::function onCopy) override; void setExistingKeys(std::vector const& keys) override; + void setOnSelectAll(std::function onSelectAll) override; + void setSelectionView(std::vector const& except) override; + void setOnStatusEntry(std::function onStatusEntry) override; void setRealizedWindow(std::size_t first, std::size_t count, std::size_t total) override; void setOnVisibleRangeChanged(std::function onVisibleRangeChanged) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setRowIndex(ui::Widget& row, std::size_t viewRow) override; + /// The status line: one line of text under the rows, a polite live region, with "Retry" while the state offers + /// it; it takes no space while not shown. + void setStatus(ui::TableStatus const& status) override; + void setOnRetry(std::function onRetry) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setCellLoad(ui::Widget& row, std::size_t column, ui::CellLoad load) override; + /// The row's cell draws the tone's tint under its selection and focus marks, the theme's error mark in place of + /// an invalid value, and the "more here" mark and a tooltip (its accessible description) for a tooltip. Throws + /// std::logic_error when @p row is not one of this table's rows. + void setCellAccent(ui::Widget& row, std::size_t column, ui::CellAccent const& accent) override; + /// The window's columns, offsets and widths are pixels: the header and the rows draw these columns only. + void setColumnWindow(std::span columns, std::span offsets, + std::span widths, int totalWidth, std::size_t pinned) override; + /// Only a table over a `TableSource` is given one, before any row: MorphTable then places each row by its view + /// index and each cell by its column. + void setOnHorizontalRange(std::function handler) override; + void setHorizontalOffset(int scrollX) override; + void setOnColumnMeasured( + std::function handler) override; + /// Pixels: a unit is `Theme.unitWidth`, a monospace character `Theme.monoAdvance`, a content column starts at + /// twelve units, and a column's padding is `table.cellPaddingX` a side, as the unwindowed table sizes them. + [[nodiscard]] ui::TableMeasure tableMeasure() const override; + void setFocusCell(std::size_t viewRow, std::size_t column) override; + void setOnFocusMove(std::function handler) override; + /// MorphTable reports printable text typed on its focused cell, while no editor is open, as its `text` event. + void setOnText(std::function onText) override; + /// A row reports a tap on a cell as its `cellClick` event, `{column, double}`. + void setOnCellClick( + std::function onClick) override; + /// MorphTable reports its `focusOut` event once the active focus is outside the table, its editor and its popups. + void setOnFocusOut(std::function onFocusOut) override; + /// The editor's item takes the cell's column, the cell in that column is covered, and the row places the editor + /// over the cell's rectangle. Throws std::logic_error when @p row is not one of this table's rows. + void setCellEditor(ui::Widget& row, std::size_t column, ui::Widget* editor) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setCellMarks(ui::Widget& row, std::size_t column, ui::CellMarks const& marks) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setRowModified(ui::Widget& row, bool modified) override; + /// MorphTable draws the rectangle (`cellRect`, `[firstRow, rowCount, firstPosition, positionCount]`, empty for + /// none) over the rows it spans and the visible columns at those positions. + void setCellSelection(std::optional> rect) override; + /// MorphTable selects cells (`selectsCells`): a drag from cell to cell, a Shift-click, a click on a row's leading + /// edge and a Ctrl-click on a column's header report its `cellSelect` event, and no row is selected. + void setOnCellSelect(std::function + onSelect) override; + /// A tap on a row's cell, reported by the row. + void cellClicked(TableRowImpl const& row, std::size_t column, bool doubleClick) const; + /// Shift with an arrow, a Shift-click and Ctrl+A over a source go to the handler as view rows. + void setOnSelectRange( + std::function handler) override; + void setCounts(std::optional rows, std::size_t columns) override; + void scrollToRow(std::size_t viewRow) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setCellColumn(ui::Widget& row, ui::Widget& cell, std::optional column) override; /// A click on a row, or Space or Shift with an arrow on the current row, as @p click; the table's selection model /// (`ui::TableWidget`). @@ -705,6 +802,10 @@ class TableImpl final : public ContainerItemWidget { void anchorAt(TableRowImpl const& row); /// Ctrl+A in `Multiple` mode: every row, or none when every row is selected already. void selectAll(); + /// Opens the menu of @p row's cell in @p column, after making the row the selection alone when it is not selected. + void openCellMenu(TableRowImpl const& row, std::size_t column); + /// The column MorphTable reports a cell menu's choice with: no header has it. + static constexpr qlonglong kCellMenuColumn = -2; /// A double click on a row, or Enter on it. void activated(TableRowImpl const& row) const; /// The Flickable reported a scroll; @p first and @p count are what it wants realized next. @@ -713,6 +814,8 @@ class TableImpl final : public ContainerItemWidget { [[nodiscard]] static bool marked(ItemBase const& row); /// Whether a row is a group heading. [[nodiscard]] static bool heading(ItemBase const& row); + /// Whether a row is never current, selected, counted or activated: a heading or a summary row. + [[nodiscard]] static bool passive(ItemBase const& row); protected: void adopted(ItemBase& child) override; @@ -736,17 +839,48 @@ class TableImpl final : public ContainerItemWidget { ui::SelectionMode _mode = ui::SelectionMode::None; std::vector _requested; std::function, ui::SelectionChange)> _onSelectionChange; + // Ctrl+A's and the header box's handler in place of selecting the rows held; empty for none. + std::function _onSelectAll; // Where a range starts: the row last clicked or toggled. std::optional _anchor; std::function _onActivate; - std::function _onSort; + std::function _onSort; + std::function(std::optional)> _menu; + std::function, std::vector)> _onMenu; + std::function(ui::Key const&, std::size_t)> _cellMenu; + std::function const&)> _cellChosen; + /// The cell whose menu is open; none before any. + std::optional> _cellMenuAt; + /// The chords that ask for the focused cell's entries. + std::vector _cellMenuKeys; + std::function _onColumnMove; + std::function)> _onColumnResize; + std::function _onFilter; + std::function _onGroupFilter; + std::function _onCopy; // Every key the table's data has, realized or dewindowed; set only above a virtualized table's threshold // (mount.hpp never calls setExistingKeys below it). Empty below threshold, where existingSelection() falls // back to realized children alone, which is already exactly every key that exists at that size. std::unordered_set _existingKeys; // The same keys, in row order, for a range or Ctrl+A over rows that are not realized. std::vector _existingOrder; + // The keys of the summary rows, which no selection, count or Ctrl+A takes in. + std::vector _summaryKeys; std::function _onVisibleRangeChanged; + std::function _onRetry; + std::function _onStatusEntry; + // Engaged while the selection is of the view: every row but these keys is marked, until the next setSelection. + std::optional> _viewExcept; + std::function _onHorizontalRange; + std::function _onColumnMeasured; + std::function _onFocusMove; + std::function _onSelectRange; + std::function _onText; + std::function _onCellClick; + std::function _onCellSelect; + std::function _onFocusOut; + /// Each row's open cell editor's item, by row. + QHash> _editors; /// Each row's effective spans, as last told. std::unordered_map> _spans; /// Whether any row has been told it spans or is covered, so a table that never spans does no work. @@ -779,6 +913,19 @@ class TableRowImpl final : public ContainerItemWidget { /// Its key, once the table was told it. [[nodiscard]] std::optional const& key() const noexcept { return _key; } void setKey(ui::Key key); + /// Writes the load state of the row's cell in @p column to the row's `cellLoads`, which holds the columns not + /// loaded. + void setLoad(std::size_t column, ui::CellLoad load); + /// Writes the accent of the row's cell in @p column to the row's `cellAccents`, which holds the columns with one: + /// `{tone, tooltip, invalid}`, the tone -1 for none. + void setAccent(std::size_t column, ui::CellAccent const& accent); + /// Writes the marks of the row's cell in @p column to the row's `cellMarks`, which holds the columns with some: + /// `{readOnly, modified, error, stale, muted}`. + void setMarks(std::size_t column, ui::CellMarks const& marks); + /// Its view row, once the table was told it. + [[nodiscard]] std::optional viewRow() const noexcept { return _viewRow; } + /// Remembers the view row the table told it. + void setViewRow(std::size_t viewRow) noexcept { _viewRow = viewRow; } protected: /// The table places a row's cells in its columns. @@ -787,6 +934,13 @@ class TableRowImpl final : public ContainerItemWidget { private: std::optional _key; + /// The columns not loaded, by column as text: `1` unloaded, `2` failed. + QVariantMap _loads; + /// The columns with an accent, by column as text. + QVariantMap _accents; + /// The columns with marks, by column as text. + QVariantMap _marks; + std::optional _viewRow; }; } // namespace morph::qt_quick::detail diff --git a/src/qt_quick/leaves.cpp b/src/qt_quick/leaves.cpp index b66e45ee9..cbc0fbdb1 100644 --- a/src/qt_quick/leaves.cpp +++ b/src/qt_quick/leaves.cpp @@ -28,6 +28,15 @@ std::function actionHandler(ui::Action action) { }; } +// A list entry's content: a slot that never scrolls, since the entry grows with what it holds. +class EntryContent final : public ContainerItemWidget { +public: + using ContainerItemWidget::ContainerItemWidget; + void setScrollable(bool scrollable) override { static_cast(scrollable); } +}; + +} // namespace + // NOLINTBEGIN(misc-no-recursion): a menu is a tree of entries. QVariantList menuEntries(std::vector const& entries) { QVariantList list; @@ -54,15 +63,6 @@ QVariantList menuEntries(std::vector const& entries) { } // NOLINTEND(misc-no-recursion) -// A list entry's content: a slot that never scrolls, since the entry grows with what it holds. -class EntryContent final : public ContainerItemWidget { -public: - using ContainerItemWidget::ContainerItemWidget; - void setScrollable(bool scrollable) override { static_cast(scrollable); } -}; - -} // namespace - // ── Button ──────────────────────────────────────────────────────────────── ButtonImpl::ButtonImpl(Context& context, ui::ContainerWidget* parent) diff --git a/src/qt_quick/qml/MorphTable.qml b/src/qt_quick/qml/MorphTable.qml index 457e67b2a..a457c1e69 100644 --- a/src/qt_quick/qml/MorphTable.qml +++ b/src/qt_quick/qml/MorphTable.qml @@ -7,6 +7,36 @@ import QtQuick.Layouts // Rows of cells under column headers. Each column's width comes from its sizing: fixed units, the widest of its // header and its shown cells for content, or for stretch its content plus a share of what is left; every row places // its cells at those widths. +// +// A table over a `TableSource` (`sourceRows`) draws what the mount realizes. Each row sits at the top of its view row +// (`viewRow`), whatever its place among the children, and each cell in the column C++ gave it (`measuredIndex`); a +// cell with none is pooled and hidden. Once the mount lays the columns out (`arranged`), the header and the rows show +// the window's columns only (`windowColumns`, pixels), the first `pinnedShown` of them held at the leading edge over +// the rest, which scroll; the table reports its sideways scroll and viewport, and a cell's width to grow its column. +// A row is as tall as the tallest of its placed cells, and its height only grows while it is realized; a row that +// leaves forgets it, and a row not realized counts as the mean of those measured. A table whose columns all keep one +// line has one row height and measures no cell. When rows above the first visible one change height, the view moves +// by as much, so the rows in view stay where they were. Keyboard focus stays on the table, never on a row, which a +// recycled slot would take away: the keys go to the mount (`focusMove`), and the focused cell (`focusedRowIndex`, +// `focusedColumnIndex`) is kept in view and drawn as the current row. +// +// The status line (`statusShown`) is one line under the rows: the counts, the state and the message, and "Retry" +// while the state offers it. It takes no space while it is not shown. +// +// A header is a Tab stop while it can sort, move or open a menu. A click, Enter or Space on a sortable header asks to +// sort (`sort`, with `shift` while Shift is held); a right click, Shift+F10 or the menu key asks for its menu +// (`menu`, with its column), and the `⋯` at the header's trailing end (`Table options`) for the table's (`-1`); C++ +// answers with `showMenu`, which shows the entries in a button-style MorphMenu's popup under the header, and a choice +// is reported as `menuChoose`. Dragging a header onto another, or Ctrl+Shift+Left and Ctrl+Shift+Right on it, report +// a move to a visible place (`columnMove`); dragging a header's trailing edge reports its width in pixels and a double +// click on the edge none (`columnResize`). A filterable header ends in a filter button (`filter`), filled while +// `filteredColumns` names it, and then named "{label}, filtered". Column groups draw a line above the headers, each +// group's label over the visible places it names with its own filter button (`groupFilter`). Ctrl+C on the table asks +// to copy (`copy`). With a cell menu (`hasCellMenu`), a right click or a long press on a cell asks its row for the +// cell's menu (the row's `cellMenu`, with the column), as Shift+F10 or the menu key does on the focused cell over a +// source; C++ answers with `showCellMenu`, which shows the entries in the same popup under the cell, and the choice +// is reported as `menuChoose` with the column -2. Over a source, a key the table leaves is offered to the focused +// cell's entries (`cellKey`). MorphWidget { id: root @@ -14,13 +44,271 @@ MorphWidget { // `Align`: 0 stretch, 1 start, 2 center, 3 end. property var columns: [] property bool showHeader: true - // The column whose header marks the sort, -1 for none, and whether it is descending; C++ writes both. - property int sortColumn: -1 - property bool sortDescending: false - // What follows a sortable header's label while it sorts, and the room every sortable header keeps for it, so the - // columns do not move when the sort does. - readonly property string ascendingMark: " ▲" - readonly property string descendingMark: " ▼" + // Each sorted header's mark and accessible description, by column as text: the sort chain, which C++ writes. + property var sortMarks: ({}) + property var sortDescriptions: ({}) + // The room every sortable header keeps for a one-key mark, so the columns do not move when such a sort does. + readonly property string ascendingMark: " \u25B2" + // Whether the headers and the table have menus, columns can be moved and resized, and the table copies. + property bool hasMenu: false + // Whether the cells have a menu. + property bool hasCellMenu: false + property bool movable: false + property bool resizable: false + property bool copies: false + // The visible columns in layout order; empty for every column in its own order. + property var visibleColumns: [] + // The columns that have a filter, by column as text. + property var filteredColumns: ({}) + // The column groups: [{label, first, count, filtered}], `first` a visible place. + property var columnGroups: [] + // The column the open menu belongs to, -1 for the table's menu. + property int menuColumn: -1 + // The header bands, outermost level first: [{level, text, first, count, pinned}], `first` a visible place. + property var bands: [] + readonly property int bandLevels: { + let levels = 0 + for (let at = 0; at < root.bands.length; ++at) + levels = Math.max(levels, root.bands[at].level + 1) + return levels + } + // One line of the header above the column headers: a band level's, or the group line's. + readonly property real headerLineHeight: headerMetrics.height + 2 * Theme.tableCellPaddingY + readonly property real bandsHeight: root.showHeader ? root.bandLevels * root.headerLineHeight : 0 + // Everything above the column headers: the band levels, then the group line. + readonly property real groupRowHeight: root.bandsHeight + (root.columnGroups.length > 0 ? root.headerLineHeight + : 0) + // The width kept at the header's trailing end for the `⋯`, which no column's header or filter button lies under. + readonly property real menuReserve: root.hasMenu && root.showHeader ? Theme.targetHeight : 0 + + // Where a column's header is drawn in the header area: its left edge and width, from the widths and the window + // the header is laid out by (so a binding that reads it follows order, hidden and pinned columns, widths and the + // sideways scroll); null while the column's header is not drawn. + function columnBox(column: int): var { + if (root.arranged) { + for (let at = 0; at < root.windowColumns.length; ++at) { + const entry = root.windowColumns[at] + if (entry.column === column) + return {"x": root.lead + entry.offset + (at < root.pinnedShown ? root.scrollX : 0), + "width": entry.width} + } + return null + } + if (root.widths[column] === undefined) + return null + let x = root.lead + for (let before = 0; before < column; ++before) + x += root.widths[before] ?? 0 + return {"x": x, "width": root.widths[column]} + } + + // A column's visible place: its index among `visibleColumns`, or the column itself when every column shows. + function placeOf(column: int): int { + return root.visibleColumns.length > 0 ? root.visibleColumns.indexOf(column) : column + } + + // The column at a visible place: the inverse of `placeOf`. + function columnAtPlace(place: int): int { + return root.visibleColumns.length > 0 ? (root.visibleColumns[place] ?? -1) : place + } + + // ── Cells selected (`selectsCells`) ── + + // Whether the table selects cells, not rows: C++ sets it with its handler, and `cellRect` is the rectangle it + // draws, `[firstRow, rowCount, firstPosition, positionCount]` in view rows and visible places, empty for none. + property bool selectsCells: false + property var cellRect: [] + + // Reports a rectangle by its corners' view rows and visible places. + function selectCells(anchorRow: int, anchorPosition: int, focusRow: int, focusPosition: int) { + if (anchorRow < 0 || anchorPosition < 0 || focusRow < 0 || focusPosition < 0) + return + root.fire("cellSelect", {"anchorRow": anchorRow, "anchorPosition": anchorPosition, + "focusRow": focusRow, "focusPosition": focusPosition}) + } + + // A Shift-click on a cell: from the focused cell to the one clicked. + function selectCellsTo(viewRow: int, column: int) { + if (root.focusedRowIndex >= 0 && root.focusedColumnIndex >= 0) + root.selectCells(root.focusedRowIndex, root.placeOf(root.focusedColumnIndex), viewRow, root.placeOf(column)) + } + + // A click on a row's leading edge: every visible cell of the row. + function selectRowCells(viewRow: int) { + const places = root.visibleColumns.length > 0 ? root.visibleColumns.length : root.columns.length + if (places > 0) + root.selectCells(viewRow, 0, viewRow, places - 1) + } + + // A Ctrl-click on a column's header: every row's cell of the column. + function selectColumnCells(column: int) { + if (root.totalRows > 0) + root.selectCells(0, root.placeOf(column), root.totalRows - 1, root.placeOf(column)) + } + + // The column whose cells lie under `x`, in the rows' coordinates; -1 for none. + function columnAtX(x: real): int { + for (let column = 0; column < root.columns.length; ++column) { + const box = root.columnBox(column) + if (box !== null && root.placeOf(column) >= 0 && x >= box.x && x < box.x + box.width) + return column + } + return -1 + } + + // The visible place under `x`, a point before the first column taking the first and one past the last the last: + // a drag that ends beside the cells selects up to the edge. + function placeAtX(x: real): int { + const column = root.columnAtX(x) + if (column >= 0) + return root.placeOf(column) + const places = root.visibleColumns.length > 0 ? root.visibleColumns.length : root.columns.length + if (places === 0) + return -1 + const first = root.columnBox(root.columnAtPlace(0)) + return first !== null && x < first.x ? 0 : places - 1 + } + + // The rectangle `cellRect` names, in the rows' coordinates; null while it is empty or none of its columns is + // drawn. + function cellRectBox(): var { + if (root.cellRect.length !== 4) + return null + let left = Infinity + let right = -Infinity + for (let place = root.cellRect[2]; place < root.cellRect[2] + root.cellRect[3]; ++place) { + const box = root.columnBox(root.columnAtPlace(place)) + if (box !== null) { + left = Math.min(left, box.x) + right = Math.max(right, box.x + box.width) + } + } + if (left > right) + return null + const top = root.rowTop(root.cellRect[0]) + return {"x": left, "y": top, "width": right - left, + "height": root.rowTop(root.cellRect[0] + root.cellRect[1]) - top} + } + + function sortMarkOf(column: int): string { + return root.sortMarks[String(column)] ?? "" + } + + function headerName(column: int, label: string): string { + const filterable = root.columns[column]?.filterable === true + return filterable && root.filteredColumns[String(column)] === true ? label + ", filtered" : label + } + + // The keys of a focused header: Shift with Enter or Space extends the sort, Ctrl+Shift with Left or Right moves + // the column a place, Shift+F10 or the menu key opens its menu. + function headerKey(event: var, column: int, sortable: bool): bool { + const mods = event.modifiers & (Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier) + if (root.copies && event.key === Qt.Key_C && mods === Qt.ControlModifier) { + root.fire("copy", undefined) + return true + } + const activate = event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space + // Ctrl, as on a click, has no meaning on a header and sorts as a plain key. + if (sortable && activate + && (mods === Qt.NoModifier || mods === Qt.ShiftModifier || mods === Qt.ControlModifier)) { + root.fire("sort", {"column": column, "shift": mods === Qt.ShiftModifier}) + return true + } + if (root.movable && mods === (Qt.ControlModifier | Qt.ShiftModifier) + && (event.key === Qt.Key_Left || event.key === Qt.Key_Right)) { + const place = root.placeOf(column) + const count = root.visibleColumns.length > 0 ? root.visibleColumns.length : root.columns.length + const target = event.key === Qt.Key_Left ? place - 1 : place + 1 + if (place >= 0 && target >= 0 && target < count) + root.fire("columnMove", {"column": column, "position": target}) + return true + } + if (root.hasMenu && ((event.key === Qt.Key_F10 && mods === Qt.ShiftModifier) || event.key === Qt.Key_Menu)) { + root.fire("menu", column) + return true + } + return false + } + + // The header item of a column, or of the table's menu for -1; null when it is not drawn. + function headerItem(column: int): Item { + if (column < 0) + return tableMenuButton + const name = "header" + column + const pending = [headerArea] + while (pending.length > 0) { + const item = pending.pop() + if (item.objectName === name) + return item + for (const child of item.children) + pending.push(child) + } + return null + } + + // Shows a menu's entries, as C++ read them for `column` (-1 for the table's), under its header or the `⋯`. + function showMenu(column: var, entries: var) { + const anchor = root.headerItem(Number(column)) + if (!anchor) + return + root.menuColumn = Number(column) + configMenu.anchorItem = anchor + configMenu.entries = entries + configMenu.path = [] + configMenu.current = configMenu.nextEntry(-1, 1) + configMenu.y = anchor.mapToItem(root, 0, anchor.height).y + if (configMenu.opened) + root.placeMenu() + else + configMenu.open() + } + + // Shows a cell's menu, as C++ read it for the cell `anchor` is; a choice goes back with the column -2. + function showCellMenu(anchor: var, entries: var) { + const at = anchor as Item + if (!at) + return + root.menuColumn = -2 + configMenu.anchorItem = at + configMenu.entries = entries + configMenu.path = [] + configMenu.current = configMenu.nextEntry(-1, 1) + configMenu.y = at.mapToItem(root, 0, at.height).y + if (configMenu.opened) + root.placeMenu() + else + configMenu.open() + } + + // An entry's text as a button-style MorphMenu writes it: a checkable entry's mark (a check, or room for one), an + // icon the theme does not draw as its name, the label, and a marker for a submenu. + function menuEntryText(entry: var): string { + const mark = entry.checked === true ? "✓ " : entry.checked === false ? " " : "" + const more = entry.items && entry.items.length > 0 ? " ›" : "" + const named = entry.icon && Theme.iconSource(entry.icon) === "" ? entry.icon + " " : "" + return mark + named + (entry.label ?? "") + more + } + + function placeMenu() { + if (configMenu.anchorItem) + menuPlacement.place(configMenu, configMenu.anchorItem) + } + + // The drop of a header dragged to @p x in the header's own coordinates: a move to the place of the header there. + function dropHeader(column: int, sceneX: real) { + for (let other = 0; other < root.columns.length; ++other) { + const item = root.headerItem(other) + if (!item || other === column || !item.visible) + continue + const at = item.mapFromItem(null, sceneX, 0) + if (at.x >= 0 && at.x < item.width) { + const place = root.placeOf(other) + if (place >= 0) + root.fire("columnMove", {"column": column, "position": place}) + return + } + } + } // Whether the user can select several rows; C++ writes it with the selection mode. property bool multiple: false // The row keyboard focus is on, or was on last; null before any. @@ -30,7 +318,9 @@ MorphWidget { // The select-all box's accessible name. property string selectAllLabel: "Select all" // The width the select column takes before the first column: a touch target. - readonly property real lead: root.selectColumn ? Theme.targetHeight : 0 + // The leading strip before the first column: the select column's boxes, or in a table that selects cells the row + // headers, a click on which selects the row's cells. + readonly property real lead: root.selectColumn || root.selectsCells ? Theme.targetHeight : 0 // How many of the shown rows are selected, for the select-all box. readonly property int selectedShown: { let count = 0 @@ -40,10 +330,10 @@ MorphWidget { } return count } - // Set by C++ (TableImpl::setRealizedWindow) only above a virtualized table's threshold; totalRows stays -1 - // (its default, meaning "not virtualizing") otherwise, which is what keeps every binding below referencing - // these three properties a no-op for a table that never crosses its threshold -- body has no spacers, and the - // Flickable's own reporting never fires, since nothing ever asks "what rows exist beyond what's realized." + // Set by C++ (TableImpl::setRealizedWindow) for a table over a source, and for a table over `rows` at or above + // its virtualization threshold: the contiguous range realized and the view's rows. totalRows stays -1 (its + // default, "not virtualizing") otherwise, which keeps every binding below that reads these three a no-op for a + // short table -- body has no spacers, and the Flickable's own reporting never fires. property int realizedFirst: 0 property int realizedCount: 0 property int totalRows: -1 @@ -69,7 +359,160 @@ MorphWidget { property int anchorRow: 0 property real anchorOffset: 0 property bool restoring: false - readonly property Item content: body + // The table's horizontal measure, which C++ gives the mount (`TableImpl::tableMeasure`): a unit, a monospace + // character and a column's padding, in pixels, as `measure` sizes an unwindowed fixed column. + readonly property real measureUnit: Theme.unitWidth + readonly property real measureMonoUnit: Theme.monoAdvance + readonly property real measurePadding: 2 * Theme.tableCellPaddingX + // Whether the rows come from a `TableSource`; C++ sets it before the first row. + property bool sourceRows: false + // Whether C++ selects the whole view itself on "selectAll", in place of a range through the mount. + property bool selectAllHandled: false + // Whether printable text typed on the focused cell goes to C++ as the `text` event, while no editor is open. + property bool takesText: false + // Whether a tap on a cell goes to C++ as its row's `cellClick` event (MorphTableRow). + property bool reportsCellClicks: false + // Whether the focus leaving the table and everything in it goes to C++ as the `focusOut` event. + property bool reportsFocusOut: false + // Whether the window's active focus was in the table, a cell editor in one of its rows included. + property bool focusWithin: false + // Whether @p focused is inside a shown popup that @p item, or an object it holds, owns: a control's `popup` (a + // combo box's list) or a Popup among its data. A popup lives in the window's overlay, not under its control. + // `visible`, not `opened`: a popup takes the focus as it opens, before its enter transition ends and `opened` + // turns true. + function popupHolds(item, focused, depth: int): bool { + if (!item || depth > 12) + return false + const owned = [] + if (item.popup instanceof Popup) + owned.push(item.popup) + if (item instanceof Popup) + owned.push(item) + for (const popup of owned) { + if (!popup.visible || !popup.contentItem) + continue + for (let at = focused; at; at = at.parent) { + if (at === popup.contentItem || at === popup.contentItem.parent) + return true + } + } + const held = item.data ? item.data : (item.contentData ? item.contentData : []) + for (let i = 0; i < held.length; ++i) { + if (root.popupHolds(held[i], focused, depth + 1)) + return true + } + return false + } + // Whether @p focused is inside a popup of a row's open cell editor. + function inEditorPopup(focused): bool { + for (let i = 0; i < rowsPlane.children.length; ++i) { + const row = rowsPlane.children[i] + if (row.editorItem && root.popupHolds(row.editorItem, focused, 0)) + return true + } + return false + } + Connections { + target: root.Window.window + enabled: root.reportsFocusOut + function onActiveFocusItemChanged() { + const focused = root.Window.activeFocusItem + let within = false + for (let at = focused; at; at = at.parent) { + if (at === root) { + within = true + break + } + } + // Focus in an open cell editor's own popup (a dropdown's list, a date picker) stays in the table; any + // other popup or dialog is outside it. + if (!within && focused && root.inEditorPopup(focused)) + within = true + if (root.focusWithin && !within) + root.fire("focusOut", undefined) + root.focusWithin = within + } + } + readonly property Item content: root.sourceRows ? rowsPlane : body + readonly property Item rowsHolder: root.sourceRows ? rowsPlane : body + // The column window, once the mount lays the columns out: [{column, offset, width}] in pixels, the pinned ones + // first; the width of every visible column together; how many of the window are pinned. C++ writes them. + property bool arranged: false + property var windowColumns: [] + property real windowTotalWidth: 0 + // A count of the times the column window changed, its columns or their widths. A row's height is kept against a + // shorter measure only across such a change (`layoutRows`), so a wrapped cell that scrolls out sideways does not + // make its row shorter, while a row measured again in the same window takes what it measures. + property int windowEpoch: 0 + property string windowShape: "" + onWindowColumnsChanged: { + const shape = root.windowColumns.map(entry => entry.column + ":" + Math.round(entry.width)).join(",") + if (shape !== root.windowShape) { + root.windowShape = shape + ++root.windowEpoch + } + } + property int pinnedShown: 0 + // For tests and assistive technology: the window's size, its first scrolled column, and the header cells alive. + readonly property int realizedColumnCount: root.windowColumns.length + readonly property int realizedColumnFirst: root.windowColumns.length > root.pinnedShown + ? root.windowColumns[root.pinnedShown].column : 0 + readonly property int headerCellCount: root.arranged ? windowHeader.count : headerLabels.count + // Each window column's place in `windowColumns`, by column. + readonly property var windowPlaces: { + const places = {} + for (let i = 0; i < root.windowColumns.length; ++i) + places[root.windowColumns[i].column] = i + return places + } + // Where the scrolled columns pass under the pinned ones, from the first column's start. + readonly property real pinnedEdge: { + let edge = 0 + for (let i = 0; i < root.pinnedShown && i < root.windowColumns.length; ++i) + edge = Math.max(edge, root.windowColumns[i].offset + root.windowColumns[i].width) + return edge + } + readonly property real scrollX: hflick.contentX + // The view's width across the columns, the select column left out. + readonly property real columnViewport: Math.max(0, hflick.width - root.lead - root.menuReserve) + // Whether every column keeps one line: the rows then share one height and no cell is measured. + readonly property bool allOneLine: { + for (const column of root.columns) { + if (column.wrap) + return false + } + return true + } + readonly property real oneLineRowHeight: root.estimatedRowHeight + // Each realized row's height by view row, and the mean of them, which a row not realized counts as. + property var rowHeights: ({}) + // By view row: the `windowEpoch` each height was last measured in, and the height it had when the column window + // last changed, under which it does not go while the window stays. + property var rowHeightEpochs: ({}) + property var rowHeightFloors: ({}) + property real meanRowHeight: root.estimatedRowHeight + // Test-only: how many cell heights the rows have measured for their own heights. + property int rowMeasures: 0 + readonly property real sourceContentHeight: { + let height = Math.max(0, root.totalRows) * root.meanRowHeight + for (const key in root.rowHeights) + height += root.rowHeights[key] - root.meanRowHeight + return Math.max(0, height) + } + // The focused cell, which C++ writes; -1 before any. + property int focusedRowIndex: -1 + property int focusedColumnIndex: -1 + // The counts assistive technology is told: the rows, -1 while they are a lower bound or not known, and the visible + // columns. + property int accessibleRowCount: -1 + property int accessibleColumnCount: 0 + // The status line. + property string statusText: "" + property bool statusShown: false + property bool retryShown: false + // The status line's choices, each `{id, label}`: a button each after the text. + property var statusEntries: [] + readonly property real statusHeight: root.statusShown ? statusLine.implicitHeight : 0 // The sideways scroll's bar, made from the `scrollBar` part (`MorphScrollBar` or its restyle), which C++ passes at // creation; null without one. property Component bar: null @@ -93,7 +536,8 @@ MorphWidget { property var leastCache: [] // Test-only: how many rows a full column rescan has visited, summed across every rescan. Not a public API. property int rowScans: 0 - readonly property var widths: root.columnWidths(width - root.lead) + // Once the mount lays the columns out, no width is worked out here: nothing reads every column per frame. + readonly property var widths: root.arranged ? [] : root.columnWidths(width - root.lead - root.menuReserve) // A column's declared width describes its content, with `table.cellPaddingX` added on both sides, so the padding // never takes room from the content: a fixed column is its units plus the padding (a unit is a body character, @@ -115,16 +559,29 @@ MorphWidget { // wider in sum than the table by a pixel or more scroll sideways (`hflick`). // // Each column's widths, read from the caches and the headers, never from the table's own width. + // The width a column's header asks for, padding included, and never under 8 units. A sortable header keeps room for + // a one-key mark, and for the mark it draws now: a chain of two or more keys adds the key's place after its arrow. + // The header draws its unit after its label: the column is never narrower than both, its sort mark and its filter + // button. + function headerWidthOf(index: int): real { + const column = root.columns[index] + const mark = column.sortable ? Math.max(headerMetrics.advanceWidth(root.ascendingMark), + headerMetrics.advanceWidth(root.sortMarkOf(index))) : 0 + const button = column.filterable === true ? Theme.targetHeight : 0 + return Math.max(headerMetrics.advanceWidth(root.headerTextOf(column)) + mark + button + + 2 * Theme.tableCellPaddingX, 8 * Theme.unitWidth) + } + function measure(): var { // `advanceWidth` is a plain call, so the font is read here for the widths to follow a header font that changes. void headerMetrics.font + // Read here too, so the widths follow a chain whose marks grow with its keys' places. + void root.sortMarks const pad = 2 * Theme.tableCellPaddingX const out = [] for (let i = 0; i < root.columns.length; ++i) { const column = root.columns[i] - const mark = column.sortable ? headerMetrics.advanceWidth(root.ascendingMark) : 0 - const header = Math.max(headerMetrics.advanceWidth(column.label) + mark + pad, - 8 * Theme.unitWidth) + const header = root.headerWidthOf(i) let natural = header let least = header let floor = header @@ -226,6 +683,8 @@ MorphWidget { // The columns' summed width: the rows' and the header's width, and what `hflick` scrolls across. readonly property real columnsWidth: { + if (root.arranged) + return root.lead + root.windowTotalWidth let sum = root.lead for (const w of root.widths) sum += w @@ -267,6 +726,8 @@ MorphWidget { // a column whose widest cell really is 0 (an empty table) -- harmless here, since seeding an already-correct // zero with the same scan just repeats the (cheap, currently-zero-row) work rather than skipping it wrongly. function seedMissingColumns() { + if (root.sourceRows) + return for (let i = 0; i < root.columns.length; ++i) { if (root.columns[i].kind !== 1 && i >= root.columnCache.length) root.rescanColumn(i) @@ -279,9 +740,9 @@ MorphWidget { function widestCell(index: int): var { let natural = 0 let least = 0 - for (let r = 0; r < body.children.length; ++r) { + for (let r = 0; r < root.rowsHolder.children.length; ++r) { ++root.rowScans - const row = body.children[r] + const row = root.rowsHolder.children[r] // A heading's one cell spans every column, so it widens none. if (!row.visible || row.heading || !row.content || index >= row.content.children.length) continue @@ -302,7 +763,7 @@ MorphWidget { // rule from invalidateAllColumns' own comment is enforced here, not duplicated at each call site. function rescanColumn(index: int) { const column = root.columns[index] - if (!column || column.kind === 1) + if (!column || column.kind === 1 || root.sourceRows) return const scanned = root.widestCell(index) if (column.kind === 2) { @@ -344,6 +805,21 @@ MorphWidget { const column = root.columns[index] if (!column || column.kind === 1 || !cell || !cell.visible || cell.parent?.parent?.heading) return + // Over a source the mount holds the widths: it learns what a cell asks for, and widens a content column to it + // and fits the stretch columns to the table. It keeps the largest it was told, so a width already told is not + // told again. + if (root.sourceRows) { + const pad = 2 * Theme.tableCellPaddingX + const natural = Math.ceil(root.naturalOf(cell) + pad) + const least = Math.ceil(root.leastOf(cell, root.naturalOf(cell)) + pad) + const told = root.toldWidths[index] + if (!told || natural > told.natural || least > told.least) { + root.toldWidths[index] = {"natural": Math.max(natural, told ? told.natural : 0), + "least": Math.max(least, told ? told.least : 0)} + root.fire("measured", {"column": index, "natural": natural, "least": least}) + } + return + } const natural = root.naturalOf(cell) const stretch = column.kind === 2 const least = stretch ? root.leastOf(cell, natural) : 0 @@ -382,6 +858,8 @@ MorphWidget { // The accepted cost of the monotonic rule is a column that stays wider than currently necessary after the row // that justified it has scrolled away, preferred over that jitter. function invalidateAllColumns() { + if (root.sourceRows) + return for (let i = 0; i < root.columns.length; ++i) { if (root.columns[i].kind !== 1) root.rescanColumn(i) @@ -391,13 +869,42 @@ MorphWidget { onColumnsChanged: { root.columnCache = [] root.leastCache = [] + root.toldWidths = [] root.seedMissingColumns() + root.scheduleHeaders() + } + + // What the mount was told of each column's cells, by column: a plain list, written outside any binding. + property var toldWidths: [] + + // Over a source the mount fits the columns to the table, so it is told each header's width, and again when a font + // or a sort mark changes it. + readonly property var headerWidths: { + void headerMetrics.font + void root.sortMarks + const out = [] + for (let i = 0; i < root.columns.length; ++i) + out.push(Math.ceil(root.headerWidthOf(i))) + return out + } + onHeaderWidthsChanged: root.scheduleHeaders() + function scheduleHeaders() { + if (root.sourceRows) + Qt.callLater(root.reportHeaders) + } + function reportHeaders() { + if (!root.sourceRows) + return + for (let i = 0; i < root.headerWidths.length; ++i) { + if (root.columns[i].kind !== 1) + root.fire("measured", {"column": i, "header": root.headerWidths[i]}) + } } // A Tab stop: the focus goes on to the current row, or the first one. activeFocusOnTab: true onActiveFocusChanged: { - if (activeFocus) + if (activeFocus && !root.sourceRows) root.focusRow(root.shownRows().includes(root.currentRow) ? root.currentRow : root.shownRows()[0]) } @@ -416,8 +923,8 @@ MorphWidget { function recomputeSpans() { root.spansQueued = false const rows = [] - for (let i = 0; i < body.children.length; ++i) { - const row = body.children[i] + for (let i = 0; i < root.rowsHolder.children.length; ++i) { + const row = root.rowsHolder.children[i] if (row.visible && row.table === root) rows.push(row) } @@ -450,12 +957,12 @@ MorphWidget { } } - // The data rows the user can see, in order: a heading row is never current, selected or counted. + // The data rows the user can see, in order: a heading or summary row is never current, selected or counted. function shownRows(): var { const shown = [] - for (let i = 0; i < body.children.length; ++i) { - const row = body.children[i] - if (row.visible && row.table === root && !row.heading) + for (let i = 0; i < root.rowsHolder.children.length; ++i) { + const row = root.rowsHolder.children[i] + if (row.visible && row.table === root && !row.heading && !row.summary) shown.push(row) } return shown @@ -476,6 +983,13 @@ MorphWidget { const focused = root.Window.activeFocusItem if (focused !== root && (focused as MorphTableRow)?.table !== root) return false + const held = event.modifiers & (Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier) + if (root.copies && event.key === Qt.Key_C && held === Qt.ControlModifier) { + root.fire("copy", undefined) + return true + } + if (root.sourceRows) + return root.sourceKey(event) const rows = root.shownRows() const at = rows.indexOf(root.currentRow) const mods = event.modifiers & (Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier) @@ -523,7 +1037,9 @@ MorphWidget { // from the caches and the headers. `implicitWidth` follows `width` through the header, so a table that is a cell // of another table reports this instead. widthFreeNatural: { - let sum = root.lead + if (root.arranged) + return Math.ceil(root.lead + root.windowTotalWidth + root.menuReserve) + let sum = root.lead + root.menuReserve for (const m of root.measure()) sum += m.natural // In whole pixels, so a sum that wobbles in its last digits does not read as a change. @@ -534,11 +1050,14 @@ MorphWidget { // now -- otherwise the table's own size, and so its container's scrollbar, would shrink every time a row // dewindows, which is the "table visually collapses" symptom this design exists to avoid, not just the // underlying widget cost. - implicitHeight: (root.showHeader ? header.implicitHeight : 0) + body.implicitHeight + - (root.virtualized ? root.heightBefore(root.realizedFirst) + - root.heightBefore(root.totalRows) - - root.heightBefore(root.realizedFirst + root.realizedCount) : 0) + - root.barHeight + implicitHeight: headerArea.height + root.barHeight + root.statusHeight + + (root.sourceRows ? root.sourceContentHeight + : body.implicitHeight + + (root.virtualized ? root.heightBefore(root.realizedFirst) + + root.heightBefore(root.totalRows) - + root.heightBefore(root.realizedFirst + + root.realizedCount) + : 0)) // A table whose columns are wider than it scrolls sideways, and says so once. needWidth: root.columnsWidth haveWidth: root.width @@ -556,7 +1075,10 @@ MorphWidget { id: hflick objectName: "hflick" anchors.fill: parent - contentWidth: Math.max(root.columnsWidth, width) + anchors.bottomMargin: root.statusHeight + onContentXChanged: root.reportColumns() + onWidthChanged: root.reportColumns() + contentWidth: Math.max(root.columnsWidth + root.menuReserve, width) contentHeight: height flickableDirection: Flickable.HorizontalFlick // Columns wider than the table by less than a pixel are rounding, not content to scroll to. @@ -570,7 +1092,9 @@ MorphWidget { visible: root.showHeader width: hflick.contentWidth implicitWidth: header.implicitWidth - height: root.showHeader ? header.implicitHeight : 0 + height: !root.showHeader ? 0 : root.groupRowHeight + (root.arranged ? headerMetrics.height + + 2 * Theme.tableCellPaddingY + : header.implicitHeight) Loader { id: headerBackgroundLoader @@ -583,19 +1107,137 @@ MorphWidget { value: root.scheme } + // The band lines: each run over the columns at the visible places it names, at its level. The mount cut the + // runs, so a band never covers a column that is not its own. + Repeater { + model: root.showHeader ? root.bands : [] + + Item { + id: bandCell + required property int index + required property var modelData + objectName: "band" + index + readonly property var span: { + let left = -1 + let right = -1 + for (let column = 0; column < root.columns.length; ++column) { + const place = root.placeOf(column) + const box = root.columnBox(column) + if (!box || place < bandCell.modelData.first + || place >= bandCell.modelData.first + bandCell.modelData.count) + continue + left = left < 0 ? box.x : Math.min(left, box.x) + right = Math.max(right, box.x + box.width) + } + return {"left": left, "right": right} + } + visible: span.left >= 0 + x: span.left + y: bandCell.modelData.level * root.headerLineHeight + width: Math.max(0, span.right - span.left) + height: root.headerLineHeight + Accessible.role: Accessible.ColumnHeader + Accessible.name: bandCell.modelData.text + + Label { + anchors.fill: parent + leftPadding: Theme.tableCellPaddingX + verticalAlignment: Text.AlignVCenter + textFormat: Text.PlainText + font: Theme.tableHeaderFont + color: root.scheme.muted + text: bandCell.modelData.text + elide: Text.ElideRight + } + } + } + + // The group line: each group's label over the columns at the visible places it names, ending in its + // filter button. + Repeater { + model: root.showHeader ? root.columnGroups : [] + + Item { + id: groupCell + required property int index + required property var modelData + readonly property var span: { + let left = -1 + let right = -1 + for (let column = 0; column < root.columns.length; ++column) { + const place = root.placeOf(column) + const box = root.columnBox(column) + if (!box || place < groupCell.modelData.first + || place >= groupCell.modelData.first + groupCell.modelData.count) + continue + left = left < 0 ? box.x : Math.min(left, box.x) + right = Math.max(right, box.x + box.width) + } + return {"left": left, "right": right} + } + visible: span.left >= 0 + x: span.left + y: root.bandsHeight + width: Math.max(0, span.right - span.left) + height: root.headerLineHeight + + Label { + anchors.left: parent.left + anchors.right: groupFilter.left + anchors.verticalCenter: parent.verticalCenter + leftPadding: Theme.tableCellPaddingX + textFormat: Text.PlainText + font: Theme.tableHeaderFont + color: root.scheme.muted + text: groupCell.modelData.label + elide: Text.ElideRight + } + ToolButton { + id: groupFilter + objectName: "groupFilter" + groupCell.index + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + text: groupCell.modelData.filtered === true ? "\u25BE" : "\u25BF" + Accessible.name: groupCell.modelData.label + (groupCell.modelData.filtered === true + ? ", filtered" : "") + onClicked: root.fire("groupFilter", groupCell.index) + } + } + } + + // The table's menu: the `⋯` at the header's trailing end. + ToolButton { + id: tableMenuButton + objectName: "tableMenuButton" + visible: root.hasMenu && root.showHeader + x: hflick.contentX + hflick.width - width + y: root.groupRowHeight + z: 2 + width: root.menuReserve + height: headerArea.height - root.groupRowHeight + text: "\u22EF" + Accessible.name: "Table options" + onClicked: root.fire("menu", -1) + } + Row { id: header + y: root.groupRowHeight + // Once the columns are windowed, the header cells are placed in the header area, not in this row, which + // would otherwise have nothing to size to and leave the select-all box half above the table. + height: root.arranged ? headerMetrics.height + 2 * Theme.tableCellPaddingY : implicitHeight // The select-all box: checked while every shown row is selected, partly while some are. It shows the // selection and never changes its own state, so a selection the document refuses leaves it as it was. Item { - visible: root.selectColumn + visible: root.selectColumn || root.selectsCells width: root.lead height: parent.height CheckBox { id: selectAllBox objectName: "selectAll" + visible: root.selectColumn anchors.centerIn: parent padding: 0 indicator: MorphCheckIndicator { @@ -617,13 +1259,24 @@ MorphWidget { nextCheckState: function() { return checkState } - onClicked: root.fire("selectAll", undefined) + // Over a source, every row of the view through the mount, as Ctrl+A. + onClicked: { + if (root.sourceRows && !root.selectAllHandled) { + if (root.totalRows > 0) { + root.anchorRowIndex = 0 + root.selectRangeTo(root.totalRows - 1, true) + } + } else { + root.fire("selectAll", undefined) + } + } Accessible.name: root.selectAllLabel } } Repeater { - model: root.columns + id: headerLabels + model: root.arranged ? [] : root.columns // A sortable column's header is a Tab stop, and a click, Enter or Space on it asks to sort by // the column; the table shows the sort it is given, never one of its own. @@ -634,31 +1287,72 @@ MorphWidget { font: Theme.tableHeaderFont required property int index required property var modelData - readonly property bool sorted: root.sortColumn === index width: root.widths[index] !== undefined ? root.widths[index] : 0 - text: modelData.label + (sorted ? (root.sortDescending ? root.descendingMark - : root.ascendingMark) : "") - activeFocusOnTab: modelData.sortable === true + text: root.headerTextOf(modelData) + root.sortMarkOf(index) + activeFocusOnTab: modelData.sortable === true || root.hasMenu || root.movable Accessible.role: Accessible.ColumnHeader - Accessible.name: modelData.label - Accessible.description: !sorted ? "" : root.sortDescending ? "Sorted descending" - : "Sorted ascending" + Accessible.name: root.headerName(index, modelData.accessibleName ?? modelData.label) + Accessible.description: root.sortDescriptions[String(index)] ?? "" Keys.onPressed: event => { - if (modelData.sortable === true && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter - || event.key === Qt.Key_Space)) { - root.fire("sort", index) + if (root.headerKey(event, headerLabel.index, headerLabel.modelData.sortable === true)) event.accepted = true - } } + // The modifiers come from the handler's point, which carries them; a tap on the + // trailing edge resizes and does not sort. TapHandler { + id: headerLabelSort enabled: headerLabel.modelData.sortable === true - onTapped: root.fire("sort", headerLabel.index) + onTapped: { + if (headerEdge.visible && headerLabelSort.point.position.x >= headerEdge.x) + return + // In a table that selects cells a Ctrl-click selects the column's cells and sorts + // nothing; a plain click and a Shift-click sort. + if (root.selectsCells && (headerLabelSort.point.modifiers & Qt.ControlModifier) !== 0) + return + root.fire("sort", {"column": headerLabel.index, + "shift": (headerLabelSort.point.modifiers & Qt.ShiftModifier) !== 0}) + } + } + TapHandler { + acceptedButtons: Qt.RightButton + enabled: root.hasMenu + onTapped: root.fire("menu", headerLabel.index) + } + // In a table that selects cells, a Ctrl-click selects the column's cells. + TapHandler { + enabled: root.selectsCells + acceptedModifiers: Qt.ControlModifier + onTapped: root.selectColumnCells(headerLabel.index) + } + DragHandler { + id: headerMove + enabled: root.movable + yAxis.enabled: false + target: null + onActiveChanged: { + if (!active) + root.dropHeader(headerLabel.index, centroid.scenePosition.x) + } + } + MorphTableHeaderEdge { + id: headerEdge + column: headerLabel.index + table: root + } + ToolButton { + objectName: "filter" + headerLabel.index + visible: headerLabel.modelData.filterable === true + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + text: root.filteredColumns[String(headerLabel.index)] === true ? "\u25BE" : "\u25BF" + Accessible.name: "Filter " + headerLabel.modelData.label + onClicked: root.fire("filter", headerLabel.index) } color: root.scheme.muted topPadding: Theme.tableCellPaddingY bottomPadding: Theme.tableCellPaddingY leftPadding: Theme.tableCellPaddingX - rightPadding: Theme.tableCellPaddingX + rightPadding: Theme.tableCellPaddingX + (modelData.filterable === true ? Theme.targetHeight : 0) // Over its cells: a number column's header sits over its digits. horizontalAlignment: modelData.align === 3 ? Text.AlignRight : modelData.align === 2 ? Text.AlignHCenter @@ -667,6 +1361,102 @@ MorphWidget { } } } + + // The header cells of the column window, each at its column's offset; the pinned ones held at the leading + // edge, over the rest. + Repeater { + id: windowHeader + model: root.arranged ? root.windowColumns : [] + + Label { + id: windowLabel + required property int index + required property var modelData + readonly property var column: root.columns[modelData.column] ?? ({"label": "", "align": 1, + "sortable": false}) + readonly property bool pinned: index < root.pinnedShown + objectName: "header" + modelData.column + x: root.lead + modelData.offset + (pinned ? root.scrollX : 0) + y: root.groupRowHeight + z: pinned ? 1 : 0 + width: modelData.width + height: headerArea.height - root.groupRowHeight + textFormat: Text.PlainText + font: Theme.tableHeaderFont + text: root.headerTextOf(column) + root.sortMarkOf(modelData.column) + activeFocusOnTab: column.sortable === true || root.hasMenu || root.movable + Accessible.role: Accessible.ColumnHeader + Accessible.name: root.headerName(modelData.column, column.accessibleName ?? column.label) + Accessible.description: root.sortDescriptions[String(modelData.column)] ?? "" + Keys.onPressed: event => { + if (root.headerKey(event, windowLabel.modelData.column, windowLabel.column.sortable === true)) + event.accepted = true + } + // The modifiers come from the handler's point, which carries them; a tap on the + // trailing edge resizes and does not sort. + TapHandler { + id: windowLabelSort + enabled: windowLabel.column.sortable === true + onTapped: { + if (windowEdge.visible && windowLabelSort.point.position.x >= windowEdge.x) + return + // In a table that selects cells a Ctrl-click selects the column's cells and sorts nothing; + // a plain click and a Shift-click sort. + if (root.selectsCells && (windowLabelSort.point.modifiers & Qt.ControlModifier) !== 0) + return + root.fire("sort", {"column": windowLabel.modelData.column, + "shift": (windowLabelSort.point.modifiers & Qt.ShiftModifier) !== 0}) + } + } + TapHandler { + acceptedButtons: Qt.RightButton + enabled: root.hasMenu + onTapped: root.fire("menu", windowLabel.modelData.column) + } + // In a table that selects cells, a Ctrl-click selects the column's cells. + TapHandler { + enabled: root.selectsCells + acceptedModifiers: Qt.ControlModifier + onTapped: root.selectColumnCells(windowLabel.modelData.column) + } + DragHandler { + enabled: root.movable + yAxis.enabled: false + target: null + onActiveChanged: { + if (!active) + root.dropHeader(windowLabel.modelData.column, centroid.scenePosition.x) + } + } + MorphTableHeaderEdge { + id: windowEdge + column: windowLabel.modelData.column + table: root + } + ToolButton { + objectName: "filter" + windowLabel.modelData.column + visible: windowLabel.column.filterable === true + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + text: root.filteredColumns[String(windowLabel.modelData.column)] === true ? "\u25BE" + : "\u25BF" + Accessible.name: "Filter " + windowLabel.column.label + onClicked: root.fire("filter", windowLabel.modelData.column) + } + color: root.scheme.muted + background: Rectangle { + visible: windowLabel.pinned + color: root.scheme.surface + } + topPadding: Theme.tableCellPaddingY + bottomPadding: Theme.tableCellPaddingY + leftPadding: Theme.tableCellPaddingX + rightPadding: Theme.tableCellPaddingX + horizontalAlignment: column.align === 3 ? Text.AlignRight + : column.align === 2 ? Text.AlignHCenter : Text.AlignLeft + elide: Text.ElideRight + } + } } // Unvirtualized, flick is a transparent pass-through: its height is body's own, nothing clips, and it never @@ -684,11 +1474,12 @@ MorphWidget { interactive: root.virtualized flickableDirection: Flickable.VerticalFlick contentWidth: width - contentHeight: topSpace.height + body.implicitHeight + bottomSpace.height + contentHeight: root.sourceRows ? root.sourceContentHeight + : topSpace.height + body.implicitHeight + bottomSpace.height boundsBehavior: Flickable.StopAtBounds onContentYChanged: { - if (!root.restoring) + if (!root.restoring && !root.sourceRows) root.anchorAt(flick.contentY) root.reportVisibleRange() } @@ -699,7 +1490,7 @@ MorphWidget { Item { id: topSpace width: 1 - height: root.virtualized ? root.heightBefore(root.realizedFirst) : 0 + height: root.virtualized && !root.sourceRows ? root.heightBefore(root.realizedFirst) : 0 } ColumnLayout { @@ -714,11 +1505,112 @@ MorphWidget { id: bottomSpace width: 1 anchors.top: body.bottom - height: root.virtualized + height: root.virtualized && !root.sourceRows ? root.heightBefore(root.totalRows) - root.heightBefore(root.realizedFirst + root.realizedCount) : 0 } + + // The rows of a table over a source, each placed at the top of its view row by `layoutRows`. + Item { + id: rowsPlane + width: flick.width + height: root.sourceContentHeight + + // A mouse drag from one cell to another selects the rectangle they span, reported on release. A touch + // drag is left to the Flickables, so a long grid still scrolls under a finger. + DragHandler { + id: cellDrag + enabled: root.selectsCells + target: null + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + // The mouse drag is the selection's: the scrolling Flickables around the rows do not take it over. + grabPermissions: PointerHandler.CanTakeOverFromItems | PointerHandler.CanTakeOverFromHandlersOfSameType + | PointerHandler.CanTakeOverFromHandlersOfDifferentType + onActiveChanged: { + if (cellDrag.active) + return + const from = cellDrag.centroid.pressPosition + const to = cellDrag.centroid.position + root.selectCells(root.rowAtY(from.y), root.placeAtX(from.x), + root.rowAtY(to.y), root.placeAtX(to.x)) + } + } + } + + // The selected cells: a wash in the selection's colour with its outline, over the rows they span. It + // sits beside the rows plane, not in it, so the plane holds only rows. + Rectangle { + id: cellSelectionBox + objectName: "cellSelection" + readonly property var box: root.cellRectBox() + visible: root.selectsCells && box !== null + z: 2 + x: box !== null ? box.x : 0 + y: box !== null ? box.y : 0 + width: box !== null ? box.width : 0 + height: box !== null ? box.height : 0 + color: Qt.alpha(Theme.themeScheme.selection, 0.5) + border.width: 2 + border.color: Theme.themeScheme.accent + } + } + } + + // The status line, under the rows and outside the sideways scroll. A polite live region: its text is announced + // once it has held for half a second, so a message is read out once and a count when it settles + // (`Accessible.announce`, from Qt 6.8; before it, the text is the line's accessible name and nothing more). + RowLayout { + id: statusLine + objectName: "statusLine" + visible: root.statusShown + x: Theme.tableCellPaddingX + y: root.height - root.statusHeight + width: root.width - 2 * Theme.tableCellPaddingX + spacing: Theme.tableCellPaddingX + + Text { + id: statusLabel + objectName: "statusText" + Layout.fillWidth: true + text: root.statusText + onTextChanged: announceTimer.restart() + Timer { + id: announceTimer + interval: 500 + onTriggered: { + // `announce` is Qt 6.8's; before it the lookup is undefined and nothing is called. + // qmllint disable missing-property + if (root.statusShown && statusLabel.text !== "" && + typeof statusLabel.Accessible.announce === "function") + statusLabel.Accessible.announce(statusLabel.text) + // qmllint enable missing-property + } + } + textFormat: Text.PlainText + elide: Text.ElideRight + font: Theme.smallFont + color: root.scheme.muted + topPadding: Theme.tableCellPaddingY + bottomPadding: Theme.tableCellPaddingY + Accessible.role: Accessible.StaticText + Accessible.name: text + } + Button { + objectName: "retry" + visible: root.retryShown + text: "Retry" + onClicked: root.fire("retry", undefined) + } + // The status line's choices: each reports its id. + Repeater { + model: root.statusEntries + delegate: Button { + required property var modelData + objectName: "statusEntry_" + modelData.id + text: modelData.label + onClicked: root.fire("statusEntry", modelData.id) + } } } @@ -727,7 +1619,7 @@ MorphWidget { // the content above the viewport, and the anchor keeps what the user looks at where it was. Only runs // virtualized: an unvirtualized table never needs an estimate, since every row is always realized. function remeasureRowHeight() { - if (!root.virtualized || body.children.length === 0) + if (!root.virtualized || root.sourceRows || root.rowsHolder.children.length === 0) return let changed = false let at = root.realizedFirst @@ -809,6 +1701,16 @@ MorphWidget { // every other user-driven event (a tap, an activation) already uses -- a scroll is a user-driven request for // different rows to be realized, in the same sense a tap is a request to select a row. function reportVisibleRange() { + if (root.sourceRows) { + // The window bounds what can show: before the first layout a table's height is its whole content's, and + // realizing every row for that one pass would cost far more than the screen can ever display. + const shown = root.Window.height > 0 ? Math.min(flick.height, root.Window.height) : flick.height + const first = root.rowAtY(flick.contentY) + const last = root.rowAtY(flick.contentY + Math.max(0, shown - 1)) + root.fire("scroll", {"first": first, "count": Math.max(0, Math.min(last - first + 1, + root.totalRows - first))}) + return + } if (!root.virtualized || root.estimatedRowHeight <= 0) return root.remeasureRowHeight() @@ -829,6 +1731,297 @@ MorphWidget { onRealizedFirstChanged: root.remeasureRowHeight() onRealizedCountChanged: root.remeasureRowHeight() + // ── A table over a source ── + + // Where view row `viewRow` starts: the mean height for each row before it, corrected by the rows measured. + function rowTop(viewRow: int): real { + let top = viewRow * root.meanRowHeight + for (const key in root.rowHeights) { + if (Number(key) < viewRow) + top += root.rowHeights[key] - root.meanRowHeight + } + return top + } + + // The view row at `y`, from the top of the rows. + function rowAtY(y: real): int { + const mean = Math.max(1, root.meanRowHeight) + const known = Object.keys(root.rowHeights).map(Number).sort((a, b) => a - b) + let row = 0 + let base = 0 + for (const measured of known) { + if (y < base + (measured - row) * mean) + break + base += (measured - row) * mean + row = measured + if (y < base + root.rowHeights[measured]) + return measured + base += root.rowHeights[measured] + row = measured + 1 + } + return Math.max(0, Math.min(Math.max(0, root.totalRows - 1), row + Math.floor((y - base) / mean))) + } + + // Lays the realized rows out once per event loop turn: called as rows get their view rows and change height. + property bool rowsQueued: false + function scheduleRows() { + if (root.sourceRows && !root.rowsQueued) { + root.rowsQueued = true + Qt.callLater(root.layoutRows) + } + } + + // Sets each realized row's height to what it measures now, but no less than the height it had when the column + // window last changed: a wrapped cell that scrolls out sideways does not make its row shorter, and a row measured + // again in the same window, whose cells changed, takes what it measures. A row that left is forgotten. Places + // every row at its view row, and moves the view by what the rows above the first visible one changed, so the rows + // in view stay where they are. + function layoutRows() { + root.rowsQueued = false + const anchor = root.rowAtY(flick.contentY) + const into = flick.contentY - root.rowTop(anchor) + const rows = [] + for (let i = 0; i < rowsPlane.children.length; ++i) { + const row = rowsPlane.children[i] + if (row.table === root && row.viewRow >= 0) + rows.push(row) + } + const heights = {} + const epochs = {} + const floors = {} + let sum = 0 + for (const row of rows) { + const epoch = root.rowHeightEpochs[row.viewRow] + const floor = epoch === undefined ? 0 + : epoch !== row.measuredEpoch ? root.rowHeights[row.viewRow] + : root.rowHeightFloors[row.viewRow] + const height = Math.max(floor, row.measuredHeight) + heights[row.viewRow] = height + epochs[row.viewRow] = row.measuredEpoch + floors[row.viewRow] = floor + sum += height + } + root.rowHeights = heights + root.rowHeightEpochs = epochs + root.rowHeightFloors = floors + root.meanRowHeight = rows.length > 0 ? sum / rows.length : root.estimatedRowHeight + for (const row of rows) { + row.y = root.rowTop(row.viewRow) + row.height = heights[row.viewRow] + } + const target = root.rowTop(anchor) + into + if (Math.abs(target - flick.contentY) >= 0.5) + flick.contentY = target + } + + // Reports the sideways scroll and the viewport, in pixels from the first column's start. + property bool settingOffset: false + // + // A report goes out once per event loop turn: the mount answers a viewport with the columns' widths, and those + // set `contentWidth`, whose clamp of `contentX` reports again from inside the binding that is setting it. + property bool columnsQueued: false + function reportColumns() { + if (!root.sourceRows || root.settingOffset || root.columnsQueued) + return + root.columnsQueued = true + Qt.callLater(root.sendColumns) + } + function sendColumns() { + root.columnsQueued = false + if (root.sourceRows) + root.fire("hscroll", {"scrollX": Math.round(hflick.contentX), "viewport": Math.round(root.columnViewport)}) + } + onSourceRowsChanged: { + Qt.callLater(root.reportColumns) + root.scheduleHeaders() + } + + // Called by C++: the mount moved the view so the columns in view stay where they were; it is not told back. + function setHorizontalOffset(scrollX: int) { + root.settingOffset = true + hflick.contentX = Math.max(0, scrollX) + root.settingOffset = false + } + + // Called by C++: brings a view row into view, as little as it takes. + function scrollToRow(viewRow: var) { + const top = root.rowTop(viewRow) + const bottom = top + (root.rowHeights[viewRow] ?? root.meanRowHeight) + if (top < flick.contentY) + flick.contentY = top + else if (bottom > flick.contentY + flick.height) + flick.contentY = Math.max(0, bottom - flick.height) + } + + // Puts view row `viewRow` at the top of the view. + function scrollRowToTop(viewRow: int) { + flick.contentY = root.rowTop(viewRow) + } + + // Called by C++ when focus moves: the focused row and its column come into view. + function showFocusCell() { + if (root.focusedRowIndex < 0) + return + root.scrollToRow(root.focusedRowIndex) + const place = root.windowPlaces[root.focusedColumnIndex] + if (place === undefined || place < root.pinnedShown) + return + const entry = root.windowColumns[place] + if (entry.offset - hflick.contentX < root.pinnedEdge) + hflick.contentX = Math.max(0, entry.offset - root.pinnedEdge) + else if (entry.offset + entry.width - hflick.contentX > root.columnViewport) + hflick.contentX = entry.offset + entry.width - root.columnViewport + } + + // Where a range over a source starts: the view row last clicked or toggled, or the one Shift with an arrow + // left; -1 for none. + property int anchorRowIndex: -1 + // A range over a source, from the anchor to `viewRow`: the mount resolves it over rows not realized, in + // `multiple` mode only. + function selectRangeTo(viewRow: int, extend: bool) { + if (!root.multiple) + return + if (root.anchorRowIndex < 0) + root.anchorRowIndex = viewRow + root.fire("selectRange", {"anchor": root.anchorRowIndex, "focus": viewRow, "extend": extend}) + } + + // The keys over a source: the moves go to the mount, which resolves them over rows and columns not realized; + // Shift with Up or Down moves and selects from the anchor through the mount, as Ctrl+A selects every row of the + // view; Space and Enter act on the focused row when it is realized. The order of `FocusMove`. + function sourceKey(event: var): bool { + const mods = event.modifiers & (Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier) + if (mods === Qt.ControlModifier && event.key === Qt.Key_A) { + if (root.multiple && root.selectAllHandled) { + root.fire("selectAll", undefined) + return true + } + if (!root.multiple || root.totalRows <= 0) + return false + root.anchorRowIndex = 0 + root.selectRangeTo(root.totalRows - 1, true) + return true + } + if (mods === Qt.ShiftModifier && (event.key === Qt.Key_Up || event.key === Qt.Key_Down)) { + if (root.anchorRowIndex < 0) + root.anchorRowIndex = Math.max(0, root.focusedRowIndex) + root.fire("focusMove", event.key === Qt.Key_Up ? 0 : 1) + root.selectRangeTo(root.focusedRowIndex, false) + return true + } + let move = -1 + if (mods === Qt.ControlModifier && event.key === Qt.Key_Home) + move = 6 + else if (mods === Qt.ControlModifier && event.key === Qt.Key_End) + move = 7 + else if (mods === Qt.NoModifier) { + const keys = [Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right, Qt.Key_Home, Qt.Key_End, -1, -1, + Qt.Key_PageUp, Qt.Key_PageDown] + move = keys.indexOf(event.key) + } + if (move >= 0) { + root.fire("focusMove", move) + return true + } + // Printable text on the focused cell opens its editor with the text. + if (root.takesText && root.focusedRowIndex >= 0 && event.text.length > 0 + && (mods & (Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier)) === 0 + && event.text.charCodeAt(0) >= 32 && event.text.charCodeAt(0) !== 127) { + root.fire("text", event.text) + return true + } + const row = root.realizedRow(root.focusedRowIndex) + if (row && root.hasCellMenu + && ((event.key === Qt.Key_F10 && mods === Qt.ShiftModifier) || event.key === Qt.Key_Menu)) { + row.fire("cellMenu", {"column": root.focusedColumnIndex}) + return true + } + if (root.hasCellMenu && root.question("cellKey", [event.key, event.modifiers])) + return true + if (!row || mods !== Qt.NoModifier) + return false + if (event.key === Qt.Key_Space) { + root.anchorRowIndex = root.focusedRowIndex + row.fire("tap", {"ctrl": true}) + return true + } + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + row.fire("activate", undefined) + return true + } + return false + } + + // Where a column's cells go, from the first column's start: its window entry once the mount lays the columns out, + // else its place at the table's own widths; null for a column not drawn. + function columnSlot(column: int): var { + if (root.arranged) { + const place = root.windowPlaces[column] + if (place === undefined) + return null + const entry = root.windowColumns[place] + return {"offset": entry.offset, "width": entry.width, "pinned": place < root.pinnedShown} + } + if (column < 0 || column >= root.widths.length) + return null + let offset = 0 + for (let i = 0; i < column; ++i) + offset += root.widths[i] + return {"offset": offset, "width": root.widths[column], "pinned": false} + } + + // The realized row at view row `viewRow`, or null. + function realizedRow(viewRow: int): var { + for (let i = 0; i < rowsPlane.children.length; ++i) { + const row = rowsPlane.children[i] + if (row.table === root && row.viewRow === viewRow && row.visible) + return row + } + return null + } + + // For tests: the focused cell; whether a cell is realized and shown; a column's width; a row's height; a + // cell's load state as drawn (0 loaded, 1 unloaded, 2 failed). + function focusedRow(): int { + return root.focusedRowIndex + } + function focusedColumn(): int { + return root.focusedColumnIndex + } + function cellRealized(viewRow: int, column: int): bool { + const row = root.realizedRow(viewRow) + if (!row) + return false + for (let i = 0; i < row.content.children.length; ++i) { + const cell = row.content.children[i] + if (cell.measuredIndex === column && cell.visible) + return true + } + return false + } + function columnWidth(column: int): real { + const place = root.windowPlaces[column] + if (place !== undefined) + return root.windowColumns[place].width + return column < root.widths.length ? root.widths[column] : 0 + } + function rowHeight(viewRow: int): real { + return root.rowHeights[viewRow] ?? root.meanRowHeight + } + // A header's text: its label, then its unit in brackets, as "Copy with headers" writes it. + function headerTextOf(column: var): string { + return column.unit ? column.label + " [" + column.unit + "]" : column.label + } + // The accent of a realized row's cell: {tone, tooltip, invalid}, or null for none. + function cellAccentAt(viewRow: int, column: int): var { + const row = root.realizedRow(viewRow) + return row ? row.accentOf(column) : null + } + function cellLoadAt(viewRow: int, column: int): int { + const row = root.realizedRow(viewRow) + return row ? row.loadOf(column) : 0 + } + // The bar is a child of the flickable itself, not of its content: the attached ScrollBar lays out only a bar whose // parent is the flickable. It is always on while the table scrolls, so a table at rest does not look cut off. Component.onCompleted: { @@ -851,4 +2044,174 @@ MorphWidget { flick.ScrollBar.vertical = vertical } } + + MorphPopupPlacement { + id: menuPlacement + } + + // The header and table menus: a list under the header the menu belongs to (or the `⋯`), opened by `showMenu`. It + // takes the focus: Up and Down move among the entries a user can choose, Right or Enter opens a submenu and Left + // or Backspace goes back up, Enter or Space chooses, and Escape or a press outside closes it and gives the focus + // back to the header. A choice goes to C++ with that header's column and the entry's path. + Popup { + id: configMenu + objectName: "configMenu" + // The entries, as MorphMenu reads them; the path of the submenu shown; the entry the keys are on. + property var entries: [] + property var path: [] + property int current: -1 + property Item anchorItem: null + readonly property var level: { + let shown = configMenu.entries + for (const index of configMenu.path) + shown = shown?.[index]?.items ?? [] + return shown ?? [] + } + + function choosable(entry: var): bool { + return !!entry && entry.separator !== true && entry.heading !== true && entry.enabled === true + } + + // The next entry from @p from in @p step's direction a user can choose or open; @p from when there is none. + function nextEntry(from: int, step: int): int { + for (let at = from + step; at >= 0 && at < configMenu.level.length; at += step) { + if (configMenu.choosable(configMenu.level[at])) + return at + } + return from + } + + // Opens the entry's submenu, or chooses it. + function activate(index: int) { + const entry = configMenu.level[index] + if (!configMenu.choosable(entry)) + return + if (entry.items && entry.items.length > 0) { + configMenu.path = configMenu.path.concat([index]) + configMenu.current = configMenu.nextEntry(-1, 1) + return + } + const chosen = configMenu.path.concat([index]) + configMenu.close() + root.fire("menuChoose", {"column": root.menuColumn, "path": chosen}) + } + + focus: true + padding: Theme.spaceOf(1) + closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside + onAboutToShow: root.placeMenu() + onWidthChanged: { + if (visible) + root.placeMenu() + } + onOpened: entryColumn.forceActiveFocus() + onClosed: { + // A cell's menu gives the focus back to the table, which holds it for its cells. + if (root.menuColumn === -2) + root.forceActiveFocus() + else if (configMenu.anchorItem && configMenu.anchorItem.visible && configMenu.anchorItem.activeFocusOnTab) + configMenu.anchorItem.forceActiveFocus() + } + + background: MorphPopupBackground { + } + + contentItem: ColumnLayout { + id: entryColumn + spacing: 0 + objectName: "configMenuEntries" + focus: true + Accessible.role: Accessible.PopupMenu + Accessible.name: root.menuColumn >= 0 ? (root.columns[root.menuColumn]?.label ?? "") + : root.menuColumn === -2 ? "Cell options" : "Table options" + Keys.onPressed: event => { + const level = configMenu.level + if (event.key === Qt.Key_Down) { + configMenu.current = configMenu.nextEntry(configMenu.current, 1) + } else if (event.key === Qt.Key_Up) { + configMenu.current = configMenu.nextEntry(configMenu.current, -1) + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space + || (event.key === Qt.Key_Right && level[configMenu.current]?.items?.length > 0)) { + configMenu.activate(configMenu.current) + } else if ((event.key === Qt.Key_Left || event.key === Qt.Key_Backspace) + && configMenu.path.length > 0) { + const back = configMenu.path[configMenu.path.length - 1] + configMenu.path = configMenu.path.slice(0, -1) + configMenu.current = back + } else { + return + } + event.accepted = true + } + + Repeater { + model: configMenu.level + + // As a button-style MorphMenu draws an entry: a separator is a line, a checkable entry shows its mark, + // an icon the theme names is drawn as the entry's icon, its chord follows the label, and its + // description is a muted line under it. + ColumnLayout { + id: menuEntry + required property int index + required property var modelData + readonly property bool checkable: modelData.checked === true || modelData.checked === false + spacing: 0 + Layout.fillWidth: true + + MenuSeparator { + visible: menuEntry.modelData.separator === true + Layout.fillWidth: true + } + ItemDelegate { + id: entryButton + objectName: "menuEntry" + menuEntry.index + visible: menuEntry.modelData.separator !== true + Layout.fillWidth: true + font: menuEntry.modelData.heading === true ? Theme.overlineFont : Theme.bodyFont + text: root.menuEntryText(menuEntry.modelData) + + (menuEntry.modelData.keys ? " " + menuEntry.modelData.keys : "") + icon.source: Theme.iconSourceIn(menuEntry.modelData.icon ? menuEntry.modelData.icon : "", + entryButton.palette.text) + icon.color: "transparent" + contentItem: MorphPlainContent { + control: entryButton + color: entryButton.palette.text + alignment: Qt.AlignLeft + } + enabled: configMenu.choosable(menuEntry.modelData) + highlighted: menuEntry.index === configMenu.current + focusPolicy: Qt.NoFocus + Accessible.role: menuEntry.modelData.heading === true ? Accessible.StaticText + : Accessible.MenuItem + Accessible.name: menuEntry.modelData.label ?? "" + Accessible.description: menuEntry.modelData.description ?? "" + Accessible.checkable: menuEntry.checkable + Accessible.checked: menuEntry.modelData.checked === true + // Both the attached `Accessible` and the button itself carry the state: which of the two a + // Qt version reports to assistive technology differs, and a button writes its own state over + // the attached one once assistive technology is active. + checkable: menuEntry.checkable + checked: menuEntry.modelData.checked === true + // A click on a checkable button toggles `checked` and breaks the binding; the entry's state is + // the document's, so the binding is put back before the click is acted on. + onClicked: { + entryButton.checked = Qt.binding(() => menuEntry.modelData.checked === true) + configMenu.activate(menuEntry.index) + } + } + Label { + textFormat: Text.PlainText + visible: menuEntry.modelData.separator !== true && !!menuEntry.modelData.description + text: menuEntry.modelData.description ? menuEntry.modelData.description : "" + font: Theme.bodyFont + color: root.scheme.muted + leftPadding: Theme.spaceOf(3) + bottomPadding: Theme.spaceOf(1) + Layout.fillWidth: true + Accessible.ignored: true + } + } + } + } + } } diff --git a/src/qt_quick/qml/MorphTableHeaderEdge.qml b/src/qt_quick/qml/MorphTableHeaderEdge.qml new file mode 100644 index 000000000..76df98acc --- /dev/null +++ b/src/qt_quick/qml/MorphTableHeaderEdge.qml @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +pragma ComponentBehavior: Bound +import QtQuick + +// A header's trailing edge, while its table's columns can be resized: dragging it reports the column's new width in +// pixels (`columnResize`), and a double click on it reports none, which gives the column its declared width again. +Item { + id: edge + + // The column whose header this edge ends, an index into the table's columns. + property int column: -1 + // The MorphTable the header belongs to; read through `var`, as its own members (`resizable`, `fire`) are not an + // Item's. + property var table: null + + // The last translation of the drag under way: the handler resets its own before it reports the drag ended. + property real dragged: 0 + + visible: edge.table !== null && edge.table.resizable + objectName: "edge" + edge.column + // Above the header's filter button, which sits at the same edge and would otherwise take the strip's input. + z: 1 + anchors.right: parent ? parent.right : undefined + anchors.top: parent ? parent.top : undefined + anchors.bottom: parent ? parent.bottom : undefined + width: 6 + + HoverHandler { + cursorShape: Qt.SplitHCursor + } + DragHandler { + id: drag + yAxis.enabled: false + target: null + onActiveTranslationChanged: { + if (drag.active) + edge.dragged = drag.activeTranslation.x + } + onActiveChanged: { + if (drag.active) { + edge.dragged = 0 + } else if (edge.parent) { + edge.table.fire("columnResize", {"column": edge.column, + "width": Math.max(1, edge.parent.width + edge.dragged)}) + } + } + } + TapHandler { + onDoubleTapped: edge.table.fire("columnResize", {"column": edge.column, "width": null}) + } +} diff --git a/src/qt_quick/qml/MorphTableRow.qml b/src/qt_quick/qml/MorphTableRow.qml index 36fffcdd9..97d6c47c4 100644 --- a/src/qt_quick/qml/MorphTableRow.qml +++ b/src/qt_quick/qml/MorphTableRow.qml @@ -16,6 +16,20 @@ import QtQuick.Layouts // background, the look of the row over the whole block, and a tap handler of its own, since the block lies outside // the row's bounds, which the row's handlers would not reach. Hover is the row's own: its `containmentMask` takes in // the blocks. A row ignores a tap in a spanning or covered column: the backdrop took it. +// +// In a table whose columns the mount lays out (`table.arranged`), each cell is placed in the column C++ gave it +// (`measuredIndex`), at the window's offset and width; a pinned column's cell is held at the leading edge, over the +// rest. A cell whose column has not loaded (`cellLoads`) keeps its content, bound but invisible, under a mark: a +// rounded bar 3 em wide for one not loaded, an error mark of the same width for one that failed. A cell's accent +// (`cellAccents`) tints its slot over the row's background and under the cell, at half the tone's fill, so the +// cell keeps its tone in a toned or selected row and the selection shows through; a tooltip draws the "more here" +// mark, shows on hover after the style's delay and at once while the cell has the keyboard focus, and is the slot's +// accessible name; a value that could not be read draws the error mark in place of the cell, with the accent's +// tooltip. A cell's marks (`cellMarks`) draw over its slot: a read-only cell's muted wash, a modified cell's corner +// mark, an error outline. An open cell editor is placed in its cell's column, over the cell, which C++ covers. A +// modified row (`modified`) draws its mark at the leading edge. In a table that reports cell clicks, each tap reports +// its cell (`cellClick`), a double tap a second time with `double`. The row's `measuredHeight` is its tallest placed +// cell's, unless every column keeps one line; the table sets its height. MorphWidget { id: root @@ -36,7 +50,80 @@ MorphWidget { // row, and the row hands its state to the instance. property Component background: null readonly property bool hovered: rowHover.hovered - readonly property bool current: root.holdsFocus(Window.activeFocusItem) + // The row's view row, in a table over a source; C++ writes it. A recycled slot measures its cells again for the + // row it now shows, and is striped by the view row's parity, not by its place among the children. + property int viewRow: -1 + onViewRowChanged: { + if (root.viewRow >= 0) { + root.alternate = root.viewRow % 2 === 1 + root.schedulePlace() + } + } + // Places the cells once, from the event loop: C++ asks for it as each cell of a pass is placed or pooled. The + // flag keeps the many asks of one turn to one placing; `Qt.callLater` alone does not join calls of a method. + property bool placeQueued: false + function schedulePlace() { + if (root.placeQueued) + return + root.placeQueued = true + Qt.callLater(root.placeQueuedNow) + } + // Places for a change in a cell's own size: at once in a table of its own rows; in a table over a source, with + // the other asks of the turn, since a cell's size changes several times as the cell is placed and each change + // would place every cell of the row again. + function placeSoon() { + if (root.table && root.table.sourceRows) + root.schedulePlace() + else + root.place() + } + function placeQueuedNow() { + root.placeQueued = false + root.place() + } + // The height the row's cells ask for, in a table over a source (the table keeps it no lower than it was when the + // column window last changed). + property real measuredHeight: 0 + // The table's `windowEpoch` when `measuredHeight` was measured. + property int measuredEpoch: 0 + onMeasuredEpochChanged: { + if (root.table) + root.table.scheduleRows() + } + onMeasuredHeightChanged: { + if (root.table) + root.table.scheduleRows() + } + // The columns whose cells have not loaded, by column as text: 1 not loaded, 2 failed. C++ writes it. + property var cellLoads: ({}) + // The marks drawn over those cells: [{x, width, load, align}]. + property var loadMarks: [] + function loadOf(column: int): int { + return root.cellLoads[String(column)] ?? 0 + } + onCellLoadsChanged: root.place() + // The columns whose cells have an accent, by column as text: {tone, tooltip, invalid}. C++ writes it. + property var cellAccents: ({}) + // The accents drawn in those cells' slots: [{x, offset, width, column, tone, tooltip, pinned}]. + property var accentMarks: [] + function accentOf(column: int): var { + return root.cellAccents[String(column)] ?? null + } + onCellAccentsChanged: root.place() + // The columns whose cells have marks, by column as text: {readOnly, modified, error, stale, muted}. C++ writes it. + property var cellMarks: ({}) + // The marks drawn over those cells' slots: [{x, width, column, readOnly, modified, error, muted}]. + property var cellMarkSlots: [] + onCellMarksChanged: root.place() + // Whether a cell of the row changed since the record was loaded; C++ writes it. + property bool modified: false + // The column of the row's open cell editor, or -1, and the editor's item, or null; C++ writes both. + property int editorColumn: -1 + property Item editorItem: null + // Over a source the table holds the focus and names the focused row; otherwise the row holds it. + readonly property bool current: root.table && root.table.sourceRows + ? root.table.activeFocus && root.viewRow === root.table.focusedRowIndex + : root.holdsFocus(Window.activeFocusItem) onCurrentChanged: { if (current && root.table) root.table.currentRow = root @@ -47,6 +134,21 @@ MorphWidget { property int tone: -1 // Whether the row is a group heading; C++ sets it once, right after the row's key. property bool heading: false + // Whether the row is a summary row, drawn on `Theme.tableSummary` and never selected, activated or edited; C++ + // sets it once, right after the row's key. + property bool summary: false + // The row's marks (`setRowMarks`): an action is working on it, another user holds it, it no longer matches the + // filter, and what its tooltip says of them. An unmatched row draws at the theme's muted opacity. + property bool busy: false + property bool locked: false + property bool unmatched: false + property string marksTooltip: "" + opacity: unmatched ? Theme.mutedOpacity : 1.0 + // A busy or locked row always says why, over the row's own tooltip. + tooltipText: marksTooltip !== "" ? marksTooltip + : locked ? qsTr("Locked by another user") + : busy ? qsTr("Saving this row") + : tooltip readonly property Item backgroundItem: backgroundLoader.item as Item // The cells that span, C++'s resolve of the row's spans: [{column, rows}], and the columns of this row that a // span above covers: [column]. The table gives each spanning column the block it covers: [{column, height}], and @@ -96,6 +198,41 @@ MorphWidget { return false } + // The column of the cell under `x`, in the row's own coordinates: by the window over a source the mount lays out, + // a pinned column before the scrolled ones under it, else by the table's widths; -1 for none. + function columnAt(x: real): int { + const table = root.table + if (!table) + return -1 + if (table.arranged) { + for (let place = 0; place < table.windowColumns.length; ++place) { + const entry = table.windowColumns[place] + const left = table.lead + entry.offset + (place < table.pinnedShown ? table.scrollX : 0) + if (x >= left && x < left + entry.width) + return entry.column + } + return -1 + } + for (let i = 0; i < root.widths.length; ++i) { + if (x >= root.columnLeft(i) && x < root.columnLeft(i) + root.widths[i]) + return i + } + return -1 + } + + // A right click or a long press at `x`: the menu of the cell there. The table takes the focus over a source, as a + // click does. + function openCellMenu(x: real) { + if (!root.table || !root.table.hasCellMenu || root.heading || root.summary) + return + const column = root.columnAt(x) + if (column < 0) + return + if (root.table.sourceRows && !root.holdsFocus(root.Window.activeFocusItem)) + root.table.forceActiveFocus(Qt.MouseFocusReason) + root.fire("cellMenu", {"column": column}) + } + function holdsFocus(focused: Item): bool { for (let at = focused; at; at = at.parent) { if (at === root) @@ -112,6 +249,20 @@ MorphWidget { return false } + // The width the spanning cell of column `index` is laid out across: its column's and the next ones' it covers, + // else its column's alone. + function spanWidth(index: int): real { + let columns = 1 + for (const span of root.spanPlan) { + if (span.column === index && span.columns !== undefined) + columns = span.columns + } + let width = 0 + for (let i = index; i < index + columns && i < root.widths.length; ++i) + width += root.widths[i] + return width + } + // Each cell sits inset by `table.cellPaddingX` and `table.cellPaddingY`, as the header label is (MorphTable.qml), // so its text lines up under its header, and a row is as tall as its tallest cell plus twice the vertical inset. // A cell fills its column's width, except a kind whose width is its label (`fillsAcross` @@ -163,6 +314,10 @@ MorphWidget { function placeOnce() { const inset = Theme.tableCellPaddingX const insetY = Theme.tableCellPaddingY + if (root.table && root.table.sourceRows && !root.heading) { + root.placeWindowed() + return + } if (root.heading) { let across = root.table ? root.table.lead : 0 for (const w of root.widths) @@ -189,7 +344,8 @@ MorphWidget { for (let i = 0; i < cells.children.length; ++i) { const cell = cells.children[i] const w = i < root.widths.length ? root.widths[i] : cell.implicitWidth - const room = Math.max(0, w - 2 * inset) + // A cell spanning columns is laid out across them; the columns after it keep their places. + const room = Math.max(0, (root.isSpanning(i) ? root.spanWidth(i) : w) - 2 * inset) const across = i < root.columns.length ? root.columns[i].align : 1 if ((cell as MorphWidget)?.fillsAcross === false) { cell.width = Math.min(cell.implicitWidth, room) @@ -227,6 +383,211 @@ MorphWidget { } } + // Each placed cell in its column (`table.columnSlot`); a pooled cell (no column, hidden by C++) is left where it is. + function placeWindowed() { + const table = root.table + const inset = Theme.tableCellPaddingX + const insetY = Theme.tableCellPaddingY + const measure = !table.allOneLine + const placed = [] + const marks = [] + const accents = [] + const marked = [] + let tallest = 0 + for (let i = 0; i < cells.children.length; ++i) { + const cell = cells.children[i] + const column = cell.measuredIndex + const slot = cell === root.pinnedBackdrop || column === undefined ? null : table.columnSlot(column) + if (!slot) + continue + const pinned = slot.pinned + const left = table.lead + slot.offset + (pinned ? table.scrollX : 0) + const room = Math.max(0, slot.width - 2 * inset) + const spec = column < root.columns.length ? root.columns[column] : null + const across = spec ? spec.align : 1 + if ((cell as MorphWidget)?.fillsAcross === false) { + cell.width = Math.min(cell.implicitWidth, room) + const spare = room - cell.width + cell.x = left + inset + (across === 3 ? spare : across === 2 ? Math.floor(spare / 2) : 0) + } else { + cell.width = room + cell.x = left + inset + } + cell.z = pinned ? 1 : 0 + const accent = root.accentOf(column) + const loaded = root.loadOf(column) + // A value that could not be read draws the error mark in place of its text, as a failed load does. + const load = loaded !== 0 ? loaded : accent && accent.invalid ? 2 : 0 + // Assigning the opacity replaces the cell's own binding, which dims a stale field, so a cell shown again + // gets it back; a cell that was never hidden keeps the binding it has. + if (load !== 0) + cell.opacity = 0 + else if (cell.opacity === 0) + cell.opacity = cell.stale !== undefined ? Qt.binding(() => cell.stale ? Theme.staleOpacity : 1.0) : 1 + if (load !== 0) + marks.push({"x": left + inset, "width": room, "load": load, "align": across, "pinned": pinned, + "tip": loaded === 0 && accent ? accent.tooltip : ""}) + if (accent && (accent.tone >= 0 || accent.tooltip !== "")) + accents.push({"x": left, "offset": slot.offset, "width": slot.width, "column": column, + "tone": accent.tone, "tooltip": accent.tooltip, "pinned": pinned}) + const cellMark = root.cellMarks[String(column)] ?? null + if (cellMark && cell.visible) + marked.push({"x": left, "width": slot.width, "column": column, "readOnly": cellMark.readOnly, + "modified": cellMark.modified, "error": cellMark.error, + "muted": cellMark.muted || cellMark.stale}) + if (cell.textAlign !== undefined && !cell.ownAlign) + cell.textAlign = across === 3 ? Qt.AlignRight : across === 2 ? Qt.AlignHCenter : Qt.AlignLeft + if (cell.singleLine !== undefined) + cell.singleLine = !(spec && spec.wrap) + if (cell.elideToWidth !== undefined) + cell.elideToWidth = true + if (cell.tabularFigures !== undefined) + cell.tabularFigures = across === 3 + if (measure && cell.visible) { + ++table.rowMeasures + tallest = Math.max(tallest, cell.implicitHeight) + } + placed.push(cell) + } + const own = measure ? tallest + 2 * insetY : table.oneLineRowHeight + root.measuredEpoch = table.windowEpoch + root.measuredHeight = Math.max(own, root.backgroundItem ? root.backgroundItem.implicitHeight : 0) + cells.implicitWidth = table.columnsWidth + cells.implicitHeight = root.measuredHeight + const space = Math.max(0, (root.height > 0 ? root.height : root.measuredHeight) - 2 * insetY) + for (const cell of placed) { + const down = cell.measuredIndex < root.columns.length ? root.columns[cell.measuredIndex].valign : 2 + cell.height = down === 0 ? space : Math.min(cell.implicitHeight, space) + const spare = space - cell.height + cell.y = insetY + (down === 3 ? spare : down === 2 ? Math.floor(spare / 2) : 0) + } + if (JSON.stringify(marks) !== JSON.stringify(root.loadMarks)) + root.loadMarks = marks + if (JSON.stringify(accents) !== JSON.stringify(root.accentMarks)) + root.accentMarks = accents + if (JSON.stringify(marked) !== JSON.stringify(root.cellMarkSlots)) + root.cellMarkSlots = marked + root.placeBackdrop() + } + + // The opaque surface under the pinned cells, which the scrolled cells pass beneath: the surface, then the row's + // own background cut to the pinned columns, so the row's state shows there as on the rest of the row. It is made + // in `cells` (the cells' sibling, so it can lie between the scrolled cells and the pinned ones) only for a table + // over a source with pinned columns, so a row of any other table holds nothing in `cells` but its cells. + property Item pinnedBackdrop: null + Component { + id: pinnedBackdropComponent + Item { + id: backdrop + objectName: "pinnedBackdrop" + z: 0.5 + clip: true + Rectangle { + anchors.fill: parent + color: root.scheme.surface + } + Loader { + id: backdropLoader + x: -backdrop.x + width: root.width + height: backdrop.height + sourceComponent: root.background + } + Binding { + target: backdropLoader.item + property: "selected" + value: root.selected + } + Binding { + target: backdropLoader.item + property: "hovered" + value: root.hovered + } + Binding { + target: backdropLoader.item + property: "current" + value: root.current + } + Binding { + target: backdropLoader.item + property: "alternate" + value: root.alternate + } + Binding { + target: backdropLoader.item + property: "tone" + value: root.tone + } + Binding { + target: backdropLoader.item + property: "scheme" + value: root.scheme + } + Binding { + target: backdropLoader.item + property: "selectColumn" + value: root.table ? root.table.selectColumn : false + when: backdropLoader.item !== null && ("selectColumn" in backdropLoader.item) + } + // The pinned cells' accent slots, over the backdrop's background and under the pinned cells. + Repeater { + model: root.accentMarks.filter(mark => mark.pinned) + delegate: accentSlot + } + } + } + function placeBackdrop() { + const table = root.table + const shown = table && table.arranged && table.pinnedShown > 0 && table.pinnedEdge > 0 + if (shown && !root.pinnedBackdrop) + root.pinnedBackdrop = pinnedBackdropComponent.createObject(cells) + if (!root.pinnedBackdrop) + return + root.pinnedBackdrop.visible = shown + if (shown) { + root.pinnedBackdrop.x = table.lead + table.scrollX + root.pinnedBackdrop.width = table.pinnedEdge + root.pinnedBackdrop.height = root.height + } + } + + // The pinned cells follow the sideways scroll, so they stay at the leading edge; nothing else moves. + function placePinned() { + const table = root.table + if (!table || !table.arranged || table.pinnedShown === 0) + return + for (let i = 0; i < cells.children.length; ++i) { + const cell = cells.children[i] + const place = cell.measuredIndex >= 0 ? table.windowPlaces[cell.measuredIndex] : undefined + if (place === undefined || place >= table.pinnedShown) + continue + const entry = table.windowColumns[place] + const room = Math.max(0, entry.width - 2 * Theme.tableCellPaddingX) + cell.x = table.lead + entry.offset + table.scrollX + Theme.tableCellPaddingX + (room - cell.width) * + (cell.fillsAcross === false ? (root.columns[cell.measuredIndex].align === 3 ? 1 + : root.columns[cell.measuredIndex].align === 2 ? 0.5 : 0) : 0) + } + root.placeBackdrop() + if (root.loadMarks.some(mark => mark.pinned)) + root.place() + } + Connections { + target: root.table + enabled: root.table !== null && root.table.sourceRows + function onScrollXChanged() { + root.placePinned() + } + function onWindowColumnsChanged() { + root.place() + } + } + // A height change while placing is the placing's own (the row's implicit height follows its cells), and the + // placing already reads the new height; placing again for it would only repeat the pass. + onHeightChanged: { + if (root.table && root.table.sourceRows && !root.placing) + root.place() + } + Connections { target: Theme function onTableCellPaddingXChanged() { @@ -264,11 +625,11 @@ MorphWidget { // A chord the table declares comes before the row's activation. Keys.onReturnPressed: event => { - if (!root.heading && !(root.table && root.table.takeOwnChord(event))) + if (!root.heading && !root.summary && !(root.table && root.table.takeOwnChord(event))) root.fire("activate", undefined) } Keys.onEnterPressed: event => { - if (!root.heading && !(root.table && root.table.takeOwnChord(event))) + if (!root.heading && !root.summary && !(root.table && root.table.takeOwnChord(event))) root.fire("activate", undefined) } @@ -326,6 +687,35 @@ MorphWidget { id: rowHover } + // A busy row's mark: a 3 px bar in `Theme.tableBusy` just inside the selection's bar, so a selected busy row shows + // both; the anchors follow a right-to-left layout. A locked row's: a `Theme.tableLocked` wash over its cells. + Rectangle { + objectName: "busyMark" + visible: root.busy + anchors.left: parent.left + anchors.leftMargin: 3 + anchors.top: parent.top + z: 3 + width: 3 + height: root.height + color: Theme.tableBusy + } + Rectangle { + objectName: "lockedWash" + visible: root.locked + anchors.fill: parent + z: 3 + color: Theme.tableLocked + } + // A summary row's surface, over its background and under nothing it draws: translucent, so cells read through. + Rectangle { + objectName: "summaryFill" + visible: root.summary + anchors.fill: parent + z: 3 + color: Theme.tableSummary + } + // Hover is delivered only to an item whose bounds hold the pointer, so the part of a spanning cell below the row // is part of the row for it: the row's own rectangle and the blocks of its spanning cells. containmentMask: QtObject { @@ -334,7 +724,7 @@ MorphWidget { return true for (const span of root.spanPlan) { const left = root.columnLeft(span.column) - if (span.column < root.widths.length && point.x >= left && point.x < left + root.widths[span.column] && + if (span.column < root.widths.length && point.x >= left && point.x < left + root.spanWidth(span.column) && point.y >= 0 && point.y < root.blockHeight(span.column)) return true } @@ -350,7 +740,7 @@ MorphWidget { objectName: "spanBackdrop" x: root.columnLeft(modelData.column) y: 0 - width: modelData.column < root.widths.length ? root.widths[modelData.column] : 0 + width: modelData.column < root.widths.length ? root.spanWidth(modelData.column) : 0 height: root.blockHeight(modelData.column) clip: true Rectangle { @@ -409,10 +799,160 @@ MorphWidget { } } + // Each accented cell's slot: the tone's tint, the "more here" mark and the tooltip. A slot lies over the row's + // background, so a cell keeps its tone in a toned or a selected row, and under the cells; its tint is half the + // tone's fill, so the selection fill and bar show through it. A scrolled cell's slot is the row's own child, made + // after the background and before `cells`; a pinned cell's is the pinned backdrop's, over its copy of the + // background and under the pinned cells. Either way the same layers lie under and over it. + Component { + id: accentSlot + Item { + id: accentMark + required property var modelData + readonly property bool focusedCell: root.current && root.table !== null + && root.table.focusedColumnIndex === modelData.column + objectName: "cellAccent" + modelData.column + // A pinned slot is placed in the backdrop, which follows the sideways scroll itself. + x: modelData.pinned ? modelData.offset : modelData.x + width: modelData.width + height: root.height + Rectangle { + objectName: "cellTint" + anchors.fill: parent + visible: accentMark.modelData.tone >= 0 + color: Qt.alpha(root.toneBgOf(accentMark.modelData.tone), 0.5) + } + Rectangle { + objectName: "moreMark" + visible: accentMark.modelData.tooltip !== "" + anchors.top: parent.top + anchors.right: parent.right + width: Math.round(Theme.bodyFont.pixelSize * 0.4) + height: width + color: root.scheme.accent + } + HoverHandler { + id: accentHover + } + ToolTip.visible: accentMark.modelData.tooltip !== "" && (accentHover.hovered || accentMark.focusedCell) + ToolTip.delay: accentMark.focusedCell ? 0 : Application.styleHints.mousePressAndHoldInterval + ToolTip.text: accentMark.modelData.tooltip + // The cell names itself; its slot carries only the tooltip, and only when there is one. + Accessible.role: Accessible.ToolTip + Accessible.name: accentMark.modelData.tooltip + Accessible.description: accentMark.modelData.tooltip + Accessible.ignored: accentMark.modelData.tooltip === "" + } + } + Repeater { + objectName: "scrolledAccents" + model: root.accentMarks.filter(mark => !mark.pinned) + delegate: accentSlot + } + + // A read-only cell's wash, under the cells; a modified cell's corner mark and an error outline over them. + Repeater { + objectName: "cellMarks" + model: root.cellMarkSlots + delegate: Item { + id: cellMark + required property var modelData + objectName: "cellMark" + modelData.column + x: modelData.x + z: 2 + width: modelData.width + height: root.height + Rectangle { + objectName: "readOnlyWash" + anchors.fill: parent + visible: cellMark.modelData.readOnly + color: Qt.alpha(root.scheme.muted, 0.12) + } + Rectangle { + objectName: "modifiedMark" + visible: cellMark.modelData.modified + anchors.top: parent.top + anchors.left: parent.left + width: Math.round(Theme.bodyFont.pixelSize * 0.4) + height: width + color: root.scheme.accent + } + Rectangle { + objectName: "errorOutline" + anchors.fill: parent + visible: cellMark.modelData.error + color: "transparent" + border.width: 1 + border.color: root.scheme.error + } + opacity: modelData.muted ? Theme.mutedOpacity : 1.0 + } + } + Item { id: cells anchors.fill: parent - onChildrenChanged: root.place() + // A source table adopts or pools a row's cells one at a time and asks for the placing itself once the pass is + // done (`schedulePlace`); placing at each one would make the pass quadratic in the row's cells. + onChildrenChanged: { + if (root.table && root.table.sourceRows) + return + root.place() + } + } + + // A modified row's mark: a bar at the leading edge. + Rectangle { + objectName: "rowModifiedMark" + visible: root.modified + x: 0 + width: 2 + height: root.height + z: 2 + color: root.scheme.accent + } + + // A cell not loaded draws a rounded bar; one that failed, an error mark; each 3 em wide in its column's alignment. + Repeater { + model: root.loadMarks + delegate: Item { + id: mark + required property var modelData + readonly property real markWidth: Math.min(3 * Theme.bodyFont.pixelSize, modelData.width) + objectName: modelData.load === 2 ? "failedMark" : "unloadedMark" + x: modelData.x + (modelData.align === 3 ? modelData.width - markWidth + : modelData.align === 2 ? (modelData.width - markWidth) / 2 : 0) + z: 2 + width: markWidth + height: root.height + Rectangle { + visible: mark.modelData.load === 1 + anchors.verticalCenter: parent.verticalCenter + width: parent.width + height: Math.round(Theme.bodyFont.pixelSize * 0.6) + radius: height / 2 + color: root.scheme.muted + opacity: 0.35 + } + Text { + id: failedText + visible: mark.modelData.load === 2 + anchors.verticalCenter: parent.verticalCenter + width: parent.width + horizontalAlignment: Text.AlignHCenter + text: "!" + font: Theme.strongFont + color: root.scheme.error + Accessible.role: Accessible.StaticText + Accessible.name: mark.modelData.tip ? mark.modelData.tip : "Could not be loaded" + Accessible.description: mark.modelData.tip ?? "" + HoverHandler { + id: failedHover + } + ToolTip.visible: failedHover.hovered + ToolTip.text: mark.modelData.tip ? mark.modelData.tip : "Could not be loaded" + } + } } // The row's select box: checked while the row is selected, and a click on it is a Ctrl-click on the row. It shows @@ -445,12 +985,36 @@ MorphWidget { // A click, as the row takes it: by the row's own handler, or by a spanning cell's backdrop, which passes its point // in the row's coordinates (a point past the row's bottom). function tapped(modifiers: int, tapCount: int, x: real, y: real, fromRow: bool) { - if (root.heading) + if (root.heading || root.summary) return // The backdrop takes a tap in a spanning or covered column; the row's own handler leaves it. if (fromRow && root.inSpannedColumn(x)) return const held = modifiers & (Qt.ControlModifier | Qt.ShiftModifier) + // A table that selects cells takes a click on the row's header, the leading strip before the first column, as + // the row's cells, and a Shift-click on a cell as a rectangle from its focused cell; it selects no row. + if (root.table && root.table.selectsCells) { + if (x < root.table.lead) { + root.table.selectRowCells(root.viewRow) + return + } + const at = root.columnAt(x) + if (held === Qt.ShiftModifier && at >= 0) { + root.table.selectCellsTo(root.viewRow, at) + return + } + } + // A table that takes cell clicks hears every tap on a cell; its second tap of a double tap opens the cell. + if (root.table && root.table.reportsCellClicks) { + const column = root.columnAt(x) + if (column >= 0) { + if (root.table.sourceRows && !root.holdsFocus(root.Window.activeFocusItem)) + root.table.forceActiveFocus(Qt.MouseFocusReason) + root.fire("cellClick", {"column": column, "double": tapCount >= 2 && held === Qt.NoModifier}) + if (tapCount >= 2) + return + } + } // Only plain clicks make a double click, so two quick Ctrl-clicks toggle a row twice. if (tapCount >= 2 && held === Qt.NoModifier) { root.fire("activate", undefined) @@ -459,9 +1023,20 @@ MorphWidget { // A click on the select box is the box's own. if (fromRow && selectBox.visible && selectBox.contains(selectBox.mapFromItem(root, Qt.point(x, y)))) return - // The row takes the focus unless a control in one of its cells took it with the press. - if (!root.holdsFocus(root.Window.activeFocusItem)) + // Over a source the table takes the focus, never the row, which a recycled slot would take away; a + // Shift-click selects through the mount, from the table's anchor, and any other click makes this row the anchor. + // Otherwise the row takes the focus unless a control in one of its cells took it with the press. + if (root.table && root.table.sourceRows) { + if (!root.holdsFocus(root.Window.activeFocusItem)) + root.table.forceActiveFocus(Qt.MouseFocusReason) + if ((modifiers & Qt.ShiftModifier) !== 0 && (modifiers & Qt.ControlModifier) === 0 && root.table.multiple) { + root.table.selectRangeTo(root.viewRow, false) + return + } + root.table.anchorRowIndex = root.viewRow + } else if (!root.holdsFocus(root.Window.activeFocusItem)) { root.forceActiveFocus(Qt.MouseFocusReason) + } root.fire("tap", { "ctrl": (modifiers & Qt.ControlModifier) !== 0, "shift": (modifiers & Qt.ShiftModifier) !== 0 @@ -470,7 +1045,22 @@ MorphWidget { TapHandler { id: tap - enabled: !root.heading + enabled: !root.heading && !root.summary onTapped: root.tapped(tap.point.modifiers, tap.tapCount, tap.point.position.x, tap.point.position.y, true) } + + TapHandler { + id: contextTap + enabled: !root.heading && !root.summary && root.table !== null && root.table.hasCellMenu + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + acceptedButtons: Qt.RightButton + onTapped: root.openCellMenu(contextTap.point.position.x) + } + + TapHandler { + id: pressTap + enabled: !root.heading && !root.summary && root.table !== null && root.table.hasCellMenu + acceptedDevices: PointerDevice.TouchScreen + onLongPressed: root.openCellMenu(pressTap.point.position.x) + } } diff --git a/src/qt_quick/qml/MorphTextInput.qml b/src/qt_quick/qml/MorphTextInput.qml index 3d2afec08..714bbb335 100644 --- a/src/qt_quick/qml/MorphTextInput.qml +++ b/src/qt_quick/qml/MorphTextInput.qml @@ -85,7 +85,9 @@ MorphField { Keys.onEnterPressed: event => root.enterPressed(event) // Every other key: the widget's own chords come before the field's handling of it. Keys.onPressed: event => { - if (event.key !== Qt.Key_Return && event.key !== Qt.Key_Enter) + if (event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) + event.accepted = root.takeOwnChord(event) || root.takeAncestorChord(event) + else if (event.key !== Qt.Key_Return && event.key !== Qt.Key_Enter) event.accepted = root.takeOwnChord(event) } // The elided copy draws the text in its place while it shows. diff --git a/src/qt_quick/qml/MorphWidget.qml b/src/qt_quick/qml/MorphWidget.qml index e7969106d..4d42a960d 100644 --- a/src/qt_quick/qml/MorphWidget.qml +++ b/src/qt_quick/qml/MorphWidget.qml @@ -277,6 +277,17 @@ Item { return root.chords.length > 0 && root.question("chord", [key, modifiers]) } + // Runs the chord a key is when an ancestor widget declares it, the nearest first; returns whether one did. A text + // field calls it for Tab, which Qt's text input takes for itself before the key reaches an ancestor's handler. + function takeAncestorChord(event: var): bool { + for (let item = root.parent; item; item = item.parent) { + const widget = item as MorphWidget + if (widget && widget.chords.length > 0) + return widget.takeOwnChord(event) + } + return false + } + // A content child under an alignment other than stretch keeps its own extent across; a stretch child keeps its // fill, and its maximum with the alignment places it. // Whether this widget hands the width it has to each widget in it, as a row of actions in a sheet's footer does: diff --git a/src/qt_quick/qml/Theme.qml b/src/qt_quick/qml/Theme.qml index a10d2f09d..241689493 100644 --- a/src/qt_quick/qml/Theme.qml +++ b/src/qt_quick/qml/Theme.qml @@ -203,6 +203,13 @@ QtObject { property color chart3: "#00805e" property color chart4: "#a8508a" property real staleOpacity: 0.55 + // The opacity of a table row kept in view although it no longer matches the filter: `opacity.muted`. + property real mutedOpacity: 0.55 + // A busy table row's bar and a locked one's wash: `color.table.busy`, `color.table.locked`. + property color tableBusy: "#1565c0" + property color tableLocked: "#388e8e93" + // A table's summary row's surface: `color.table.summary`. + property color tableSummary: "#1f8e8e93" // The window behind every surface, the corner radii, the height of an input or a button, and the font sizes, in // px. A font size of 0 is derived from the platform font: the body is its size, a heading 1.3 times the body. property color background: "#f2f3f7" diff --git a/src/qt_quick/table.cpp b/src/qt_quick/table.cpp index 27b1665ac..93e63897f 100644 --- a/src/qt_quick/table.cpp +++ b/src/qt_quick/table.cpp @@ -3,11 +3,18 @@ #include #include #include +#include +#include +#include +#include #include #include #include +#include #include +#include #include +#include #include #include #include @@ -18,6 +25,7 @@ namespace morph::qt_quick::detail { +// NOLINTNEXTLINE(readability-function-cognitive-complexity): the constructor wires every signal of the QML table to its handler in one place; the connections share the locals they capture TableImpl::TableImpl(Context& context, ui::ContainerWidget* parent) : ContainerItemWidget{ context, QStringLiteral("MorphTable"), parent, @@ -31,27 +39,230 @@ TableImpl::TableImpl(Context& context, ui::ContainerWidget* parent) static_cast(std::max(0, map.value(QStringLiteral("count")).toLongLong()))); }); relay().on(QStringLiteral("selectAll"), [this](QVariant const&) { selectAll(); }); + // A copy of each handler below: it may destroy this table. + relay().on(QStringLiteral("hscroll"), [this](QVariant const& payload) { + QVariantMap const map = payload.toMap(); + if (auto const handler = _onHorizontalRange) { + handler(map.value(QStringLiteral("scrollX")).toInt(), map.value(QStringLiteral("viewport")).toInt()); + } + }); + relay().on(QStringLiteral("measured"), [this](QVariant const& payload) { + QVariantMap const map = payload.toMap(); + qlonglong const column = map.value(QStringLiteral("column")).toLongLong(); + if (auto const handler = _onColumnMeasured; handler && column >= 0) { + handler(static_cast(column), + ui::ColumnMeasure{.header = map.value(QStringLiteral("header")).toInt(), + .natural = map.value(QStringLiteral("natural")).toInt(), + .least = map.value(QStringLiteral("least")).toInt()}); + } + }); + relay().on(QStringLiteral("focusMove"), [this](QVariant const& payload) { + int const move = payload.toInt(); + if (auto const handler = _onFocusMove; + handler && move >= 0 && move <= static_cast(ui::FocusMove::PageDown)) { + handler(static_cast(move)); + } + }); + relay().on(QStringLiteral("selectRange"), [this](QVariant const& payload) { + QVariantMap const map = payload.toMap(); + qlonglong const anchor = map.value(QStringLiteral("anchor")).toLongLong(); + qlonglong const focus = map.value(QStringLiteral("focus")).toLongLong(); + if (auto const handler = _onSelectRange; handler && anchor >= 0 && focus >= 0) { + handler(static_cast(anchor), static_cast(focus), + map.value(QStringLiteral("extend")).toBool() ? ui::SelectionChange::Extend + : ui::SelectionChange::Replace); + } + }); + relay().on(QStringLiteral("statusEntry"), [this](QVariant const& columnId) { + if (auto const handler = _onStatusEntry) { + handler(columnId.toString().toStdString()); + } + }); + relay().on(QStringLiteral("retry"), [this](QVariant const&) { + if (auto const handler = _onRetry) { + handler(); + } + }); + relay().on(QStringLiteral("text"), [this](QVariant const& text) { + if (auto const handler = _onText) { + handler(text.toString().toStdString()); + } + }); + relay().on(QStringLiteral("focusOut"), [this](QVariant const&) { + if (auto const handler = _onFocusOut) { + handler(); + } + }); relay().on(QStringLiteral("sort"), [this](QVariant const& payload) { - if (_onSort && payload.toLongLong() >= 0) { + QVariantMap const map = payload.toMap(); + qlonglong const column = map.value(QStringLiteral("column")).toLongLong(); + if (auto const handler = _onSort; handler && column >= 0) { + handler(static_cast(column), + map.value(QStringLiteral("shift")).toBool() ? ui::HeaderClick::Shift : ui::HeaderClick::Plain); + } + }); + // A rectangle of cells the user selected, by its corners' view rows and visible positions. + relay().on(QStringLiteral("cellSelect"), [this](QVariant const& payload) { + QVariantMap const map = payload.toMap(); + qlonglong const anchorRow = map.value(QStringLiteral("anchorRow")).toLongLong(); + qlonglong const anchorPosition = map.value(QStringLiteral("anchorPosition")).toLongLong(); + qlonglong const focusRow = map.value(QStringLiteral("focusRow")).toLongLong(); + qlonglong const focusPosition = map.value(QStringLiteral("focusPosition")).toLongLong(); + if (auto const handler = _onCellSelect; + handler && anchorRow >= 0 && anchorPosition >= 0 && focusRow >= 0 && focusPosition >= 0) { + handler(static_cast(anchorRow), static_cast(anchorPosition), + static_cast(focusRow), static_cast(focusPosition)); + } + }); + // A menu asked for by its column, -1 for the table's: its entries are read now and shown under its place. + relay().on(QStringLiteral("menu"), [this](QVariant const& payload) { + qlonglong const column = payload.toLongLong(); + if (!_menu || item() == nullptr) { + return; + } + auto const entries = _menu; + std::optional const which = + column >= 0 ? std::optional{static_cast(column)} : std::nullopt; + QVariantList const shown = menuEntries(entries(which)); + if (item() != nullptr && !shown.isEmpty()) { + QMetaObject::invokeMethod(item(), "showMenu", Qt::DirectConnection, Q_ARG(QVariant, column), + Q_ARG(QVariant, shown)); + } + }); + relay().on(QStringLiteral("menuChoose"), [this](QVariant const& payload) { + QVariantMap const map = payload.toMap(); + qlonglong const column = map.value(QStringLiteral("column")).toLongLong(); + std::vector path; + for (QVariant const& index : map.value(QStringLiteral("path")).toList()) { + if (index.toLongLong() < 0) { + return; + } + path.push_back(static_cast(index.toLongLong())); + } + if (column == kCellMenuColumn) { // A copy: the handler may destroy this table. - auto const handler = _onSort; + if (auto const handler = _cellChosen; handler && _cellMenuAt) { + auto const [key, index] = *_cellMenuAt; + handler(key, index, path); + } + return; + } + if (auto const handler = _onMenu) { + handler(column >= 0 ? std::optional{static_cast(column)} : std::nullopt, + std::move(path)); + } + }); + // A key the table leaves, with a cell focused, that is one of the entries' chords: the focused cell's first + // enabled entry without a submenu whose chord it is runs, as if chosen from its menu. + relay().answer(QStringLiteral("cellKey"), [this](QVariant const& payload) { + QVariantList const pressed = payload.toList(); + if (pressed.size() != 2 || !_cellMenu || !_cellChosen || item() == nullptr || !reachable()) { + return false; + } + int const key = pressed.at(0).toInt(); + auto const modifiers = Qt::KeyboardModifiers::fromInt(pressed.at(1).toUInt()); + // A key that is none of the entries' chords asks for nothing. + if (std::ranges::none_of(_cellMenuKeys, + [&](std::string const& chord) { return chordMatches(chord, key, modifiers); })) { + return false; + } + qlonglong const viewRow = item()->property("focusedRowIndex").toLongLong(); + int const column = item()->property("focusedColumnIndex").toInt(); + std::optional rowKey; + for (ItemBase const* const child : children()) { + auto const* const row = dynamic_cast(child); + if (row != nullptr && row->item() != nullptr && row->key() && + row->item()->property("viewRow").toLongLong() == viewRow) { + rowKey = row->key(); + } + } + if (!rowKey || column < 0) { + return false; + } + auto const entries = _cellMenu; + auto const chosen = _cellChosen; + std::vector path; + std::function const&)> const find = + [&](std::vector const& level) { + for (std::size_t at = 0; at < level.size(); ++at) { + ui::MenuEntry const& entry = level.at(at); + if (entry.separator || entry.heading || !entry.enabled) { + continue; + } + path.push_back(at); + if (entry.items.empty() ? !entry.keys.empty() && chordMatches(entry.keys, key, modifiers) + : find(entry.items)) { + return true; + } + path.pop_back(); + } + return false; + }; + if (!find(entries(*rowKey, static_cast(column)))) { + return false; + } + chosen(*rowKey, static_cast(column), path); + return true; + }); + relay().on(QStringLiteral("columnMove"), [this](QVariant const& payload) { + QVariantMap const map = payload.toMap(); + qlonglong const column = map.value(QStringLiteral("column")).toLongLong(); + qlonglong const position = map.value(QStringLiteral("position")).toLongLong(); + if (auto const handler = _onColumnMove; handler && column >= 0 && position >= 0) { + handler(static_cast(column), static_cast(position)); + } + }); + // A header's width in pixels, or none for a double click on the edge. The header holds the column's content and + // its padding on both sides, which a width in units does not count (the mount adds it back), so the padding is + // taken off before the pixels become units. + relay().on(QStringLiteral("columnResize"), [this](QVariant const& payload) { + QVariantMap const map = payload.toMap(); + qlonglong const column = map.value(QStringLiteral("column")).toLongLong(); + auto const handler = _onColumnResize; + if (!handler || column < 0) { + return; + } + std::optional units; + if (QVariant const width = map.value(QStringLiteral("width")); width.isValid() && !width.isNull()) { + double const unit = read("measureUnit").toDouble(); + double const content = width.toDouble() - read("measurePadding").toDouble(); + units = unit > 0 ? std::max(1, static_cast(std::lround(content / unit))) : 1; + } + handler(static_cast(column), units); + }); + relay().on(QStringLiteral("filter"), [this](QVariant const& payload) { + if (auto const handler = _onFilter; handler && payload.toLongLong() >= 0) { + handler(static_cast(payload.toLongLong())); + } + }); + relay().on(QStringLiteral("groupFilter"), [this](QVariant const& payload) { + if (auto const handler = _onGroupFilter; handler && payload.toLongLong() >= 0) { handler(static_cast(payload.toLongLong())); } }); + relay().on(QStringLiteral("copy"), [this](QVariant const&) { + if (auto const handler = _onCopy) { + handler(); + } + }); } void TableImpl::setColumns(std::vector const& columns) { QVariantList list; for (ui::TableColumn const& column : columns) { - list.append(QVariantMap{{QStringLiteral("label"), toQString(column.label)}, - {QStringLiteral("kind"), static_cast(column.width.kind)}, - {QStringLiteral("amount"), column.width.amount}, - {QStringLiteral("role"), static_cast(column.role)}, - {QStringLiteral("wrap"), column.wrap}, - {QStringLiteral("shrink"), column.shrink}, - {QStringLiteral("align"), static_cast(column.align)}, - {QStringLiteral("valign"), static_cast(column.valign)}, - {QStringLiteral("sortable"), column.sortable}}); + list.append(QVariantMap{ + {QStringLiteral("label"), toQString(column.label)}, + {QStringLiteral("unit"), toQString(column.unit)}, + {QStringLiteral("accessibleName"), toQString(ui::headerAccessibleName(column.label, column.unit))}, + {QStringLiteral("kind"), static_cast(column.width.kind)}, + {QStringLiteral("amount"), column.width.amount}, + {QStringLiteral("role"), static_cast(column.role)}, + {QStringLiteral("wrap"), column.wrap}, + {QStringLiteral("shrink"), column.shrink}, + {QStringLiteral("align"), static_cast(column.align)}, + {QStringLiteral("valign"), static_cast(column.valign)}, + {QStringLiteral("sortable"), column.sortable}, + {QStringLiteral("filterable"), column.filterable}}); } write("columns", list); } @@ -78,6 +289,17 @@ void TableImpl::setRowTone(ui::Widget& row, std::optional tone) { tableRow->write("tone", tone ? static_cast(*tone) : -1); } +void TableImpl::setRowMarks(ui::Widget& row, ui::RowMarks const& marks) { + auto const* const tableRow = dynamic_cast(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setRowMarks of a widget that is not this table's row"}; + } + tableRow->write("busy", marks.busy); + tableRow->write("locked", marks.locked); + tableRow->write("unmatched", marks.unmatched); + tableRow->write("marksTooltip", toQString(marks.tooltip)); +} + void TableImpl::setRowHeading(ui::Widget& row) { auto const* const tableRow = dynamic_cast(&row); if (tableRow == nullptr || tableRow->container() != this) { @@ -87,6 +309,18 @@ void TableImpl::setRowHeading(ui::Widget& row) { mark(); } +void TableImpl::setRowSummary(ui::Widget& row) { + auto const* const tableRow = dynamic_cast(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setRowSummary of a widget that is not this table's row"}; + } + tableRow->write("summary", true); + if (tableRow->key() && !std::ranges::contains(_summaryKeys, *tableRow->key())) { + _summaryKeys.push_back(*tableRow->key()); + } + mark(); +} + void TableImpl::setRowSpans(ui::Widget& row, std::vector const& spans) { auto const* const tableRow = dynamic_cast(&row); if (tableRow == nullptr || tableRow->container() != this) { @@ -113,10 +347,20 @@ void TableImpl::setRowLabel(ui::Widget& row, std::string_view label) { } void TableImpl::setSelection(std::vector const& keys) { + _viewExcept.reset(); _requested = keys; mark(); } +void TableImpl::setSelectionView(std::vector const& except) { + _viewExcept = except; + mark(); +} + +void TableImpl::setOnStatusEntry(std::function onStatusEntry) { + _onStatusEntry = std::move(onStatusEntry); +} + void TableImpl::setOnSelectionChange( std::function, ui::SelectionChange)> onSelectionChange) { _onSelectionChange = std::move(onSelectionChange); @@ -124,13 +368,122 @@ void TableImpl::setOnSelectionChange( void TableImpl::setOnActivate(std::function onActivate) { _onActivate = std::move(onActivate); } -// MorphTable's `sortColumn` is -1 for none. -void TableImpl::setSort(std::optional sort) { - write("sortDescending", sort && sort->direction == ui::SortDirection::Descending); - write("sortColumn", sort ? static_cast(sort->column) : -1); +// By column, as text keys: a header not in the chain has neither a mark nor a description. +void TableImpl::setSort(std::vector const& chain) { + QVariantMap marks; + QVariantMap descriptions; + for (std::size_t place = 0; place < chain.size(); ++place) { + QString const column = QString::number(chain.at(place).column); + marks.insert(column, toQString(ui::sortMarkText(chain.at(place).direction, place + 1, chain.size()))); + descriptions.insert(column, + toQString(ui::sortDescription(chain.at(place).direction, place + 1, chain.size()))); + } + write("sortMarks", marks); + write("sortDescriptions", descriptions); +} + +void TableImpl::setOnSort(std::function onSort) { _onSort = std::move(onSort); } + +void TableImpl::setMenu(std::function(std::optional)> entries, + std::function, std::vector)> onChoose) { + _menu = std::move(entries); + _onMenu = std::move(onChoose); + write("hasMenu", static_cast(_menu)); +} + +void TableImpl::setCellMenu(std::function(ui::Key const&, std::size_t)> entries, + std::function const&)> chosen) { + _cellMenu = std::move(entries); + _cellChosen = std::move(chosen); + write("hasCellMenu", static_cast(_cellMenu)); +} + +void TableImpl::openCellMenu(TableRowImpl const& row, std::size_t column) { + if (!_cellMenu || !row.key() || !row.reachable() || passive(row) || item() == nullptr) { + return; + } + ui::Key const key = *row.key(); + // The menu shows at the cell; a row not drawn as a cell (none in the column) anchors it. + QPointer anchor{row.item()}; + for (ItemBase const* const child : row.children()) { + QQuickItem* const cell = child->item(); + if (cell != nullptr && cell->isVisible() && + cell->property("measuredIndex").toLongLong() == static_cast(column)) { + anchor = cell; + } + } + // A row already selected keeps the selection, so the menu acts on every selected row. + if (_mode != ui::SelectionMode::None && !marked(row)) { + _anchor = key; + select({key}, ui::SelectionChange::Replace); + } + auto const entries = _cellMenu; + QVariantList const shown = menuEntries(entries(key, column)); + if (item() != nullptr && anchor != nullptr && !shown.isEmpty()) { + _cellMenuAt = std::pair{key, column}; + QMetaObject::invokeMethod(item(), "showCellMenu", Qt::DirectConnection, + Q_ARG(QVariant, QVariant::fromValue(anchor.data())), + Q_ARG(QVariant, shown)); + } +} + +void TableImpl::setVisibleColumns(std::vector const& visible) { + QVariantList list; + for (std::size_t const column : visible) { + list.append(static_cast(column)); + } + write("visibleColumns", list); +} + +void TableImpl::setOnColumnMove(std::function handler) { + _onColumnMove = std::move(handler); + write("movable", static_cast(_onColumnMove)); +} + +void TableImpl::setOnColumnResize(std::function)> handler) { + _onColumnResize = std::move(handler); + write("resizable", static_cast(_onColumnResize)); +} + +void TableImpl::setOnFilter(std::function handler) { _onFilter = std::move(handler); } + +void TableImpl::setFiltered(std::vector const& columns) { + QVariantMap filtered; + for (std::size_t const column : columns) { + filtered.insert(QString::number(column), true); + } + write("filteredColumns", filtered); +} + +void TableImpl::setColumnGroups(std::vector const& groups) { + QVariantList list; + for (ui::TableColumnGroup const& group : groups) { + list.append(QVariantMap{{QStringLiteral("label"), toQString(group.label)}, + {QStringLiteral("first"), static_cast(group.first)}, + {QStringLiteral("count"), static_cast(group.count)}, + {QStringLiteral("filtered"), group.filtered}}); + } + write("columnGroups", list); +} + +void TableImpl::setBands(std::vector const& runs) { + QVariantList list; + for (ui::BandRun const& run : runs) { + list.append(QVariantMap{{QStringLiteral("level"), static_cast(run.level)}, + {QStringLiteral("text"), toQString(ui::headerText(run.label, run.unit))}, + {QStringLiteral("first"), static_cast(run.first)}, + {QStringLiteral("count"), static_cast(run.count)}, + {QStringLiteral("pinned"), run.pinned}}); + } + write("bands", list); } -void TableImpl::setOnSort(std::function onSort) { _onSort = std::move(onSort); } +void TableImpl::setOnGroupFilter(std::function handler) { _onGroupFilter = std::move(handler); } + +void TableImpl::setOnCopy(std::function onCopy) { + _onCopy = std::move(onCopy); + write("copies", static_cast(_onCopy)); +} void TableImpl::setExistingKeys(std::vector const& keys) { _existingKeys = std::unordered_set{keys.begin(), keys.end()}; @@ -147,6 +500,259 @@ void TableImpl::setOnVisibleRangeChanged(std::function(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setRowIndex of a widget that is not this table's row"}; + } + tableRow->setViewRow(viewRow); + tableRow->write("viewRow", static_cast(viewRow)); + if (item() != nullptr) { + QMetaObject::invokeMethod(item(), "scheduleRows", Qt::DirectConnection); + } +} + +// The counts, the state, what stands and the message on one line, two spaces apart; the entries are buttons after +// it, the standing ones first, each with its id and label. +void TableImpl::setStatus(ui::TableStatus const& status) { + QStringList parts; + for (std::string const* const part : {&status.counts, &status.state, &status.standing, &status.message}) { + if (!part->empty()) { + parts.append(toQString(*part)); + } + } + write("statusText", parts.join(QStringLiteral(" "))); + QVariantList entries; + for (auto const* const list : {&status.standingEntries, &status.entries}) { + for (ui::StatusEntry const& entry : *list) { + entries.append(QVariantMap{{QStringLiteral("id"), toQString(entry.id)}, + {QStringLiteral("label"), toQString(entry.label)}}); + } + } + write("statusEntries", status.shown ? entries : QVariantList{}); + write("retryShown", status.shown && status.retry); + write("statusShown", status.shown); +} + +void TableImpl::setOnRetry(std::function onRetry) { _onRetry = std::move(onRetry); } + +void TableImpl::setCellLoad(ui::Widget& row, std::size_t column, ui::CellLoad load) { + auto* const tableRow = dynamic_cast(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setCellLoad of a widget that is not this table's row"}; + } + tableRow->setLoad(column, load); +} + +void TableImpl::setCellAccent(ui::Widget& row, std::size_t column, ui::CellAccent const& accent) { + auto* const tableRow = dynamic_cast(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setCellAccent of a widget that is not this table's row"}; + } + tableRow->setAccent(column, accent); +} + +void TableImpl::setColumnWindow( + std::span columns, std::span offsets, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): overrides `Table::setColumnWindow`; the declaration says how its totals are told apart + std::span widths, int totalWidth, std::size_t pinned) { + QVariantList window; + for (auto const [column, offset, width] : std::views::zip(columns, offsets, widths)) { + window.append(QVariantMap{{QStringLiteral("column"), static_cast(column)}, + {QStringLiteral("offset"), offset}, + {QStringLiteral("width"), width}}); + } + write("windowTotalWidth", totalWidth); + write("pinnedShown", static_cast(std::min(pinned, columns.size()))); + write("windowColumns", window); + write("arranged", true); +} + +void TableImpl::setOnHorizontalRange(std::function handler) { + _onHorizontalRange = std::move(handler); + write("sourceRows", true); +} + +void TableImpl::setHorizontalOffset(int scrollX) { + if (item() != nullptr) { + QMetaObject::invokeMethod(item(), "setHorizontalOffset", Qt::DirectConnection, Q_ARG(int, scrollX)); + } +} + +// The measure the table's widths are in: pixels, from the theme the table item reads. +ui::TableMeasure TableImpl::tableMeasure() const { + return ui::TableMeasure{.unit = read("measureUnit").toDouble(), + .monoUnit = read("measureMonoUnit").toDouble(), + .contentEstimate = static_cast(std::lround(12 * read("measureUnit").toDouble())), + .padding = static_cast(std::lround(read("measurePadding").toDouble())), + .shrinkFloor = static_cast(std::lround(8 * read("measureUnit").toDouble()))}; +} + +void TableImpl::setOnColumnMeasured( + std::function handler) { + _onColumnMeasured = std::move(handler); +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): overrides `Table::setFocusCell`; the declaration says how its pair is told apart +void TableImpl::setFocusCell(std::size_t viewRow, std::size_t column) { + write("focusedRowIndex", static_cast(viewRow)); + write("focusedColumnIndex", static_cast(column)); + if (item() != nullptr) { + QMetaObject::invokeMethod(item(), "showFocusCell", Qt::DirectConnection); + } +} + +void TableImpl::setOnFocusMove(std::function handler) { _onFocusMove = std::move(handler); } + +void TableImpl::setOnText(std::function onText) { + _onText = std::move(onText); + write("takesText", static_cast(_onText)); +} + +void TableImpl::setOnCellClick(std::function onClick) { + _onCellClick = std::move(onClick); + write("reportsCellClicks", static_cast(_onCellClick)); +} + +void TableImpl::setOnFocusOut(std::function onFocusOut) { + _onFocusOut = std::move(onFocusOut); + write("reportsFocusOut", static_cast(_onFocusOut)); +} + +// The editor is placed as a cell of its column is, over the cell, which is covered while it is open; the row's +// `editorColumn` says which column and `editorItem` the editor, whose own popups the table's focus watch counts as +// inside the table. An editor that holds the focus when it closes gives it back to the table, so the next key reaches +// the table. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): places the editor over its cell and hands focus back on close; the open and close paths share the row's editor state +void TableImpl::setCellEditor(ui::Widget& row, std::size_t column, ui::Widget* editor) { + auto const* const tableRow = dynamic_cast(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setCellEditor of a widget that is not this table's row"}; + } + ItemBase* const shown = editor != nullptr ? baseOf(*editor) : nullptr; + if (shown == nullptr) { + QPointer const closing = _editors.take(tableRow); + QQuickWindow const* const window = item() != nullptr ? item()->window() : nullptr; + bool held = false; + for (QQuickItem const* at = window != nullptr ? window->activeFocusItem() : nullptr; + at != nullptr && closing != nullptr; at = at->parentItem()) { + held = held || at == closing.data(); + } + if (held && item() != nullptr) { + item()->forceActiveFocus(Qt::OtherFocusReason); + } + } else if (shown->item() != nullptr) { + _editors.insert(tableRow, QPointer{shown->item()}); + } + for (ItemBase* const cell : tableRow->children()) { + if (cell == shown || cell->item() == nullptr) { + continue; + } + if (cell->item()->property("measuredIndex").toInt() == static_cast(column)) { + cell->cover(shown != nullptr); + } + } + if (shown != nullptr) { + shown->offer("measuredIndex", static_cast(column)); + shown->cover(false); + } + tableRow->write("editorColumn", shown != nullptr ? static_cast(column) : -1); + tableRow->write("editorItem", QVariant::fromValue(shown != nullptr ? shown->item() : nullptr)); + if (QQuickItem* const rowItem = tableRow->item(); rowItem != nullptr) { + QMetaObject::invokeMethod(rowItem, "schedulePlace", Qt::DirectConnection); + } +} + +void TableImpl::setCellMarks(ui::Widget& row, std::size_t column, ui::CellMarks const& marks) { + auto* const tableRow = dynamic_cast(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setCellMarks of a widget that is not this table's row"}; + } + tableRow->setMarks(column, marks); +} + +void TableImpl::setRowModified(ui::Widget& row, bool modified) { + auto const* const tableRow = dynamic_cast(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setRowModified of a widget that is not this table's row"}; + } + tableRow->write("modified", modified); +} + +void TableImpl::setCellSelection(std::optional> rect) { + QVariantList shown; + if (rect) { + for (std::size_t const part : *rect) { + shown.append(static_cast(part)); + } + } + write("cellRect", shown); +} + +void TableImpl::setOnCellSelect(std::function onSelect) { + _onCellSelect = std::move(onSelect); + write("selectsCells", static_cast(_onCellSelect)); +} + +void TableImpl::cellClicked(TableRowImpl const& row, std::size_t column, bool doubleClick) const { + if (!row.viewRow() || !row.reachable() || !_onCellClick) { + return; + } + auto const handler = _onCellClick; + handler(*row.viewRow(), column, doubleClick); +} + +void TableImpl::setOnSelectRange( + std::function handler) { + _onSelectRange = std::move(handler); +} + +// -1 for a row count that is a lower bound or not known yet. +void TableImpl::setCounts(std::optional rows, std::size_t columns) { + write("accessibleRowCount", static_cast(rows.value_or(-1))); + write("accessibleColumnCount", static_cast(columns)); +} + +void TableImpl::scrollToRow(std::size_t viewRow) { + if (item() != nullptr) { + QMetaObject::invokeMethod(item(), "scrollToRow", Qt::DirectConnection, + Q_ARG(QVariant, QVariant{static_cast(viewRow)})); + } +} + +// A cell with no column is pooled: hidden, as a covered cell is, and placed nowhere. `measuredIndex` is the column +// the row places it in and the one its widths are reported for. +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): overrides `Table::setCellColumn`; the declaration says how its pair is told apart +void TableImpl::setCellColumn(ui::Widget& row, ui::Widget& cell, std::optional column) { + auto const* const tableRow = dynamic_cast(&row); + if (tableRow == nullptr || tableRow->container() != this) { + throw std::logic_error{"morph::qt_quick: setCellColumn of a widget that is not this table's row"}; + } + ItemBase* const base = baseOf(cell); + if (base == nullptr) { + return; + } + base->offer("measuredIndex", column ? static_cast(*column) : -1); + base->cover(!column.has_value()); + // A cell reports a change of its width itself, but its width may have changed before it had this column, and a + // pooled cell's content is rebound after its column is set. Its width in this column is told to the table once the + // pass is over, when the content is the row's own. + if (column && base->item() != nullptr && item() != nullptr) { + QTimer::singleShot(0, item(), + [tableRef = QPointer{item()}, cellRef = QPointer{base->item()}] { + if (tableRef != nullptr && cellRef != nullptr && cellRef->isVisible()) { + QMetaObject::invokeMethod(tableRef, "reportCell", Qt::DirectConnection, + Q_ARG(int, cellRef->property("measuredIndex").toInt()), + Q_ARG(QVariant, QVariant::fromValue(cellRef.data()))); + } + }); + } + // Once per row and event loop turn, however many of its cells a pass places. + if (QQuickItem* const rowItem = tableRow->item(); rowItem != nullptr) { + QMetaObject::invokeMethod(rowItem, "schedulePlace", Qt::DirectConnection); + } +} + void TableImpl::scrolled(std::size_t first, std::size_t count) const { if (_onVisibleRangeChanged) { _onVisibleRangeChanged(first, count); @@ -176,6 +782,7 @@ void TableImpl::moved() { void TableImpl::releasing(ItemBase& child) noexcept { stripe(&child); _spans.erase(&child); + _editors.remove(dynamic_cast(&child)); planSpans(&child); // `child`'s item is still parented into the QML body (ItemBase's own destructor calls release() -- which calls // this -- before it hides and reparents the item away), so a QML-side rescan of body.children would still see @@ -192,6 +799,7 @@ void TableImpl::releasing(ItemBase& child) noexcept { // Coverage follows the rows' order, so it is worked out here from the rows as they stand, whenever a row comes, goes, // moves or is told its spans, and never from a span alone. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): works out coverage in one pass in the rows' order: the spans carried from earlier rows decide what each next row covers void TableImpl::planSpans(ItemBase const* leaving) { if (_spans.empty() && !_planned) { return; @@ -217,9 +825,11 @@ void TableImpl::planSpans(ItemBase const* leaving) { std::size_t const cells = rows.at(index)->children().size(); coveredUntil.resize(std::max(coveredUntil.size(), cells), 0); for (ui::RowSpan const& span : found->second) { - if (span.column >= cells || span.rows < 2 || coveredUntil.at(span.column) > index) { + if (span.column >= cells || span.rows == 0 || coveredUntil.at(span.column) > index) { continue; } + // The columns it covers, its own and the next ones, clipped at the row's last cell. + std::size_t const wide = std::max(1, std::min(span.columns, cells - span.column)); std::size_t last = std::min(index + span.rows, rows.size()) - 1; for (std::size_t between = index + 1; between <= last; ++between) { if (heading(*rows.at(between))) { @@ -227,16 +837,21 @@ void TableImpl::planSpans(ItemBase const* leaving) { break; } } - if (last == index) { + if (last == index && wide == 1) { continue; } - coveredUntil.at(span.column) = last + 1; + for (std::size_t column = span.column; column < span.column + wide; ++column) { + coveredUntil.at(column) = last + 1; + } plans.at(index).append(QVariantMap{{QStringLiteral("column"), static_cast(span.column)}, - {QStringLiteral("rows"), static_cast(last - index + 1)}}); - for (std::size_t between = index + 1; between <= last; ++between) { - if (span.column < covered.at(between).size()) { - covered.at(between).at(span.column) = true; - coveredColumns.at(between).append(static_cast(span.column)); + {QStringLiteral("rows"), static_cast(last - index + 1)}, + {QStringLiteral("columns"), static_cast(wide)}}); + for (std::size_t between = index; between <= last; ++between) { + for (std::size_t column = span.column; column < span.column + wide; ++column) { + if ((between != index || column != span.column) && column < covered.at(between).size()) { + covered.at(between).at(column) = true; + coveredColumns.at(between).append(static_cast(column)); + } } } } @@ -264,6 +879,10 @@ void TableImpl::planSpans(ItemBase const* leaving) { } void TableImpl::stripe(ItemBase const* leaving) const noexcept { + // Over a source a row is striped by its view row (`MorphTableRow.viewRow`), not by its place among the children. + if (read("sourceRows").toBool()) { + return; + } // Every child is a row, and one being adopted is still being made, so its type is not asked. bool alternate = false; for (ItemBase const* const child : children()) { @@ -279,6 +898,8 @@ bool TableImpl::marked(ItemBase const& row) { return row.read("selected").toBool bool TableImpl::heading(ItemBase const& row) { return row.read("heading").toBool(); } +bool TableImpl::passive(ItemBase const& row) { return heading(row) || row.read("summary").toBool(); } + void TableImpl::mark() const { // Every child of a table is one of its rows; the mount makes nothing else in one. for (ItemBase const* const child : children()) { @@ -286,8 +907,9 @@ void TableImpl::mark() const { if (row == nullptr) { continue; } - bool const selected = - row->key() && !heading(*row) && std::ranges::find(_requested, *row->key()) != _requested.end(); + bool const selected = row->key() && !passive(*row) && + (_viewExcept ? !std::ranges::contains(*_viewExcept, *row->key()) + : std::ranges::find(_requested, *row->key()) != _requested.end()); row->write("selected", selected); } } @@ -313,14 +935,20 @@ std::vector TableImpl::existingSelection() const { } std::vector TableImpl::rowKeys() const { - // Below a virtualized table's threshold every row is realized, in row order. + // Below a virtualized table's threshold every row is realized, in row order. A summary row is never selected. if (!_existingOrder.empty()) { - return _existingOrder; + std::vector keys; + for (ui::Key const& key : _existingOrder) { + if (!std::ranges::contains(_summaryKeys, key)) { + keys.push_back(key); + } + } + return keys; } std::vector keys; for (ItemBase const* const child : children()) { auto const* const row = dynamic_cast(child); - if (row != nullptr && row->key() && !heading(*row)) { + if (row != nullptr && row->key() && !passive(*row)) { keys.push_back(*row->key()); } } @@ -328,7 +956,7 @@ std::vector TableImpl::rowKeys() const { } void TableImpl::tapped(TableRowImpl const& row, ui::RowClick click) { - if (_mode == ui::SelectionMode::None || !row.key() || !row.reachable() || heading(row)) { + if (_mode == ui::SelectionMode::None || !row.key() || !row.reachable() || passive(row)) { return; } ui::Key const key = *row.key(); @@ -349,6 +977,24 @@ void TableImpl::tapped(TableRowImpl const& row, ui::RowClick click) { ui::SelectionChange::Replace); return; } + // A selection of the view: the keys now marked among the rows held, the clicked one toggled. The view state + // lasts until the caller sets the selection or the view again. + if (_viewExcept) { + std::vector marked; + for (ui::Key const& held : rowKeys()) { + bool const out = std::ranges::contains(*_viewExcept, held); + if (held == key ? out : !out) { + marked.push_back(held); + } + } + _anchor = key; + if (_onSelectionChange) { + // A copy: the handler may destroy this table. + auto const handler = _onSelectionChange; + handler(std::move(marked), ui::SelectionChange::Extend); + } + return; + } // A user's change drops a requested key still waiting for its row. std::vector next = existingSelection(); if (auto const found = std::ranges::find(next, key); found != next.end()) { @@ -367,10 +1013,21 @@ void TableImpl::anchorAt(TableRowImpl const& row) { } } +void TableImpl::setOnSelectAll(std::function onSelectAll) { + _onSelectAll = std::move(onSelectAll); + write("selectAllHandled", static_cast(_onSelectAll)); +} + void TableImpl::selectAll() { if (_mode != ui::SelectionMode::Multiple) { return; } + if (_onSelectAll) { + // A copy: the handler may destroy this table. + auto const handler = _onSelectAll; + handler(); + return; + } std::vector keys = rowKeys(); std::vector const selected = existingSelection(); bool const every = std::ranges::all_of( @@ -389,7 +1046,7 @@ void TableImpl::select(std::vector next, ui::SelectionChange change) { } void TableImpl::activated(TableRowImpl const& row) const { - if (!row.key() || !row.reachable() || !_onActivate || heading(row)) { + if (!row.key() || !row.reachable() || !_onActivate || passive(row)) { return; } auto const handler = _onActivate; @@ -420,11 +1077,26 @@ TableRowImpl::TableRowImpl(Context& context, ui::ContainerWidget* parent, TableI owner->anchorAt(*this); } }); + // A right click, a long press or the menu key on one of the row's cells, by its column. + relay().on(QStringLiteral("cellMenu"), [this](QVariant const& payload) { + qlonglong const column = payload.toMap().value(QStringLiteral("column")).toLongLong(); + if (auto* const owner = dynamic_cast(container()); owner != nullptr && column >= 0) { + owner->openCellMenu(*this, static_cast(column)); + } + }); relay().on(QStringLiteral("activate"), [this](QVariant const&) { if (auto const* const owner = dynamic_cast(container())) { owner->activated(*this); } }); + // A tap on one of the row's cells, by its column: the second tap of a double tap with `double`. + relay().on(QStringLiteral("cellClick"), [this](QVariant const& payload) { + QVariantMap const map = payload.toMap(); + qlonglong const column = map.value(QStringLiteral("column")).toLongLong(); + if (auto const* const owner = dynamic_cast(container()); owner != nullptr && column >= 0) { + owner->cellClicked(*this, static_cast(column), map.value(QStringLiteral("double")).toBool()); + } + }); } void TableRowImpl::adopted(ItemBase& child) { @@ -440,7 +1112,7 @@ void TableRowImpl::adopted(ItemBase& child) { // through this widget, which may be gone while Qt still holds the item. auto const place = [row = QPointer{item()}] { if (row != nullptr) { - QMetaObject::invokeMethod(row, "place", Qt::DirectConnection); + QMetaObject::invokeMethod(row, "placeSoon", Qt::DirectConnection); } }; QObject::connect(cell, &QQuickItem::implicitWidthChanged, item(), place); @@ -456,14 +1128,17 @@ void TableRowImpl::adopted(ItemBase& child) { return; } int const columnIndex = static_cast(children().size()) - 1; - // A cell reports a change of its least or width-free natural width itself, through these. + // A cell reports a change of its least or width-free natural width itself, through these. Its column is read when + // it reports: a table over a source moves a pooled cell to another column (`TableImpl::setCellColumn`). + // A table over a source places each cell in a column of its own choosing (`setCellColumn`), whatever its place + // among the row's children, so no cell is reported for a column before it has one. child.offer("measuredBy", QVariant::fromValue(tableItem)); - child.offer("measuredIndex", columnIndex); + child.offer("measuredIndex", tableItem->property("sourceRows").toBool() ? -1 : columnIndex); QObject::connect(cell, &QQuickItem::implicitWidthChanged, item(), - [tableRef = QPointer{tableItem}, columnIndex, cellRef = QPointer{cell}] { + [tableRef = QPointer{tableItem}, cellRef = QPointer{cell}] { if (tableRef != nullptr && cellRef != nullptr && cellRef->isVisible()) { QMetaObject::invokeMethod(tableRef, "reportCell", Qt::DirectConnection, - Q_ARG(int, columnIndex), + Q_ARG(int, cellRef->property("measuredIndex").toInt()), Q_ARG(QVariant, QVariant::fromValue(cellRef.data()))); } }); @@ -471,12 +1146,70 @@ void TableRowImpl::adopted(ItemBase& child) { // today's widest cell, becoming visible may introduce a wider one. Rescans only this one column, not every // column via invalidateAllColumns: every cell in the table carries this connection, so a full-table sweep here // costs O(rows) per cell whose visibility ever changes during mount, compounding into O(rows^2) overall. - QObject::connect( - cell, &QQuickItem::visibleChanged, item(), [tableRef = QPointer{tableItem}, columnIndex] { - if (tableRef != nullptr) { - QMetaObject::invokeMethod(tableRef, "rescanColumn", Qt::DirectConnection, Q_ARG(int, columnIndex)); - } - }); + QObject::connect(cell, &QQuickItem::visibleChanged, item(), + [tableRef = QPointer{tableItem}, cellRef = QPointer{cell}] { + if (tableRef != nullptr && cellRef != nullptr) { + QMetaObject::invokeMethod(tableRef, "rescanColumn", Qt::DirectConnection, + Q_ARG(int, cellRef->property("measuredIndex").toInt())); + } + }); +} + +// A row's cells are bound one by one, each calling one of the three setters below, and each write hands the row's +// whole map to QML, which converts it to a JavaScript object: a write per cell makes a pass over a wide row cost +// the square of its columns. A cell whose entry does not change writes nothing. +namespace { + +/// Sets or clears one column's entry in a row's map. +/// @param map The map. +/// @param key The column's key. +/// @param entry The entry; an empty variant clears the column's. +/// @return Whether the map changed. +bool setEntry(QVariantMap& map, QString const& key, QVariant const& entry) { + if (!entry.isValid()) { + return map.remove(key) > 0; + } + auto const found = map.constFind(key); + if (found != map.constEnd() && *found == entry) { + return false; + } + map.insert(key, entry); + return true; +} + +} // namespace + +void TableRowImpl::setLoad(std::size_t column, ui::CellLoad load) { + if (setEntry(_loads, QString::number(column), + load == ui::CellLoad::Loaded ? QVariant{} : QVariant{static_cast(load)})) { + write("cellLoads", _loads); + } +} + +void TableRowImpl::setAccent(std::size_t column, ui::CellAccent const& accent) { + QVariant entry; + if (accent != ui::CellAccent{}) { + entry = QVariantMap{{QStringLiteral("tone"), accent.tone ? static_cast(*accent.tone) : -1}, + {QStringLiteral("tooltip"), toQString(accent.tooltip)}, + {QStringLiteral("invalid"), accent.invalid}}; + } + if (setEntry(_accents, QString::number(column), entry)) { + write("cellAccents", _accents); + } +} + +void TableRowImpl::setMarks(std::size_t column, ui::CellMarks const& marks) { + QVariant entry; + if (marks != ui::CellMarks{}) { + entry = QVariantMap{{QStringLiteral("readOnly"), marks.readOnly}, + {QStringLiteral("modified"), marks.modified}, + {QStringLiteral("error"), marks.error}, + {QStringLiteral("stale"), marks.stale}, + {QStringLiteral("muted"), marks.muted}}; + } + if (setEntry(_marks, QString::number(column), entry)) { + write("cellMarks", _marks); + } } void TableRowImpl::setGap(int gap) { static_cast(gap); } diff --git a/src/qt_quick/theme.cpp b/src/qt_quick/theme.cpp index c186ae4fd..2f6566784 100644 --- a/src/qt_quick/theme.cpp +++ b/src/qt_quick/theme.cpp @@ -33,7 +33,7 @@ namespace morph::qt_quick { namespace { /// The `Theme` property each colour token of the set sets. -constexpr std::array, 45> kColorProperties = {{ +constexpr auto kColorProperties = std::to_array>({ {"color.text", "text"}, {"color.muted", "muted"}, {"color.err", "error"}, @@ -68,6 +68,9 @@ constexpr std::array, 45> kColorPropert {"color.info.dot", "infoDot"}, {"color.table.header", "tableHeader"}, {"color.table.headerRule", "tableHeaderRule"}, + {"color.table.busy", "tableBusy"}, + {"color.table.locked", "tableLocked"}, + {"color.table.summary", "tableSummary"}, {"color.chart.1", "chart1"}, {"color.chart.2", "chart2"}, {"color.chart.3", "chart3"}, @@ -79,7 +82,21 @@ constexpr std::array, 45> kColorPropert {"color.disabled.text", "disabledText"}, {"color.disabled.bg", "disabledFill"}, {"color.disabled.border", "disabledBorder"}, -}}; +}); + +/// How many colour tokens the theme defines. +/// @return The count. +[[nodiscard]] consteval std::size_t colorTokenCount() { + std::size_t count = 0; + for (ui::ThemeTokenSpec const& token : ui::kThemeTokens) { + count += token.kind == ui::ThemeTokenKind::Color ? 1 : 0; + } + return count; +} + +// Every colour token reaches a `Theme` property: all but `color.background`, which `applyTheme` sets on its own. +static_assert(kColorProperties.size() + 1 == colorTokenCount(), + "a colour token is missing from kColorProperties, or one is listed that the theme does not define"); /// The colour tokens that have no default, with the `Theme` flag that tells whether the theme sets each. constexpr std::array, 3> kOptionalColors = {{ @@ -181,8 +198,9 @@ void setOptionalColorFlags(QObject& theme, ui::ThemeValues const& values, std::v } } -// The colours, the stale opacity, the background and the dimensions; each property that would not take its value -// is added to @p unset. +// The colours, the stale and muted opacities, the background and the dimensions; each property that would not take +// its value is added to @p unset. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): applies each token group to its property and collects the ones the property refused; the groups share the `unset` list void setPlainTokens(QObject& theme, ui::ThemeValues const& values, std::vector& unset) { for (auto const& [path, property] : kColorProperties) { auto const found = values.colors.find(path); @@ -198,6 +216,10 @@ void setPlainTokens(QObject& theme, ui::ThemeValues const& values, std::vectorsecond)) { unset.emplace_back("staleOpacity"); } + if (auto const muted = values.numbers.find("opacity.muted"); + muted != values.numbers.end() && !theme.setProperty("mutedOpacity", muted->second)) { + unset.emplace_back("mutedOpacity"); + } if (!theme.setProperty("borderDashed", dashed(values))) { unset.emplace_back("borderDashed"); } diff --git a/src/qt_quick/widget.hpp b/src/qt_quick/widget.hpp index 2e94ef610..d9f86daee 100644 --- a/src/qt_quick/widget.hpp +++ b/src/qt_quick/widget.hpp @@ -98,8 +98,9 @@ class ItemBase { void takeHover(std::function onHover) const; void takeFocus() const; - /// Hides the widget's item while a spanning cell above covers it (@p covered), or shows it again as its own - /// visibility says. The flag is kept apart from `setVisible`, so uncovering never shows a cell the document hid. + /// Hides the widget's item while its table keeps it out of view (@p covered): a spanning cell above covers it, or + /// the table pools it; or shows it again as its own visibility says. The flag is kept apart from `setVisible`, so + /// uncovering never shows a cell the document hid. void cover(bool covered); /// Whether a spanning cell covers the widget. [[nodiscard]] bool covered() const noexcept { return _covered; } diff --git a/src/table/description.cpp b/src/table/description.cpp new file mode 100644 index 000000000..cd9f30a48 --- /dev/null +++ b/src/table/description.cpp @@ -0,0 +1,1267 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- cell, column and row indices are bounded by the page's and the snapshot's own counts, checked before they are used + +namespace morph::table { + +TableDescription describe(TableDescription description) { + description.revision.clear(); + auto const json = glz::write_json(description).value_or(std::string{}); + description.revision = model::detail::hex64(model::detail::fnv1a64(json)); + return description; +} + +std::vector columnInfos(TableDescription const& description) { + std::vector out; + out.reserve(description.columns.size()); + for (auto const& column : description.columns) { + out.push_back(column.info); + } + return out; +} + +std::expected, TableError> registryOf(TableDescription const& description) { + UnitRegistryBuilder builder; + for (auto const& unit : description.units) { + if (unit.id.empty()) { + continue; + } + if (auto added = builder.add(unit); !added) { + return std::unexpected(std::move(added.error())); + } + } + return std::move(builder).build(); +} + +std::expected validateDisplay(TableDescription const& description) { + using Refused = std::unexpected; + auto const refuse = [](std::string column, std::string message) { + return Refused{TableError{ + .code = TableErrorCode::SourceContract, .column = std::move(column), .message = std::move(message)}}; + }; + auto const isCompanion = [&description](std::string_view columnId) { + auto const found = std::ranges::find(description.columns, columnId, + [](TableColumn const& column) -> auto const& { return column.info.id; }); + return found != description.columns.end() && found->info.kind == ColumnKind::Text; + }; + for (TableColumn const& column : description.columns) { + if (column.info.kind == ColumnKind::Measure && (column.display.decimals || !column.display.unit.empty())) { + return refuse(column.info.id, + "a measure column shows each cell in its own unit; it takes no `decimals` or `unit`"); + } + for (std::string const* const named : {&column.tone, &column.tooltip}) { + if (!named->empty() && !isCompanion(*named)) { + return refuse(*named, "column `" + column.info.id + "` names `" + *named + + "` as a companion; a companion is a `Text` column of the table"); + } + } + } + for (std::string const* const named : {&description.rowTone, &description.rowLock}) { + if (!named->empty() && !isCompanion(*named)) { + return refuse(*named, + "the table names `" + *named + "` as a row's companion; a companion is a `Text` column"); + } + } + return {}; +} + +std::expected checkBands(std::span bands, std::span columns) { + std::vector ids; + ids.reserve(columns.size()); + for (TableColumn const& column : columns) { + ids.push_back(column.info.id); + } + if (std::optional refused = bandRefusal(bands, ids)) { + return std::unexpected( + TableError{.code = TableErrorCode::SourceContract, .column = {}, .message = std::move(*refused)}); + } + return {}; +} + +std::vector columnsWithCompanions(TableDescription const& description, + std::span columns, + CompanionOverrides const& overrides) { + std::vector out; + auto const add = [&out](std::string const& columnId) { + if (!columnId.empty() && !std::ranges::contains(out, columnId)) { + out.push_back(columnId); + } + }; + for (std::string const& columnId : columns) { + add(columnId); + auto const found = std::ranges::find(description.columns, columnId, + [](TableColumn const& column) -> auto const& { return column.info.id; }); + if (found == description.columns.end()) { + continue; + } + if (!overrides.tone.contains(columnId)) { + add(found->tone); + } + if (!overrides.tooltip.contains(columnId)) { + add(found->tooltip); + } + } + if (!overrides.rowTone) { + add(description.rowTone); + } + add(description.rowLock); + return out; +} + +std::vector companionColumns(TableDescription const& description) { + std::set> names; + for (TableColumn const& column : description.columns) { + names.insert(column.tone); + names.insert(column.tooltip); + } + names.insert(description.rowTone); + names.insert(description.rowLock); + names.erase(std::string{}); + return {names.begin(), names.end()}; +} + +} // namespace morph::table + +namespace morph::table::detail { + +void appendInteger(std::string& out, std::int64_t value) { + std::array buffer{}; + auto const result = std::to_chars(std::to_address(buffer.begin()), std::to_address(buffer.end()), value); + out.append(buffer.data(), result.ptr); +} + +void appendJsonString(std::string& out, std::string_view text) { + static constexpr std::string_view kHex = "0123456789abcdef"; + out += '"'; + for (char const character : text) { + switch (character) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\b': + out += "\\b"; + break; + case '\f': + out += "\\f"; + break; + case '\n': + out += "\\n"; + break; + case '\r': + out += "\\r"; + break; + case '\t': + out += "\\t"; + break; + default: + if (static_cast(character) < 0x20U) { + auto const code = static_cast(character); + out += "\\u00"; + out += kHex[code >> 4U]; + out += kHex[code & 0xFU]; + } else { + out += character; + } + break; + } + } + out += '"'; +} + +void appendRational(std::string& out, math::Rational const& value) { + auto numerator = value.numerator; + auto denominator = value.denominator; + auto const scale = powerOfTen(std::min(value.decimalPlaces.value, math::kMaxDecimalPlaces)); + if (denominator > 0 && scale % denominator == 0) { + auto const factor = scale / denominator; + constexpr auto kMax = std::numeric_limits::max(); + constexpr auto kMin = std::numeric_limits::min(); + if (factor == 1 || (numerator <= kMax / factor && numerator >= kMin / factor)) { + numerator *= factor; + denominator = scale; + } + } + out += '['; + appendInteger(out, numerator); + out += ','; + appendInteger(out, denominator); + out += ']'; +} + +void appendDouble(std::string& out, double value) { + if (std::isnan(value)) { + out += "\"nan\""; + return; + } + if (std::isinf(value)) { + out += value > 0 ? "\"inf\"" : "\"-inf\""; + return; + } + auto const text = glz::write_json(value).value_or(std::string{"null"}); + out += text; + if (text.find_first_of(".eE") == std::string::npos) { + out += ".0"; + } +} + +void appendCellJson(std::string& out, Cell const& cell, std::map const& units) { + std::visit( + [&out, &units](T const& value) { + if constexpr (std::is_same_v || std::is_same_v) { + out += "null"; + } else if constexpr (std::is_same_v) { + appendInteger(out, value); + } else if constexpr (std::is_same_v) { + appendDouble(out, value); + } else if constexpr (std::is_same_v) { + appendJsonString(out, value); + } else if constexpr (std::is_same_v) { + out += value ? "true" : "false"; + } else if constexpr (std::is_same_v) { + appendRational(out, value); + } else if constexpr (std::is_same_v) { + appendRational(out, value.amount); + out.back() = ','; + if (auto const found = units.find(value.unit); found != units.end()) { + appendJsonString(out, found->second); + } else { + out += "null"; + } + out += ']'; + } else { + static_assert(std::is_same_v); + if (value.toCanonical.numerator == 1 && value.toCanonical.denominator == 1) { + appendRational(out, value.amount); + return; + } + appendRational(out, value.amount); + out.back() = ','; + appendRational(out, value.toCanonical); + out += ']'; + } + }, + cell); +} + +void CellCursor::skipSpace() noexcept { + while (_at < _text.size() && + (_text[_at] == ' ' || _text[_at] == '\t' || _text[_at] == '\n' || _text[_at] == '\r')) { + ++_at; + } +} + +bool CellCursor::eat(char character) noexcept { + skipSpace(); + if (_at < _text.size() && _text[_at] == character) { + ++_at; + return true; + } + return false; +} + +bool CellCursor::atEnd() noexcept { + skipSpace(); + return _at == _text.size(); +} + +std::string_view CellCursor::rest() noexcept { + skipSpace(); + return _text.substr(_at); +} + +std::optional CellCursor::integer() noexcept { + skipSpace(); + auto const token = numberToken(_text.substr(_at)); + if (token.empty() || token.find_first_of(".eE") != std::string_view::npos) { + return std::nullopt; + } + std::int64_t value = 0; + auto const [end, error] = std::from_chars(std::to_address(token.begin()), std::to_address(token.end()), value); + if (error != std::errc{} || end != std::to_address(token.end())) { + return std::nullopt; + } + _at += token.size(); + return value; +} + +std::string_view CellCursor::numberToken(std::string_view text) noexcept { + std::size_t position = 0; + auto const digits = [&] { + auto const from = position; + while (position < text.size() && text[position] >= '0' && text[position] <= '9') { + ++position; + } + return position > from; + }; + if (position < text.size() && text[position] == '-') { + ++position; + } + if (!digits()) { + return {}; + } + if (position < text.size() && text[position] == '.') { + ++position; + if (!digits()) { + return {}; + } + } + if (position < text.size() && (text[position] == 'e' || text[position] == 'E')) { + ++position; + if (position < text.size() && (text[position] == '+' || text[position] == '-')) { + ++position; + } + if (!digits()) { + return {}; + } + } + return text.substr(0, position); +} + +std::optional readPair(CellCursor& cursor) { + auto const numerator = cursor.integer(); + if (!numerator || !cursor.eat(',')) { + return std::nullopt; + } + auto const denominator = cursor.integer(); + if (!denominator || *denominator <= 0) { + return std::nullopt; + } + return math::Rational{math::Numerator{*numerator}, math::Denominator{*denominator}, + math::DecimalPlaces{placesOf(*denominator)}}; +} + +std::optional readExactCell(std::string_view text) { + CellCursor cursor{text}; + if (!cursor.eat('[')) { + return std::nullopt; + } + auto const amount = readPair(cursor); + if (!amount) { + return std::nullopt; + } + if (cursor.eat(']')) { + return cursor.atEnd() ? std::optional{Cell{*amount}} : std::nullopt; + } + if (!cursor.eat(',') || !cursor.eat('[')) { + return std::nullopt; + } + auto const factor = readPair(cursor); + if (!factor || !cursor.eat(']') || !cursor.eat(']') || !cursor.atEnd()) { + return std::nullopt; + } + return Cell{QuantityCell{.amount = *amount, .toCanonical = *factor}}; +} + +std::optional>> readMeasureCell(std::string_view text) { + CellCursor cursor{text}; + if (!cursor.eat('[')) { + return std::nullopt; + } + auto const amount = readPair(cursor); + if (!amount || !cursor.eat(',')) { + return std::nullopt; + } + auto unit = cursor.rest(); + auto const last = unit.find_last_not_of(" \t\n\r"); + if (last == std::string_view::npos || unit[last] != ']') { + return std::nullopt; + } + unit = unit.substr(0, last); + unit = unit.substr(0, unit.find_last_not_of(" \t\n\r") + 1); + if (unit == "null") { + return std::pair{*amount, std::optional{}}; + } + std::string unitId; + if (unit.empty() || unit.front() != '"' || glz::read(unitId, unit)) { + return std::nullopt; + } + return std::pair{*amount, std::optional{std::move(unitId)}}; +} + +std::optional nonFinite(std::string_view text) noexcept { + if (text == "nan") { + return std::numeric_limits::quiet_NaN(); + } + if (text == "inf") { + return std::numeric_limits::infinity(); + } + if (text == "-inf") { + return -std::numeric_limits::infinity(); + } + return std::nullopt; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +Cell cellFromJson(std::string_view json, std::optional kind) { + auto const first = json.find_first_not_of(" \t\n\r"); + if (first == std::string_view::npos) { + return Cell{std::string{json}}; + } + auto const text = json.substr(first, json.find_last_not_of(" \t\n\r") - first + 1); + if (text == "null") { + return Cell{}; + } + if (text == "true" || text == "false") { + return Cell{text == "true"}; + } + bool const number = kind == ColumnKind::Number; + if (text.front() == '"') { + std::string decoded; + if (glz::read(decoded, text)) { + return Cell{std::string{text}}; + } + if (number) { + if (auto const value = nonFinite(decoded)) { + return Cell{*value}; + } + } + return Cell{std::move(decoded)}; + } + if (text.front() == '[') { + if (auto cell = readExactCell(text)) { + return std::move(*cell); + } + return Cell{std::string{text}}; + } + if (CellCursor::numberToken(text).size() == text.size()) { + if (!number && text.find_first_of(".eE") == std::string_view::npos) { + std::int64_t value = 0; + auto const [end, error] = + std::from_chars(std::to_address(text.begin()), std::to_address(text.end()), value); + if (error == std::errc{} && end == std::to_address(text.end())) { + return Cell{value}; + } + } + double value = 0; + if (!glz::read(value, text) && std::isfinite(value)) { + return Cell{value}; + } + } + return Cell{std::string{text}}; +} + +void readPageRows(GenericPage& page, std::vector> const& rows) { + page.rows.clear(); + page.rows.reserve(rows.size()); + for (auto const& row : rows) { + GenericRow cells; + cells.reserve(row.size()); + for (auto const& cell : row) { + cells.push_back(cellFromJson(cell.str, std::nullopt)); + } + page.rows.push_back(std::move(cells)); + } +} + +glz::raw_json writePageRows(GenericPage const& page) { + glz::raw_json out; + out.str += '['; + for (std::size_t row = 0; row < page.rows.size(); ++row) { + out.str += row == 0 ? "[" : ",["; + auto const& cells = page.rows[row]; + for (std::size_t column = 0; column < cells.size(); ++column) { + if (column > 0) { + out.str += ','; + } + appendCellJson(out.str, cells[column], page.units); + } + out.str += ']'; + } + out.str += ']'; + return out; +} + +} // namespace morph::table::detail + +namespace morph::table { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +GenericPage writeGenericPage(PageRows const& page, DataSource const& source, std::span columns, + UnitRegistry const* units) { + auto const snapshot = source.snapshot(); + auto const infos = source.columns(); + std::vector> indices; + indices.reserve(columns.size()); + for (auto const& column : columns) { + indices.push_back(detail::findColumn(infos, column)); + } + GenericPage out; + out.columns.assign(columns.begin(), columns.end()); + out.keys.reserve(page.rows.size()); + out.rows.reserve(page.rows.size()); + std::vector unloaded; + for (std::size_t at = 0; at < page.rows.size(); ++at) { + auto const row = page.rows[at]; + out.keys.push_back(snapshot->rowId(row)); + GenericRow cells; + cells.reserve(indices.size()); + unloaded.clear(); + for (auto const& index : indices) { + if (!index) { + cells.emplace_back(); + continue; + } + cells.push_back(snapshot->cell(row, *index)); + if (std::holds_alternative(cells.back())) { + unloaded.emplace_back(infos[*index].level); + } else if (auto const* const measure = std::get_if(&cells.back())) { + // NOLINTNEXTLINE(cert-dcl03-c,misc-static-assert): units is known only at run time. + assert(units != nullptr && "writeGenericPage: a measure is written with a unit registry"); + if (units != nullptr && units->contains(measure->unit)) { + out.units.try_emplace(measure->unit, units->info(measure->unit).id); + } + } + } + out.rows.push_back(std::move(cells)); + if (!unloaded.empty()) { + out.unloadedRows.push_back(UnloadedRow{ + .index = static_cast(at), .levels = detail::sortedLevels(unloaded), .failed = {}}); + } + } + out.total = page.total; + out.offset = page.offset; + out.totalKind = page.totalKind; + out.undecided = page.undecided; + out.awaiting = page.awaiting; + out.failed = page.failed; + out.indices = page.indices; + out.viewRevision = page.viewRevision; + out.unmatched = page.unmatched; + return out; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +std::expected readGenericPage(std::string_view json, TableDescription const& description, + UnitRegistry const* units) { + auto const invalid = [](std::string message) { + return std::unexpected( + TableError{.code = TableErrorCode::InvalidValue, .column = {}, .message = std::move(message)}); + }; + GenericPage page; + if (glz::read(page, json)) { + return invalid("not a generic page"); + } + std::vector kinds; + kinds.reserve(page.columns.size()); + for (auto const& columnId : page.columns) { + auto const found = std::ranges::find(description.columns, columnId, + [](TableColumn const& column) -> auto const& { return column.info.id; }); + if (found == description.columns.end()) { + return std::unexpected(detail::unknownColumn(columnId)); + } + kinds.push_back(found->info.kind); + } + if (page.keys.size() != page.rows.size()) { + return invalid("a page of " + std::to_string(page.keys.size()) + " keys and " + + std::to_string(page.rows.size()) + " rows"); + } + for (std::size_t row = 0; row < page.rows.size(); ++row) { + if (page.rows[row].size() != kinds.size()) { + return invalid("row " + std::to_string(row) + " has " + std::to_string(page.rows[row].size()) + + " cells under " + std::to_string(kinds.size()) + " columns"); + } + } + // A window looks a row's levels up by binary search and places a keyed row by its index, so both lists are + // checked against the rows here rather than trusted by every reader after. + auto const rowCount = static_cast(page.rows.size()); + std::int64_t previous = -1; + for (auto const& unloaded : page.unloadedRows) { + if (unloaded.index <= previous || unloaded.index >= rowCount) { + return invalid("an unloaded row at " + std::to_string(unloaded.index) + " in a page of " + + std::to_string(rowCount) + " rows, or out of order"); + } + previous = unloaded.index; + } + if (!page.indices.empty() && page.indices.size() != page.rows.size()) { + return invalid("a page of " + std::to_string(page.indices.size()) + " indices and " + + std::to_string(page.rows.size()) + " rows"); + } + if (std::ranges::any_of(page.indices, [](std::int64_t index) { return index < 0; })) { + return invalid("a negative view row in indices"); + } + // The rows were read with no kind: a measure's array is text until its column is known to be `Measure`. + std::shared_ptr built; + for (std::size_t column = 0; column < kinds.size(); ++column) { + if (kinds[column] != ColumnKind::Measure) { + continue; + } + if (units == nullptr) { + auto registry = registryOf(description); + if (!registry) { + return std::unexpected(std::move(registry.error())); + } + built = std::move(*registry); + units = built.get(); + } + for (auto& cells : page.rows) { + auto& cell = cells[column]; + auto const* const text = std::get_if(&cell); + auto const measure = + text != nullptr && text->starts_with('[') ? detail::readMeasureCell(*text) : std::nullopt; + if (!measure) { + continue; + } + auto const unit = measure->second ? units->find(*measure->second) : std::nullopt; + if (unit) { + page.units.try_emplace(*unit, *measure->second); + } + cell = Measure{.amount = measure->first, .unit = unit.value_or(kUnknownUnit)}; + } + } + // Only a `Number` column reads differently besides, taking an integer token or a non-finite string as a double. + for (std::size_t column = 0; column < kinds.size(); ++column) { + if (kinds[column] != ColumnKind::Number) { + continue; + } + for (auto& cells : page.rows) { + auto& cell = cells[column]; + if (auto const* const integer = std::get_if(&cell)) { + cell = static_cast(*integer); + } else if (auto const* const text = std::get_if(&cell)) { + if (auto const real = detail::nonFinite(*text)) { + cell = *real; + } + } + } + } + return page; +} + +} // namespace morph::table + +namespace morph::table::detail { + +std::vector GenericWindowCells::columns() const { + std::vector out; + out.reserve(cells.size()); + for (auto const& [column, values] : cells) { + out.push_back(column); + } + return out; +} + +void GenericWindowCells::truncate(std::size_t count) { + for (auto& [column, values] : cells) { + values.resize(std::min(count, values.size())); + } +} + +} // namespace morph::table::detail + +namespace morph::table { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +bool PageWindow::accept(PageFetch const& fetch, GenericPage page) { + return acceptReply( + fetch, replyOf(page), + [this, &page](detail::GenericWindowCells& content, detail::WindowFetchKind kind, std::size_t take) { + if (kind == detail::WindowFetchKind::Whole) { + content.cells.clear(); + } + if (kind == detail::WindowFetchKind::Rest) { + std::erase_if(content.cells, [&page](auto const& entry) { + return std::ranges::find(page.columns, entry.first) == page.columns.end(); + }); + } + // Each reply column's target, found once; the rows are then read in order, row by + // row, so the reply's cells are visited where they lie. + std::vector*> targets(page.columns.size(), nullptr); + for (std::size_t column = 0; column < page.columns.size(); ++column) { + auto const& columnId = page.columns[column]; + if (kind == detail::WindowFetchKind::Rest && !content.holds(columnId)) { + continue; + } + auto& values = content.cells[columnId]; + if (kind != detail::WindowFetchKind::Rest) { + values.clear(); + } + values.reserve(values.size() + take); + targets[column] = &values; + } + for (std::size_t row = 0; row < take; ++row) { + auto& cells = page.rows[row]; + for (std::size_t column = 0; column < targets.size(); ++column) { + if (targets[column] != nullptr) { + targets[column]->push_back(column < cells.size() ? std::move(cells[column]) : Cell{}); + } + } + } + limitColumns(content); + }); +} + +std::vector PageWindow::patch(RowsFetch const& fetch, GenericPage reply) { + // The columns a page holds that the reply lacks go once per page, not once per row. + Core::Held const* trimmed = nullptr; + return patchRows( + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the page's position, then the reply's row it is taken from. + fetch, replyOf(reply), [&reply, &trimmed](Core::Held& page, std::size_t position, std::size_t from) { + if (trimmed != &page) { + std::erase_if(page.content.cells, [&reply](auto const& entry) { + return std::ranges::find(reply.columns, entry.first) == reply.columns.end(); + }); + trimmed = &page; + } + auto& cells = reply.rows[from]; + for (std::size_t column = 0; column < reply.columns.size() && column < cells.size(); ++column) { + auto const found = page.content.cells.find(reply.columns[column]); + if (found != page.content.cells.end() && position < found->second.size()) { + found->second[position] = std::move(cells[column]); + } + } + }); +} + +RowId const* PageWindow::key(std::int64_t index) const { + auto const* const page = heldAt(index); + return page == nullptr ? nullptr : &page->keys[static_cast(index % pageSize())]; +} + +Cell const* PageWindow::cell(std::int64_t index, std::string_view column) const { + auto const* const page = heldAt(index); + if (page == nullptr) { + return nullptr; + } + auto const found = page->content.cells.find(column); + auto const position = static_cast(index % pageSize()); + return found == page->content.cells.end() || position >= found->second.size() ? nullptr : &found->second[position]; +} + +detail::WindowReply PageWindow::replyOf(GenericPage const& page) { + return detail::WindowReply{.keys = page.keys, + .rows = page.rows.size(), + .unloadedRows = page.unloadedRows, + .total = page.total, + .totalKind = page.totalKind, + .undecided = page.undecided, + .awaiting = page.awaiting, + .failed = page.failed, + .indices = page.indices}; +} + +void PageWindow::limitColumns(detail::GenericWindowCells& content) const { + if (content.cells.size() <= maxColumns()) { + return; + } + std::vector> candidates; + candidates.reserve(content.cells.size()); + for (auto const& [column, values] : content.cells) { + if (!shownNow(column)) { + candidates.emplace_back(namedAt(column), column); + } + } + std::ranges::sort(candidates); + auto excess = content.cells.size() - maxColumns(); + std::vector dropped; + for (auto const& candidate : candidates) { + if (excess == 0) { + break; + } + dropped.emplace_back(candidate.second); + --excess; + } + for (auto const& column : dropped) { + content.cells.erase(column); + } +} + +std::expected servedDescription(ServedTable const& served) { + if (served.limits.maxSortKeys == 0 || served.limits.maxSortKeys > kMaxSortKeysBound) { + return std::unexpected(TableError{.code = TableErrorCode::SourceContract, + .column = {}, + .message = "a table's `limits.maxSortKeys` is 1 to 32"}); + } + TableDescription description = served.description; + description.capabilities.maxSortKeys = static_cast(served.limits.maxSortKeys); + auto const measure = std::ranges::find(description.columns, ColumnKind::Measure, + [](TableColumn const& column) { return column.info.kind; }); + if (measure != description.columns.end()) { + if (served.services.units == nullptr) { + return std::unexpected(TableError{.code = TableErrorCode::SourceContract, + .column = measure->info.id, + .message = "a table with measures needs a unit registry"}); + } + if (description.units.empty()) { + description.units = unitsFor(*served.services.units, columnInfos(description)); + } + } + return describe(std::move(description)); +} + +} // namespace morph::table + +namespace morph::table::detail { + +MORPH_PROCESS_UNIQUE std::uint64_t PinnedSource::nextPin() noexcept { + static std::atomic pins{0}; + return pins.fetch_add(1) + 1; +} + +std::shared_ptr ScopedSource::snapshot() const { + auto base = _source->snapshot(); + std::scoped_lock const lock{_mutex}; + if (base != _base || _scoped == nullptr) { + std::vector rows; + rows.reserve(std::min(_keys.size(), base->rowCount())); + for (std::size_t row = 0; row < base->rowCount(); ++row) { + if (_keys.contains(base->rowId(row))) { + rows.push_back(row); + } + } + _scoped = std::make_shared(base, std::move(rows)); + _base = std::move(base); + } + return _scoped; +} + +std::optional viewQueryOf(TableQuery const& validated) { + auto sort = glz::write_json(validated.sort); + auto filters = glz::write_json(validated.filters); + if (!sort || !filters) { + return std::nullopt; + } + return *sort + "\n" + *filters; +} + +ServedTable pinned(ServedTable served) { + if (served.source != nullptr) { + auto const columns = served.source->columns(); + auto const groups = served.source->groups(); + served.source = std::make_shared( + served.source->snapshot(), std::vector(columns.begin(), columns.end()), + std::vector(groups.begin(), groups.end())); + } + return served; +} + +std::string orderColumnOf(TableQuery const& query, std::span columns, std::string_view level, + Services const& services, std::span groups) { + for (auto const& key : query.sort) { + if (auto const index = findColumn(columns, key.column); index && columns[*index].level == level) { + return key.column; + } + } + if (!query.filters.empty()) { + if (auto const filter = compileFilterGuarded(query.filters, columns, services, groups)) { + for (auto const column : filter->columnsUsed()) { + if (columns[column].level == level) { + return columns[column].id; + } + } + } + } + if (query.distinct) { + auto const listed = + query.distinct->group.empty() + ? std::span{&query.distinct->column, 1} + : detail::groupColumns(groups, query.distinct->group).value_or(std::span{}); + for (auto const& columnId : listed) { + if (auto const index = findColumn(columns, columnId); index && columns[*index].level == level) { + return columnId; + } + } + } + return {}; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +std::expected answerQuery(ServedTable const& served, TableQuery const& query, + AnswerContext const& context) { + if (auto shown = validateDisplay(served.description); !shown) { + return std::unexpected(std::move(shown.error())); + } + if (context.rowScoped && served.scope.empty()) { + return std::unexpected(TableError{ + .code = TableErrorCode::SourceContract, .column = {}, .message = "a row-scoped table needs a scope"}); + } + if (served.source == nullptr) { + return std::unexpected( + TableError{.code = TableErrorCode::Unavailable, .column = {}, .message = "the table serves no source"}); + } + auto const described = servedDescription(served); + if (!described) { + return std::unexpected(described.error()); + } + if (query.keys && !served.description.capabilities.keys) { + return std::unexpected(TableError{ + .code = TableErrorCode::Unavailable, .column = {}, .message = "this table answers no keyed query"}); + } + if (query.distinct && !served.description.capabilities.distinct) { + return std::unexpected(TableError{ + .code = TableErrorCode::Unavailable, .column = {}, .message = "this table answers no distinct request"}); + } + auto const infos = columnInfos(served.description); + auto const groups = served.source->groups(); + if (auto error = detail::checkGroups(served.source->columns(), groups)) { + return std::unexpected(std::move(*error)); + } + auto checked = validate(query, infos, served.limits, served.mayRead, groups); + if (!checked) { + return std::unexpected(std::move(checked.error())); + } + auto const levelOf = [&served](std::string_view level) -> std::shared_ptr { + for (auto const& source : served.levels) { + if (source != nullptr && source->level() == level) { + return source; + } + } + return nullptr; + }; + auto const sourceColumns = served.source->columns(); + for (auto const& info : infos) { + auto const level = info.level.empty() ? nullptr : levelOf(info.level); + bool const known = info.level.empty() ? findColumn(sourceColumns, info.id).has_value() + : level == nullptr || findColumn(level->columns(), info.id).has_value(); + if (!known) { + return std::unexpected(TableError{.code = TableErrorCode::UnknownColumn, + .column = info.id, + .message = "the table's source has no column " + info.id}); + } + } + if (checked->distinct) { + // The listed column's level is an order level: the values list reads it for every candidate row. + auto const needed = levelsNeeded(*checked, infos, served.mayRead, served.services.forTask(), groups); + std::vector inputs; + for (auto const& level : needed.order) { + if (auto source = levelOf(level)) { + auto levelSnapshot = source->snapshot(); + inputs.push_back(LevelInput{.source = std::move(source), .snapshot = std::move(levelSnapshot)}); + } + } + LeveledSource const leveled{served.source, infos, std::move(inputs)}; + auto values = distinctValues( + leveled, *checked, *checked->distinct, + ApplyOptions{.limits = served.limits, .services = served.services, .mayRead = served.mayRead}); + if (!values) { + return std::unexpected(std::move(values.error())); + } + // Every row is a candidate: the order levels are wanted for every key of the snapshot. The set is kept in + // the view cache, under a key no sort or filter writes, so that the requests over one snapshot want one + // kept set, which a level holds once and each later request repeats, as a page's view does. + auto const snapshot = leveled.snapshot(); + auto const everyRow = [&]() -> std::expected { + ViewComputation out{.view = {}, .awaiting = {}, .failed = {}, .orderKeys = {}}; + auto all = std::make_shared>(); + all->reserve(snapshot->rowCount()); + out.view.rows.reserve(snapshot->rowCount()); + for (std::size_t row = 0; row < snapshot->rowCount(); ++row) { + all->push_back(snapshot->rowId(row)); + out.view.rows.push_back(static_cast(row)); + } + out.orderKeys = std::move(all); + return out; + }; + std::shared_ptr const> keys; + if (!needed.order.empty()) { + if (context.views != nullptr && !context.record.empty()) { + auto const* const pinned = dynamic_cast(served.source.get()); + auto found = context.views->find( + ViewKey{.record = std::string{context.record}, .scope = served.scope, .query = "every row"}, + served.source->snapshot(), {}, everyRow, pinned != nullptr ? pinned->pinnedAt() : 0); + if (!found) { + return std::unexpected(std::move(found.error())); + } + keys = (*found)->orderKeys; + } else { + keys = everyRow()->orderKeys; + } + } + std::vector> leased; + for (auto const& level : needed.order) { + auto const source = levelOf(level); + if (source == nullptr) { + continue; + } + if (auto wanted = source->wantSet(keys, LevelUse::Order, query.retry); !wanted) { + // The request is refused: the levels that accepted its order use hold nothing for it. + for (auto const& accepted : leased) { + accepted->unwant(*keys); + } + auto error = std::move(wanted.error()); + error.code = TableErrorCode::Unavailable; + error.column = orderColumnOf(*checked, infos, level, served.services.forTask(), groups); + return std::unexpected(std::move(error)); + } + leased.push_back(source); + } + GenericPage page; + page.revision = described->revision; + page.distinct = std::move(*values); + return page; + } + std::vector columns; + if (checked->columns) { + columns = *checked->columns; + } else { + columns.reserve(infos.size()); + for (auto const& info : infos) { + if (!served.mayRead || served.mayRead(info.id)) { + columns.push_back(info.id); + } + } + } + // Before any view is computed: `writeGenericPage` writes a measure only through a registry. + for (auto const& column : columns) { + if (auto const columnIndex = findColumn(infos, column)) { + if (auto missing = unitsMissing(infos[*columnIndex], served.services)) { + return std::unexpected(std::move(*missing)); + } + } + } + auto const needed = levelsNeeded(*checked, infos, served.mayRead, served.services.forTask(), groups); + std::vector levels = needed.order; + levels.insert(levels.end(), needed.display.begin(), needed.display.end()); + std::ranges::sort(levels); + auto const [firstDuplicate, lastDuplicate] = std::ranges::unique(levels); + levels.erase(firstDuplicate, lastDuplicate); + std::vector inputs; + for (auto const& level : levels) { + if (auto source = levelOf(level)) { + auto levelSnapshot = source->snapshot(); + inputs.push_back(LevelInput{.source = std::move(source), .snapshot = std::move(levelSnapshot)}); + } + } + LeveledSource const leveled{served.source, infos, inputs}; + ApplyOptions const options{.limits = served.limits, .services = served.services, .mayRead = served.mayRead}; + // The keys of a view's rows and of its undecided rows: what its order levels are wanted for. + auto const keysOf = [](ComputedView const& computed, RowSnapshot const& rows) { + auto out = std::make_shared>(); + out->reserve(computed.rows.size() + computed.undecided.size()); + for (auto const row : computed.rows) { + out->push_back(rows.rowId(row)); + } + for (auto const row : computed.undecided) { + out->push_back(rows.rowId(row)); + } + return std::shared_ptr const>{std::move(out)}; + }; + auto const compute = [&]() -> std::expected { + auto view = computeView(leveled, *checked, options); + if (!view) { + return std::unexpected(std::move(view.error())); + } + ViewComputation out{.view = std::move(*view), .awaiting = {}, .failed = {}, .orderKeys = {}}; + if (!needed.order.empty()) { + out.orderKeys = keysOf(out.view, *leveled.snapshot()); + } + for (auto const& level : needed.order) { + bool unloaded = false; + bool failed = false; + auto const look = [&](std::uint32_t row) { + auto const state = leveled.state(row, level); + unloaded = unloaded || state == LevelRead::Unloaded; + failed = failed || state == LevelRead::Failed; + return unloaded && failed; + }; + if (!std::ranges::any_of(out.view.rows, look)) { + static_cast(std::ranges::any_of(out.view.undecided, look)); + } + if (unloaded) { + out.awaiting.push_back(level); + } + if (failed) { + out.failed.push_back(level); + } + } + return out; + }; + auto const snapshot = leveled.snapshot(); + std::shared_ptr entry; + auto const viewQuery = context.views != nullptr && !context.record.empty() ? viewQueryOf(*checked) : std::nullopt; + if (viewQuery) { + // The pinned source's snapshot, whose identity survives across requests, and the order levels' states. + std::vector> generations; + for (auto const& level : needed.order) { + for (auto const& input : inputs) { + if (input.source->level() == level) { + generations.emplace_back(level, input.snapshot->generation()); + } + } + } + auto const* const pinned = dynamic_cast(served.source.get()); + auto found = context.views->find( + ViewKey{.record = std::string{context.record}, .scope = served.scope, .query = *viewQuery}, + served.source->snapshot(), generations, compute, pinned != nullptr ? pinned->pinnedAt() : 0); + if (!found) { + return std::unexpected(std::move(found.error())); + } + entry = std::move(*found); + } else { + auto computed = compute(); + if (!computed) { + return std::unexpected(std::move(computed.error())); + } + entry = std::make_shared( + served.source->snapshot(), std::vector>{}, std::move(*computed)); + } + auto const* const view = &entry->view; + // A cached entry keeps the keyed lookups for the requests after this one; a request's own view is scanned once. + // The retained rows are merged into a copy for this request alone: the entry is every session's. + bool const lookups = viewQuery && (checked->keys || !checked->retain.empty()); + auto paged = lookups ? viewPage(*view, leveled, *snapshot, *checked, options, + checked->retain.empty() ? entry->viewRowOf() : std::span{}, + [&entry](RowId const& key) { return entry->sourceRowOf(key); }) + : viewPage(*view, leveled, *snapshot, *checked, options); + if (!paged) { + return std::unexpected(std::move(paged.error())); + } + auto rows = std::move(*paged); + rows.awaiting = entry->awaiting; + rows.failed = entry->failed; + auto page = writeGenericPage(rows, leveled, columns, served.services.units.get()); + page.unloadedRows.clear(); + for (std::size_t at = 0; at < rows.rows.size(); ++at) { + UnloadedRow row{.index = static_cast(at), .levels = {}, .failed = {}}; + for (auto const& level : levels) { + auto const state = leveled.state(rows.rows[at], level); + if (state != LevelRead::Loaded) { + row.levels.push_back(level); + } + if (state == LevelRead::Failed) { + row.failed.push_back(level); + } + } + if (!row.levels.empty()) { + page.unloadedRows.push_back(std::move(row)); + } + } + // A level reached below has a source, so it is in `generations`; a cached entry is found only for the same + // order levels, which its computation read, so it built the keys. + auto const& orderKeys = entry->orderKeys; + std::vector> leased; + for (auto const& level : needed.order) { + auto const source = levelOf(level); + if (source == nullptr) { + continue; + } + auto const& keys = *orderKeys; + if (auto wanted = source->wantSet(orderKeys, LevelUse::Order, query.retry); !wanted) { + // The query is refused: the levels that accepted its order use hold nothing for it. + for (auto const& accepted : leased) { + accepted->unwant(keys); + } + auto error = std::move(wanted.error()); + error.code = TableErrorCode::Unavailable; + error.column = orderColumnOf(*checked, infos, level, served.services.forTask(), groups); + return std::unexpected(std::move(error)); + } + leased.push_back(source); + } + for (auto const& level : needed.display) { + if (auto const source = levelOf(level); source != nullptr && !page.keys.empty()) { + // NOLINTNEXTLINE(bugprone-unused-return-value): a display want is never refused: only an order use can exceed the cache's bound. + static_cast(source->want(page.keys, LevelUse::Display, query.retry)); + } + } + page.revision = described->revision; + return page; +} + +std::string errorCodeName(TableErrorCode code) { + auto text = glz::write_json(code).value_or(std::string{}); + if (text.size() >= 2 && text.front() == '"' && text.back() == '"') { + text = text.substr(1, text.size() - 2); + } + return text; +} + +model::ActionRefusal refusalOf(TableError const& error) { + return model::ActionRefusal{"table." + errorCodeName(error.code), + {model::RefusalArg{.name = "column", .value = error.column}}, + error.message}; +} + +TableContext callerContext() { + static session::Context const empty{}; + auto const* const current = session::current(); + return TableContext{.session = current != nullptr ? *current : empty}; +} + +void AnswerAwaiter::await_suspend(std::coroutine_handle<> awaiting) { + auto const shared = _shared; + shared->continuation = awaiting; + shared->context = ::core::async::ResumeTarget::current(); + // Nothing of this awaiter is touched after the post: the work may resume the coroutine, and free the + // awaiter with its frame, before `post` returns. + auto* const work = _work; + work->post([shared, served = std::move(_served), query = std::move(_query), context = _context] { + try { + shared->answer = answerQuery(served, query, context); + } catch (...) { + shared->error = std::current_exception(); + } + if (shared->context) { + shared->context.submit(::core::async::ParkedWork{.resume = shared->continuation, .abandon = {}}); + } else { + shared->continuation.resume(); + } + }); +} + +std::expected AnswerAwaiter::await_resume() { + if (_shared->error) { + std::rethrow_exception(_shared->error); + } + return std::move(_shared->answer); +} + +} // namespace morph::table::detail + +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) diff --git a/src/table/edits.cpp b/src/table/edits.cpp new file mode 100644 index 000000000..74c8078d7 --- /dev/null +++ b/src/table/edits.cpp @@ -0,0 +1,518 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table::detail { + +bool editFits(ColumnKind column, forms::FieldKind field) { + using forms::FieldKind; + auto const among = [field](std::initializer_list kinds) { return std::ranges::contains(kinds, field); }; + switch (column) { + case ColumnKind::Integer: + return among({FieldKind::Integer, FieldKind::Slider, FieldKind::Enum, FieldKind::Choice}); + case ColumnKind::Key: + return among({FieldKind::Integer, FieldKind::Choice}); + case ColumnKind::Decimal: + return among({FieldKind::Decimal}); + case ColumnKind::Quantity: + case ColumnKind::Measure: + return among({FieldKind::Quantity}); + case ColumnKind::Number: + return among({FieldKind::Number, FieldKind::Slider}); + case ColumnKind::Text: + return among({FieldKind::Text, FieldKind::Multiline, FieldKind::Enum, FieldKind::Choice}); + case ColumnKind::Date: + return among({FieldKind::Date, FieldKind::EpochDate}); + case ColumnKind::DateTime: + return among({FieldKind::DateTime, FieldKind::EpochDateTime}); + case ColumnKind::Bool: + return among({FieldKind::Boolean}); + case ColumnKind::Custom: + return among({FieldKind::Text, FieldKind::Enum, FieldKind::Choice}); + default: + return false; + } +} + +} // namespace morph::table::detail + +namespace morph::table { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a run of independent rules, one `if` each, in the order they are reported; splitting scatters that order. +std::expected checkEdits( + TableDescription const& description, + std::function(std::string_view action)> const& schemaOf) { + auto const refuse = [](std::string const& column, std::string message) -> std::expected { + return std::unexpected( + TableError{.code = TableErrorCode::SourceContract, .column = column, .message = std::move(message)}); + }; + for (TableColumn const& column : description.columns) { + if (!column.edit) { + continue; + } + std::string const& columnId = column.info.id; + EditInfo const& edit = *column.edit; + std::optional const schema = schemaOf ? schemaOf(edit.action) : std::nullopt; + if (!schema) { + return refuse(columnId, + "column `" + columnId + "` is edited by `" + edit.action + "`, which is not an action here"); + } + auto model = forms::FormModel::fromSchema(edit.action, *schema); + if (!model) { + return refuse(columnId, "column `" + columnId + "`'s edit action `" + edit.action + + "` has an input schema that does not read: " + model.error().message); + } + std::span const fields = model->fields(); + forms::FieldSpec const* field = nullptr; + if (edit.member.empty()) { + auto const found = std::ranges::find(fields, std::string_view{"value"}, &forms::FieldSpec::name); + field = found == fields.end() ? nullptr : &*found; + } else { + auto const values = std::ranges::find(fields, std::string_view{"values"}, &forms::FieldSpec::name); + if (values != fields.end()) { + auto const found = std::ranges::find(values->children, edit.member, &forms::FieldSpec::name); + field = found == values->children.end() ? nullptr : &*found; + } + } + if (field == nullptr) { + return refuse(columnId, edit.member.empty() ? "column `" + columnId + "`'s edit action `" + edit.action + + "` has no member `value`" + : "column `" + columnId + "`'s edit action `" + edit.action + + "` has no member `" + edit.member + "` in its `values`"); + } + // A measure is edited in its field's unit: one the table's units lack could hold none of its cells. + if (column.info.kind == ColumnKind::Measure && + !std::ranges::contains(description.units, field->unitAscii, &UnitInfo::id)) { + return refuse(columnId, "column `" + columnId + "` is a measure edited in `" + field->unitAscii + + "`, which is not one of the table's units"); + } + if (!detail::editFits(column.info.kind, field->kind)) { + return refuse(columnId, "column `" + columnId + "` cannot be edited by `" + edit.action + + "`'s field of kind `" + std::string{forms::fieldKindName(field->kind)} + "`"); + } + } + return {}; +} + +// NOLINTNEXTLINE(bugprone-exception-escape) -- a handler that throws from here terminates, as from any destructor +CellEdits::~CellEdits() { + if (_engine == nullptr) { + return; + } + std::vector rows{_ending.begin(), _ending.end()}; + for (auto const& [row, queue] : _queues) { + rows.push_back(row); + } + _queues.clear(); + _ending.clear(); + for (auto const& row : rows) { + _engine->endEdit(row); + } +} + +void CellEdits::commit(EditRequest request) { + if (unloadedInView(request)) { + _errors[request.row].insert_or_assign(request.column, "not loaded yet"); + return; + } + auto& queue = _queues[request.row]; + queue.push_back(std::move(request)); + if (queue.size() == 1) { + start(queue.front().row); + } +} + +void CellEdits::commitRow(RowEditRequest request) { + RowId const row = request.row; + std::vector> drafts; + drafts.reserve(request.cells.size()); + for (EditCell const& cell : request.cells) { + drafts.push_back(draft(row, cell.column)); + } + auto& queue = _rowQueues[row]; + queue.push_back(RowFlight{.id = ++_nextFlight, + .request = std::move(request), + .sent = false, + .discard = false, + .drafts = std::move(drafts)}); + if (queue.size() == 1) { + startRow(row); + } +} + +void CellEdits::setDraft(RowId const& row, std::string_view column, std::string text, + std::optional error) { + CellState& cell = _cells[row][std::string{column}]; + cell.draft = std::move(text); + cell.settled = false; + if (error) { + _errors[row].insert_or_assign(std::string{column}, std::move(*error)); + } else { + eraseError(row, column); + } +} + +std::optional CellEdits::draft(RowId const& row, std::string_view column) const { + CellState const* const cell = cellOf(row, column); + return cell == nullptr ? std::nullopt : cell->draft; +} + +void CellEdits::clearDraft(RowId const& row, std::string_view column) { + if (auto const found = _cells.find(row); found != _cells.end()) { + if (auto const cell = found->second.find(column); cell != found->second.end()) { + cell->second.draft.reset(); + cell->second.settled = false; + if (!cell->second.modified) { + found->second.erase(cell); + } + } + if (found->second.empty()) { + _cells.erase(found); + } + } + eraseError(row, column); +} + +bool CellEdits::modified(RowId const& row, std::string_view column) const { + CellState const* const cell = cellOf(row, column); + return cell != nullptr && cell->modified; +} + +bool CellEdits::rowEdited(RowId const& row) const { + auto const found = _cells.find(row); + return found != _cells.end() && std::ranges::any_of(found->second, [](auto const& entry) { + return entry.second.modified || entry.second.draft.has_value(); + }); +} + +void CellEdits::rowFetched(RowId const& row) { + auto const found = _cells.find(row); + if (found == _cells.end()) { + return; + } + for (auto cell = found->second.begin(); cell != found->second.end();) { + if (!cell->second.modified || stale(row, cell->first)) { + ++cell; + continue; + } + cell->second.modified = false; + if (cell->second.settled) { + cell->second.draft.reset(); + cell->second.settled = false; + } + cell = cell->second.draft ? std::next(cell) : found->second.erase(cell); + } + if (found->second.empty()) { + _cells.erase(found); + } +} + +void CellEdits::rowAbsent(RowId const& row) { + _cells.erase(row); + _errors.erase(row); + auto const found = _rowQueues.find(row); + if (found == _rowQueues.end()) { + return; + } + std::erase_if(found->second, [](RowFlight const& flight) { return !flight.sent; }); + for (RowFlight& flight : found->second) { + flight.discard = true; + } + if (found->second.empty()) { + _rowQueues.erase(found); + } +} + +void CellEdits::moveRow(RowId const& from, RowId const& destination) { + if (from == destination) { + return; + } + if (auto const found = _cells.find(from); found != _cells.end()) { + auto moved = std::move(found->second); + _cells.erase(found); + auto& target = _cells[destination]; + for (auto& [column, cell] : moved) { + target.try_emplace(column, std::move(cell)); + } + } + if (auto const found = _errors.find(from); found != _errors.end()) { + auto moved = std::move(found->second); + _errors.erase(found); + auto& target = _errors[destination]; + for (auto& [column, message] : moved) { + target.try_emplace(column, std::move(message)); + } + } + if (auto const found = _rowQueues.find(from); found != _rowQueues.end()) { + auto moved = std::move(found->second); + _rowQueues.erase(found); + auto& target = _rowQueues[destination]; + for (RowFlight& flight : moved) { + flight.request.row = destination; + target.push_back(std::move(flight)); + } + } +} + +void CellEdits::keepColumns(std::span columns) { + auto const gone = [columns](std::string const& column) { return !std::ranges::contains(columns, column); }; + for (auto row = _cells.begin(); row != _cells.end();) { + std::erase_if(row->second, [&gone](auto const& entry) { return gone(entry.first); }); + row = row->second.empty() ? _cells.erase(row) : std::next(row); + } + for (auto row = _errors.begin(); row != _errors.end();) { + std::erase_if(row->second, [&gone](auto const& entry) { return gone(entry.first); }); + row = row->second.empty() ? _errors.erase(row) : std::next(row); + } +} + +std::size_t CellEdits::errorCount() const { + std::size_t out = 0; + for (auto const& [row, cells] : _errors) { + out += cells.size(); + } + return out; +} + +std::size_t CellEdits::modifiedCount() const { + std::size_t out = 0; + for (auto const& [row, cells] : _cells) { + out += static_cast( + std::ranges::count_if(cells, [](auto const& entry) { return entry.second.modified; })); + } + return out; +} + +bool CellEdits::stale(RowId const& row, std::string_view column) const { + if (auto const found = _queues.find(row); + found != _queues.end() && + std::ranges::any_of(found->second, [&](EditRequest const& request) { return request.column == column; })) { + return true; + } + auto const flights = _rowQueues.find(row); + return flights != _rowQueues.end() && std::ranges::any_of(flights->second, [&](RowFlight const& flight) { + return !flight.discard && std::ranges::any_of(flight.request.cells, [&](EditCell const& cell) { + return cell.column == column; + }); + }); +} + +std::optional CellEdits::error(RowId const& row, std::string_view column) const { + auto const found = _errors.find(row); + if (found == _errors.end()) { + return std::nullopt; + } + auto const cell = found->second.find(column); + return cell == found->second.end() ? std::nullopt : std::optional{cell->second}; +} + +std::size_t CellEdits::unsettled() const { + std::size_t out = 0; + for (auto const& [row, queue] : _queues) { + out += queue.size(); + } + return out; +} + +bool CellEdits::unloadedInView(EditRequest const& request) const { + if (_engine == nullptr) { + return false; + } + auto const viewRow = _engine->viewRowOfKey(request.row); + if (!viewRow) { + return false; + } + auto const columns = _engine->columns(); + auto const column = std::ranges::find(columns, request.column, &ColumnInfo::id); + if (column == columns.end()) { + return false; + } + auto const index = static_cast(column - columns.begin()); + return std::holds_alternative(_engine->cellAt(*viewRow, index)); +} + +void CellEdits::start(RowId const& row) { + if (_engine != nullptr) { + _engine->beginEdit(row); + } + // A copy: a commit that settles at once pops the queue's front, and the + // commit may still read its request afterwards. + auto const request = _queues.at(row).front(); + // The commit runs last: it may settle, commit again or destroy this object. + _commit(request, _alive.guard([this, row](std::expected, FieldError> outcome) { + settle(row, std::move(outcome)); + })); +} + +void CellEdits::settle(RowId const& row, std::expected, FieldError> outcome) { + auto const found = _queues.find(row); + if (found == _queues.end() || found->second.empty()) { + return; + } + auto const request = std::move(found->second.front()); + found->second.pop_front(); + bool const more = !found->second.empty(); + if (!more) { + _queues.erase(found); + _ending.insert(row); + } + if (outcome) { + if (auto const errors = _errors.find(row); errors != _errors.end()) { + errors->second.erase(request.column); + } + auto const alive = _alive.token(); + _patcher->patchRow(row, std::move(*outcome)); + if (alive.expired()) { + return; + } + } else { + auto const column = outcome.error().column.empty() ? request.column : outcome.error().column; + _errors[row].insert_or_assign(column, std::move(outcome.error().message)); + } + if (more) { + start(row); + return; + } + _ending.erase(row); + if (_queues.contains(row)) { + // A commit made while the row was patched started its next edit. + return; + } + if (_engine != nullptr) { + _engine->endEdit(row); + } +} + +CellEdits::CellState const* CellEdits::cellOf(RowId const& row, std::string_view column) const { + auto const found = _cells.find(row); + if (found == _cells.end()) { + return nullptr; + } + auto const cell = found->second.find(column); + return cell == found->second.end() ? nullptr : &cell->second; +} + +void CellEdits::eraseError(RowId const& row, std::string_view column) { + if (auto const found = _errors.find(row); found != _errors.end()) { + if (auto const cell = found->second.find(column); cell != found->second.end()) { + found->second.erase(cell); + } + if (found->second.empty()) { + _errors.erase(found); + } + } +} + +void CellEdits::startRow(RowId const& row) { + auto const found = _rowQueues.find(row); + if (found == _rowQueues.end() || found->second.empty() || found->second.front().sent) { + return; + } + RowFlight& front = found->second.front(); + front.sent = true; + // A copy: a commit that settles at once pops the queue's front, and the commit may still read its request. + RowEditRequest const request = front.request; + _rowCommit(request, + _alive.guard([this, flightId = front.id](std::expected> outcome) { + settleRow(flightId, std::move(outcome)); + })); +} + +void CellEdits::landErrors(RowEditRequest const& request, std::vector const& errors) { + auto const nameOf = [](EditCell const& cell) -> std::string const& { + return cell.member.empty() ? cell.column : cell.member; + }; + std::map> landed; + std::optional general; + for (FieldError const& error : errors) { + auto const named = std::ranges::find_if(request.cells, [&](EditCell const& cell) { + return !error.column.empty() && nameOf(cell) == error.column; + }); + if (named != request.cells.end()) { + landed.insert_or_assign(named->column, error.message); + } else if (!general) { + general = error.message; + } + } + for (EditCell const& cell : request.cells) { + if (auto const found = landed.find(cell.column); found != landed.end()) { + _errors[request.row].insert_or_assign(cell.column, found->second); + } else if (general) { + _errors[request.row].insert_or_assign(cell.column, *general); + } else { + eraseError(request.row, cell.column); + } + } +} + +void CellEdits::settleRow(std::uint64_t flightId, std::expected> outcome) { + auto queue = _rowQueues.begin(); + auto flight = std::deque::iterator{}; + for (; queue != _rowQueues.end(); ++queue) { + flight = std::ranges::find(queue->second, flightId, &RowFlight::id); + if (flight != queue->second.end()) { + break; + } + } + if (queue == _rowQueues.end()) { + return; + } + RowId const row = queue->first; + RowFlight const settled = std::move(*flight); + queue->second.erase(flight); + if (queue->second.empty()) { + _rowQueues.erase(queue); + } + if (!settled.discard) { + if (outcome) { + for (std::size_t at = 0; at < settled.request.cells.size(); ++at) { + EditCell const& cell = settled.request.cells.at(at); + eraseError(row, cell.column); + CellState& state = _cells[row][cell.column]; + state.modified = true; + state.settled = + state.draft.has_value() && at < settled.drafts.size() && state.draft == settled.drafts.at(at); + } + } else { + RowEditRequest landing = settled.request; + landing.row = row; + landErrors(landing, outcome.error()); + } + } + auto const alive = _alive.token(); + startRow(row); + if (alive.expired() || settled.discard || !_rowSettled) { + return; + } + std::function const heard = _rowSettled; + heard(row, !outcome.has_value()); +} + +} // namespace morph::table diff --git a/src/table/level_cache.cpp b/src/table/level_cache.cpp new file mode 100644 index 000000000..7343803b5 --- /dev/null +++ b/src/table/level_cache.cpp @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- column and level indices come from the plans built against the same lists + +namespace morph::table::detail { + +std::size_t cellsBytes(std::vector const& cells) noexcept { + std::size_t bytes = sizeof(std::vector); + for (auto const& cell : cells) { + bytes += cellBytes(cell); + } + return bytes; +} + +} // namespace morph::table::detail + +namespace morph::table { + +LeveledSource::LeveledSource(std::shared_ptr const& base, std::vector columns, + std::vector levels) + : _columns{std::move(columns)}, _groups(base->groups().begin(), base->groups().end()) { + auto const baseColumns = base->columns(); + std::vector plans; + plans.reserve(_columns.size()); + for (auto const& column : _columns) { + Plan plan; + if (column.level.empty()) { + plan.base = detail::findColumn(baseColumns, column.id); + } else { + for (std::size_t input = 0; input < levels.size(); ++input) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): input < levels.size() + if (levels[input].source == nullptr || levels[input].source->level() != column.level) { + continue; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): input < levels.size() + if (auto const place = detail::findColumn(levels[input].source->columns(), column.id)) { + plan.level = input; + plan.place = *place; + } + break; + } + } + plans.push_back(plan); + } + std::vector read; + read.reserve(levels.size()); + for (auto& input : levels) { + auto const width = input.source != nullptr ? input.source->columns().size() : 0; + read.push_back(Level{.name = input.source != nullptr ? std::string{input.source->level()} : std::string{}, + .snapshot = std::move(input.snapshot), + .width = width}); + } + _snapshot = std::make_shared(base->snapshot(), std::move(plans), std::move(read)); +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): row, then column, as DataSource::cell declares them. +Cell LeveledSource::Snapshot::cell(std::size_t row, std::size_t column) const { + auto const& plan = _plans[column]; + if (plan.base) { + return _base->cell(row, *plan.base); + } + if (!plan.level) { + return Unloaded{}; + } + auto const& level = _levels[*plan.level]; + std::vector buffer(level.width); + if (level.snapshot->read(_base->rowId(row), buffer) != LevelRead::Loaded) { + return Unloaded{}; + } + return std::move(buffer[plan.place]); +} + +void LeveledSource::Snapshot::readColumn(std::size_t column, ColumnSink& sink, std::size_t first, + std::size_t last) const { + auto const& plan = _plans[column]; + if (plan.base) { + _base->readColumn(*plan.base, sink, first, last); + return; + } + constexpr std::size_t kRun = 256; + std::vector run; + run.reserve(kRun); + std::vector buffer(plan.level ? _levels[*plan.level].width : 0); + for (std::size_t begin = first; begin < last; begin += kRun) { + auto const end = std::min(last, begin + kRun); + run.clear(); + for (std::size_t row = begin; row < end; ++row) { + if (plan.level && _levels[*plan.level].snapshot->read(_base->rowId(row), buffer) == LevelRead::Loaded) { + run.push_back(std::move(buffer[plan.place])); + } else { + run.emplace_back(Unloaded{}); + } + } + sink.cells(begin, run); + } +} + +MORPH_PROCESS_UNIQUE LevelRead LeveledSource::Snapshot::state(std::size_t row, std::string_view level) const { + for (auto const& entry : _levels) { + if (entry.name == level) { + thread_local std::vector buffer; + buffer.resize(entry.width); + return entry.snapshot->read(_base->rowId(row), buffer); + } + } + return LevelRead::Unloaded; +} + +} // namespace morph::table + +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) diff --git a/src/table/query.cpp b/src/table/query.cpp new file mode 100644 index 000000000..3e098c3bb --- /dev/null +++ b/src/table/query.cpp @@ -0,0 +1,1125 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- row and column indices are bounded by the snapshot's own counts, and the sort and filter loops index once per comparison, where at() would check every access + +namespace morph::table { + +void MembershipDigest::add(RowId const& key) noexcept { + std::uint64_t hash = 0; + if (auto const* const number = std::get_if(&key)) { + std::array text{'i', ':'}; + char const* const end = std::to_chars(std::next(text.data(), 2), std::to_address(text.end()), *number).ptr; + hash = model::detail::fnv1a64(std::string_view{text.data(), static_cast(end - text.data())}); + } else { + constexpr std::uint64_t kOffsetBasis = 14695981039346656037ULL; + constexpr std::uint64_t kPrime = 1099511628211ULL; + // FNV-1a over "s:" and the text, without building the joined string. + hash = kOffsetBasis; + auto const step = [&hash](char byte) { + hash ^= static_cast(static_cast(byte)); + hash *= kPrime; + }; + step('s'); + step(':'); + // The key is a number or a name, and the number was handled above: `get_if` rather than `get`, which + // would throw out of a `noexcept` function. + for (char const byte : *std::get_if(&key)) { + step(byte); + } + } + std::uint64_t mixed = hash + 0x9E3779B97F4A7C15ULL; + mixed = (mixed ^ (mixed >> 30U)) * 0xBF58476D1CE4E5B9ULL; + mixed = (mixed ^ (mixed >> 27U)) * 0x94D049BB133111EBULL; + mixed ^= mixed >> 31U; + ++_count; + _sum += hash; + _mix += mixed; +} + +} // namespace morph::table + +namespace morph::table::detail { + +TableError limitError(std::string column, std::string message) { + return TableError{ + .code = TableErrorCode::LimitExceeded, .column = std::move(column), .message = std::move(message)}; +} + +bool entryTooLong(FilterEntry const& entry, std::size_t max) { + auto const tooLong = [max](std::optional const& value) { return value && value->size() > max; }; + return tooLong(entry.eq) || tooLong(entry.ne) || tooLong(entry.lt) || tooLong(entry.le) || tooLong(entry.gt) || + tooLong(entry.ge) || tooLong(entry.contains) || tooLong(entry.startsWith) || tooLong(entry.endsWith) || + (entry.between && ((*entry.between)[0].size() > max || (*entry.between)[1].size() > max)) || + (entry.oneOf && + std::ranges::any_of(*entry.oneOf, [max](std::string const& member) { return member.size() > max; })); +} + +std::optional checkColumn(std::string const& columnId, std::span columns, + std::function const& mayRead) { + if (!findColumn(columns, columnId)) { + return unknownColumn(columnId); + } + if (mayRead && !mayRead(columnId)) { + return TableError{.code = TableErrorCode::ColumnNotReadable, + .column = columnId, + .message = "column " + columnId + " is not readable"}; + } + return std::nullopt; +} + +std::vector orderedColumns(std::span columns, std::vector const& asked) { + std::vector wanted(asked.begin(), asked.end()); + std::ranges::sort(wanted); + std::vector out; + out.reserve(std::min(asked.size(), columns.size())); + for (auto const& column : columns) { + if (std::ranges::binary_search(wanted, std::string_view{column.id})) { + out.push_back(column.id); + } + } + return out; +} + +std::optional SetTally::add(std::span entries, std::string const& column, + QueryLimits const& limits) { + for (auto const& entry : entries) { + if (!entry.oneOf) { + continue; + } + if (entry.oneOf->size() > limits.maxSetValues) { + return limitError(column, "too many values in one set"); + } + values += entry.oneOf->size(); + for (auto const& member : *entry.oneOf) { + bytes += member.size(); + } + } + return std::nullopt; +} + +std::optional> groupColumns(std::span groups, + std::string_view groupId) { + auto const found = std::ranges::find(groups, groupId, &ColumnGroupInfo::id); + if (found == groups.end()) { + return std::nullopt; + } + return std::span{found->columns}; +} + +TableError unknownGroup(std::string const& groupId) { + return TableError{ + .code = TableErrorCode::UnknownColumn, .column = groupId, .message = "no column group " + groupId}; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a run of independent rules, one `if` each, in the order they are reported; splitting scatters that order. +std::optional checkFilters(FilterSpec const& filters, std::span columns, + QueryLimits const& limits, std::function const& mayRead, + std::span groups) { + if (filters.columns.size() > limits.maxFilterColumns) { + return limitError({}, "too many filtered columns"); + } + SetTally sets; + for (auto const& [columnId, filter] : filters.columns) { + if (auto error = checkColumn(columnId, columns, mayRead)) { + return error; + } + if (filter.include.size() + filter.exclude.size() > limits.maxEntries) { + return limitError(columnId, "too many filter entries"); + } + if (anyTooLong(filter.include, limits.maxTextLength) || anyTooLong(filter.exclude, limits.maxTextLength)) { + return limitError(columnId, "filter value too long"); + } + if (auto error = sets.add(filter.include, columnId, limits)) { + return error; + } + if (auto error = sets.add(filter.exclude, columnId, limits)) { + return error; + } + } + if (filters.groups.size() > limits.maxGroups) { + return limitError({}, "too many filter groups"); + } + for (auto const& group : filters.groups) { + if (group.columns.size() > limits.maxGroupColumns || + group.include.size() + group.exclude.size() > limits.maxEntries) { + return limitError({}, "filter group too large"); + } + std::span named = group.columns; + if (!group.group.empty()) { + auto const declared = groupColumns(groups, group.group); + if (!declared) { + return unknownGroup(group.group); + } + named = *declared; + } + for (auto const& columnId : named) { + if (auto error = checkColumn(columnId, columns, mayRead)) { + return error; + } + } + if (anyTooLong(group.include, limits.maxTextLength) || anyTooLong(group.exclude, limits.maxTextLength)) { + return limitError({}, "filter value too long"); + } + if (auto error = sets.add(group.include, {}, limits)) { + return error; + } + if (auto error = sets.add(group.exclude, {}, limits)) { + return error; + } + } + if (sets.values > limits.maxQuerySetValues) { + return limitError({}, "too many set values in one query"); + } + if (sets.bytes > limits.maxQuerySetBytes) { + return limitError({}, "set values too long in one query"); + } + return std::nullopt; +} + +std::optional checkDistinct(DistinctRequest& request, std::span columns, + QueryLimits const& limits, + std::function const& mayRead, + std::span groups) { + auto const invalid = [](std::string message) { + return TableError{.code = TableErrorCode::InvalidSpec, .column = {}, .message = std::move(message)}; + }; + if (request.column.empty() == request.group.empty()) { + return invalid("a distinct request names a column or a group"); + } + std::span listed{&request.column, 1}; + if (!request.group.empty()) { + auto const declared = groupColumns(groups, request.group); + if (!declared) { + return unknownGroup(request.group); + } + if (declared->empty()) { + return invalid("column group " + request.group + " has no columns"); + } + listed = *declared; + } + for (auto const& columnId : listed) { + if (auto error = checkColumn(columnId, columns, mayRead)) { + return error; + } + } + if (request.search.size() > limits.maxTextLength) { + return limitError({}, "distinct search too long"); + } + if (request.offset < 0 || request.offset > limits.maxOffset) { + return limitError({}, "distinct offset out of range"); + } + if (request.limit < 0) { + return limitError({}, "distinct limit is negative"); + } + request.limit = std::min(request.limit, limits.maxLimit); + auto const& first = listed.front(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): validate() resolved every column the request names. + auto const kind = columns[*findColumn(columns, first)].kind; + if (kind == ColumnKind::Custom) { + return TableError{.code = TableErrorCode::UnsupportedOperator, + .column = first, + .message = "column " + first + " has no values to list"}; + } + if (request.bucket != DateBucket::Value && kind != ColumnKind::Date && kind != ColumnKind::DateTime) { + return invalid("a date bucket on column " + first + ", which holds no dates"); + } + return std::nullopt; +} + +} // namespace morph::table::detail + +namespace morph::table { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a run of independent rules, one `if` each, in the order they are reported; splitting scatters that order. +std::expected validate(TableQuery query, std::span columns, + QueryLimits const& limits, + std::function const& mayRead, + std::span groups) { + if (query.page.offset < 0 || query.page.offset > limits.maxOffset) { + return std::unexpected(detail::limitError({}, "page.offset out of range")); + } + if (query.page.limit < 0) { + return std::unexpected(detail::limitError({}, "page.limit is negative")); + } + query.page.limit = std::min(query.page.limit, limits.maxLimit); + if (query.sort.size() > limits.maxSortKeys) { + return std::unexpected(detail::limitError({}, "too many sort keys")); + } + for (auto const& key : query.sort) { + if (auto error = detail::checkColumn(key.column, columns, mayRead)) { + return std::unexpected(std::move(*error)); + } + } + if (auto error = detail::checkFilters(query.filters, columns, limits, mayRead, groups)) { + return std::unexpected(std::move(*error)); + } + if (query.columns) { + if (query.columns->size() > limits.maxColumns) { + return std::unexpected(detail::limitError({}, "too many columns")); + } + for (auto const& columnId : *query.columns) { + if (auto error = detail::checkColumn(columnId, columns, mayRead)) { + return std::unexpected(std::move(*error)); + } + } + query.columns = detail::orderedColumns(columns, *query.columns); + } + if (query.keys) { + if (query.page.offset != 0) { + return std::unexpected( + TableError{.code = TableErrorCode::InvalidSpec, .column = {}, .message = "a keyed query has no page"}); + } + if (query.keys->size() > limits.maxKeys) { + return std::unexpected(detail::limitError({}, "too many keys")); + } + auto const tooLong = [&limits](RowId const& key) { + auto const* const text = std::get_if(&key); + return text != nullptr && text->size() > limits.maxTextLength; + }; + if (std::ranges::any_of(*query.keys, tooLong)) { + return std::unexpected(detail::limitError({}, "key too long")); + } + } + if (query.retain.size() > limits.maxRetained) { + return std::unexpected(detail::limitError({}, "too many retained rows")); + } + if (std::ranges::any_of(query.retain, [&limits](RowId const& key) { + auto const* const text = std::get_if(&key); + return text != nullptr && text->size() > limits.maxTextLength; + })) { + return std::unexpected(detail::limitError({}, "retained key too long")); + } + if (query.distinct) { + if (query.keys) { + return std::unexpected(TableError{ + .code = TableErrorCode::InvalidSpec, .column = {}, .message = "a query is keyed or distinct"}); + } + if (auto error = detail::checkDistinct(*query.distinct, columns, limits, mayRead, groups)) { + return std::unexpected(std::move(*error)); + } + } + return query; +} + +} // namespace morph::table + +namespace morph::table::detail { + +std::vector sortedLevels(std::vector levels) { + std::ranges::sort(levels); + auto const [first, last] = std::ranges::unique(levels); + levels.erase(first, last); + return {levels.begin(), levels.end()}; +} + +} // namespace morph::table::detail + +namespace morph::table { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a run of independent rules, one `if` each, in the order they are reported; splitting scatters that order. +LevelsNeeded levelsNeeded(TableQuery const& query, std::span columns, + std::function const& mayRead, Services const& services, + std::span groups) { + // The columns that have a level, sorted by id: each column the query names is then one lookup. + std::vector> levelled; + for (auto const& column : columns) { + if (!column.level.empty()) { + levelled.emplace_back(column.id, column.level); + } + } + std::ranges::sort(levelled); + auto const levelOf = [&levelled](std::string_view columnId) { + auto const found = + std::ranges::lower_bound(levelled, columnId, {}, [](auto const& entry) { return entry.first; }); + return found != levelled.end() && found->first == columnId ? found->second : std::string_view{}; + }; + std::vector order; + std::vector display; + auto const add = [&levelOf](std::vector& out, std::string_view columnId) { + if (auto const level = levelOf(columnId); !level.empty()) { + out.push_back(level); + } + }; + for (auto const& key : query.sort) { + add(order, key.column); + } + if (!query.filters.empty()) { + if (auto const filter = compileFilterGuarded(query.filters, columns, services, groups)) { + for (auto const column : filter->columnsUsed()) { + if (!columns[column].level.empty()) { + order.push_back(columns[column].level); + } + } + } + } + if (query.distinct) { + auto const named = + query.distinct->group.empty() + ? std::span{&query.distinct->column, 1} + : detail::groupColumns(groups, query.distinct->group).value_or(std::span{}); + for (auto const& columnId : named) { + add(order, columnId); + } + } + if (query.columns) { + for (auto const& columnId : *query.columns) { + add(display, columnId); + } + } else { + for (auto const& [columnId, level] : levelled) { + if (!mayRead || mayRead(columnId)) { + display.push_back(level); + } + } + } + return LevelsNeeded{.order = detail::sortedLevels(std::move(order)), + .display = detail::sortedLevels(std::move(display))}; +} + +} // namespace morph::table + +namespace morph::table::detail { + +std::expected computeView(DataSource const& source, TableQuery const& validated, + ApplyOptions const& options) { + auto const columns = source.columns(); + for (auto const& key : validated.sort) { + if (auto const column = findColumn(columns, key.column)) { + if (auto missing = unitsMissing(columns[*column], options.services)) { + return std::unexpected(std::move(*missing)); + } + } + } + // One copy of the services for this call, the filter's operands included: + // a collator that is not safe to share clones itself here, so concurrent + // calls never fold on the one the caller passed. + auto services = options.services.forTask(); + auto filter = compileFilterGuarded(validated.filters, columns, services, source.groups()); + if (!filter) { + return std::unexpected(std::move(filter.error())); + } + JobInput input; + input.snapshot = source.snapshot(); + input.columns.assign(columns.begin(), columns.end()); + input.services = std::move(services); + input.keys.resize(columns.size()); + for (auto const& key : validated.sort) { + if (auto const column = findColumn(columns, key.column)) { + input.needed.push_back(*column); + } + } + for (auto const column : filter->columnsUsed()) { + input.needed.push_back(column); + } + std::ranges::sort(input.needed); + auto const [first, last] = std::ranges::unique(input.needed); + input.needed.erase(first, last); + input.sort = validated.sort; + input.filter = std::make_shared(std::move(*filter)); + input.previousSnapshot = input.snapshot; + auto const snapshot = input.snapshot; + ViewJob job{std::move(input)}; + static_cast(job.step(kNoDeadline, ::core::async::StopToken{})); + if (job.failure()) { + return std::unexpected(*job.failure()); + } + auto result = job.takeResult(); + ComputedView out{.rows = std::move(result.view), .undecided = std::move(result.undecided), .digest = {}}; + for (auto const row : out.rows) { + out.digest.add(snapshot->rowId(row)); + } + return out; +} + +void keyedRows(ComputedView const& view, RowSnapshot const& snapshot, std::span keys, + std::span viewRowOf, SourceRowOf const& sourceRowOf, PageRows& out) { + if (view.rows.empty() || keys.empty()) { + return; + } + std::vector built; + if (viewRowOf.empty()) { + built.assign(snapshot.rowCount(), kNotInView); + for (std::size_t at = 0; at < view.rows.size(); ++at) { + built[view.rows[at]] = static_cast(at); + } + viewRowOf = built; + } + // (view row, source row) of each key found in the view. + std::vector> found; + found.reserve(keys.size()); + auto const take = [&found, viewRowOf](std::size_t row) { + if (row < viewRowOf.size() && viewRowOf[row] != kNotInView) { + found.emplace_back(viewRowOf[row], static_cast(row)); + } + }; + if (sourceRowOf) { + for (auto const& key : keys) { + if (auto const row = sourceRowOf(key)) { + take(*row); + } + } + } else { + std::unordered_set const wanted(keys.begin(), keys.end()); + std::size_t matched = 0; + for (std::size_t row = 0; row < snapshot.rowCount() && matched < wanted.size(); ++row) { + if (wanted.contains(snapshot.rowId(row))) { + ++matched; + take(row); + } + } + } + // A key asked for twice is one row of the reply. + std::ranges::sort(found); + auto const [first, last] = std::ranges::unique(found); + found.erase(first, last); + out.rows.reserve(found.size()); + out.indices.reserve(found.size()); + for (auto const& [viewRow, sourceRow] : found) { + out.rows.push_back(sourceRow); + out.indices.push_back(viewRow); + } +} + +PageRows pageRows(ComputedView const& view, RowSnapshot const& snapshot, TableQuery const& validated, + QueryLimits const& limits, std::span viewRowOf, + SourceRowOf const& sourceRowOf) { + PageRows out; + out.viewRevision = view.digest.text(); + out.undecided = static_cast(view.undecided.size()); + out.totalKind = out.undecided > 0 ? TotalKind::AtLeast : TotalKind::Exact; + auto const count = static_cast(view.rows.size()); + if (count <= limits.totalCap) { + out.total = count; + } + if (validated.keys) { + keyedRows(view, snapshot, *validated.keys, viewRowOf, sourceRowOf, out); + return out; + } + out.offset = validated.page.offset; + auto const begin = std::min(validated.page.offset, count); + // Compared, not added: `maxLimit` may be as large as INT64_MAX. + auto const end = validated.page.limit >= count - begin ? count : begin + validated.page.limit; + for (auto i = begin; i < end; ++i) { + out.rows.push_back(view.rows[static_cast(i)]); + } + return out; +} + +MergedView mergeRetained(std::span baseOrder, std::int64_t baseUndecided, + MembershipDigest baseDigest, std::span retainedRows, + std::function const& before, + std::function const& match, + std::function const& keyOf) { + auto merged = mergeRetainedOrder(baseOrder, retainedRows, before, match); + MergedView out{.order = std::move(merged.order), + .unmatched = std::move(merged.unmatched), + .undecided = baseUndecided - merged.undecided, + .digest = baseDigest}; + for (auto const row : merged.admitted) { + out.digest.add(keyOf(row)); + } + return out; +} + +std::uint32_t SparseKeys::local(std::uint32_t row) { + auto const [found, made] = _local.try_emplace(row, static_cast(_rows.size())); + if (made) { + if (_rows.size() == _capacity) { + grow(_capacity * 2); + } + _rows.push_back(row); + fill(found->second); + } + return found->second; +} + +void SparseKeys::fill(std::uint32_t position) { + for (auto const column : _needed) { + _keys[column]->set(position, _snapshot->cell(_rows[position], column), _columns[column], *_services); + } +} + +void SparseKeys::grow(std::size_t capacity) { + _capacity = capacity; + _keys.clear(); + _keys.resize(_columns.size()); + _pointers.assign(_columns.size(), nullptr); + for (auto const column : _needed) { + _keys[column] = std::make_unique(KeyColumn::forColumn(_columns[column], *_services, capacity)); + _pointers[column] = _keys[column].get(); + } + for (std::size_t at = 0; at < _rows.size(); ++at) { + fill(static_cast(at)); + } +} + +std::expected retainedView(ComputedView const& base, DataSource const& source, + RowSnapshot const& snapshot, TableQuery const& validated, + ApplyOptions const& options, SourceRowOf const& sourceRowOf) { + std::vector rows; + if (sourceRowOf) { + for (auto const& key : validated.retain) { + if (auto const row = sourceRowOf(key)) { + rows.push_back(*row); + } + } + } else { + std::unordered_set const wanted(validated.retain.begin(), validated.retain.end()); + for (std::size_t row = 0; row < snapshot.rowCount() && rows.size() < wanted.size(); ++row) { + if (wanted.contains(snapshot.rowId(row))) { + rows.push_back(static_cast(row)); + } + } + } + auto const columns = source.columns(); + auto const services = options.services.forTask(); + auto filter = compileFilterGuarded(validated.filters, columns, services, source.groups()); + if (!filter) { + return std::unexpected(std::move(filter.error())); + } + std::vector> sortKeys; + std::vector needed; + for (auto const& key : validated.sort) { + if (auto const column = findColumn(columns, key.column)) { + sortKeys.emplace_back(*column, key.dir); + needed.push_back(*column); + } + } + for (auto const column : filter->columnsUsed()) { + needed.push_back(column); + } + std::ranges::sort(needed); + auto const [first, last] = std::ranges::unique(needed); + needed.erase(first, last); + SparseKeys keys{snapshot, columns, services, std::move(needed)}; + auto const before = [&keys, &sortKeys](std::uint32_t left, std::uint32_t right) { + auto const leftAt = keys.local(left); + auto const rightAt = keys.local(right); + auto const pointers = keys.pointers(); + for (auto const& [column, dir] : sortKeys) { + if (int const result = compareKeys(*pointers[column], leftAt, rightAt, dir); result != 0) { + return result < 0; + } + } + return left < right; + }; + auto const match = [&keys, &filter](std::uint32_t row) { + auto const local = keys.local(row); + return filter->evaluateRow(keys.pointers(), local); + }; + auto merged = mergeRetained(base.rows, static_cast(base.undecided.size()), base.digest, rows, before, + match, [&snapshot](std::uint32_t row) { return snapshot.rowId(row); }); + std::ranges::sort(rows); + RetainedView out; + out.view.rows = std::move(merged.order); + // The retained rows that were undecided are in the view now. + std::ranges::set_difference(base.undecided, rows, std::back_inserter(out.view.undecided)); + out.view.digest = merged.digest; + out.unmatched = std::move(merged.unmatched); + return out; +} + +void markUnmatched(PageRows& page, std::span unmatched) { + page.unmatched.clear(); + for (std::size_t at = 0; at < page.rows.size(); ++at) { + auto const viewRow = page.indices.empty() ? page.offset + static_cast(at) : page.indices[at]; + if (std::ranges::binary_search(unmatched, viewRow)) { + page.unmatched.push_back(static_cast(at)); + } + } +} + +std::expected viewPage(ComputedView const& view, DataSource const& source, + RowSnapshot const& snapshot, TableQuery const& validated, + ApplyOptions const& options, std::span viewRowOf, + SourceRowOf const& sourceRowOf) { + if (validated.retain.empty()) { + return pageRows(view, snapshot, validated, options.limits, viewRowOf, sourceRowOf); + } + auto merged = retainedView(view, source, snapshot, validated, options, sourceRowOf); + if (!merged) { + return std::unexpected(std::move(merged.error())); + } + auto out = pageRows(merged->view, snapshot, validated, options.limits, {}, sourceRowOf); + markUnmatched(out, merged->unmatched); + return out; +} + +std::string isoDate(std::int64_t days) { + auto const date = civilDate(days); + return std::format("{:04}-{:02}-{:02}", static_cast(date.year()), static_cast(date.month()), + static_cast(date.day())); +} + +std::int64_t dayOfSeconds(std::int64_t seconds) { + constexpr std::int64_t kDay = 86'400; + return (seconds >= 0 ? seconds : seconds - (kDay - 1)) / kDay; +} + +std::string isoDateTime(std::int64_t seconds) { + constexpr std::int64_t kDay = 86'400; + auto const day = dayOfSeconds(seconds); + auto const secondOfDay = seconds - (day * kDay); + return std::format("{}T{:02}:{:02}:{:02}Z", isoDate(day), secondOfDay / 3600, (secondOfDay / 60) % 60, + secondOfDay % 60); +} + +std::pair bucketDays(std::int64_t day, DateBucket bucket) { + using namespace std::chrono; + auto const date = civilDate(day); + switch (bucket) { + case DateBucket::Year: + return {daysOf(date.year() / January / 1), daysOf(date.year() / December / 31)}; + case DateBucket::Month: + return {daysOf(date.year() / date.month() / 1), + daysOf(year_month_day{year_month_day_last{date.year(), month_day_last{date.month()}}})}; + case DateBucket::Day: + case DateBucket::Value: + default: + return {day, day}; + } +} + +int compareValues(KeyColumn const& left, std::uint32_t leftRow, KeyColumn const& right, std::uint32_t rightRow) { + auto const sign = [](auto ordering) -> int { + if (std::is_lt(ordering)) { + return -1; + } + return std::is_gt(ordering) ? 1 : 0; + }; + switch (left.kind) { + case ColumnKind::Integer: + case ColumnKind::Key: + case ColumnKind::Date: + case ColumnKind::DateTime: + case ColumnKind::Bool: + return sign(left.ints[leftRow] <=> right.ints[rightRow]); + case ColumnKind::Decimal: + case ColumnKind::Quantity: + return sign(left.exact[leftRow] <=> right.exact[rightRow]); + case ColumnKind::Number: + return sign(std::strong_order(left.reals[leftRow], right.reals[rightRow])); + case ColumnKind::Text: + return sign(left.text[leftRow].compare(right.text[rightRow]) <=> 0); + case ColumnKind::Measure: + if (left.places[leftRow] != right.places[rightRow]) { + return left.places[leftRow] < right.places[rightRow] ? -1 : 1; + } + return sign(left.exact[leftRow] <=> right.exact[rightRow]); + case ColumnKind::Custom: + default: + return 0; + } +} + +std::optional measureOf(Cell const& cell, UnitRegistry const* units) { + if (auto const* const value = std::get_if(&cell)) { + return *value; + } + if (auto const* const value = std::get_if(&cell)) { + return Measure{.amount = *value, .unit = 0}; + } + if (auto const* const value = std::get_if(&cell)) { + return Measure{.amount = math::Rational{*value, math::DecimalPlaces{0}}, .unit = 0}; + } + if (auto const* const value = std::get_if(&cell); value != nullptr && units != nullptr) { + if (auto const operand = splitMeasureOperand(*value)) { + if (auto const unit = units->find(operand->second)) { + return Measure{.amount = operand->first, .unit = *unit}; + } + } + } + return std::nullopt; +} + +DistinctValue describeValue(RowSnapshot const& snapshot, std::size_t column, ColumnInfo const& info, + KeyColumn const& keys, std::uint32_t row, DateBucket bucket, UnitRegistry const* units) { + auto const both = [](std::string const& text) { return DistinctValue{.text = text, .operand = text, .count = 0}; }; + if (info.kind == ColumnKind::Measure) { + auto const measure = measureOf(snapshot.cell(row, column), units); + if (!measure || units == nullptr || !units->contains(measure->unit)) { + return both({}); + } + auto const& unit = units->info(measure->unit); + auto const amount = units::detail::formatRationalDecimal(measure->amount); + return DistinctValue{.text = unit.symbol.empty() ? amount : amount + " " + unit.symbol, + .operand = unit.id.empty() ? amount : amount + " " + unit.id, + .count = 0, + .dimension = unit.dimension, + .unit = unit.id}; + } + switch (info.kind) { + case ColumnKind::Text: + return both(keys.raw[row]); + case ColumnKind::Integer: + case ColumnKind::Key: + return both(std::to_string(keys.ints[row])); + case ColumnKind::Decimal: + case ColumnKind::Quantity: + return both(units::detail::formatRationalDecimal(keys.exact[row])); + case ColumnKind::Number: + return both(std::format("{}", keys.reals[row])); + case ColumnKind::Bool: + return both(keys.ints[row] != 0 ? "true" : "false"); + case ColumnKind::Date: + case ColumnKind::DateTime: + break; + case ColumnKind::Custom: + case ColumnKind::Measure: // answered above + default: + return both({}); + } + bool const dateTime = info.kind == ColumnKind::DateTime; + if (bucket == DateBucket::Value) { + if (auto const cell = snapshot.cell(row, column); auto const* const text = std::get_if(&cell)) { + return both(*text); + } + return both(dateTime ? isoDateTime(keys.ints[row]) : isoDate(keys.ints[row])); + } + auto const day = dateTime ? dayOfSeconds(keys.ints[row]) : keys.ints[row]; + auto const [first, last] = bucketDays(day, bucket); + auto text = isoDate(first); + if (bucket == DateBucket::Year) { + text.resize(4); + } else if (bucket == DateBucket::Month) { + text.resize(7); + } + auto operand = dateTime ? isoDate(first) + "T00:00:00Z.." + isoDate(last) + "T23:59:59Z" + : isoDate(first) + ".." + isoDate(last); + return DistinctValue{.text = std::move(text), .operand = std::move(operand), .count = 0}; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +std::expected distinctOver(DistinctInput const& input, DistinctRequest const& validated) { + try { + auto const filter = compileFilter(input.filters, input.columns, input.services, input.groups); + if (!filter) { + return std::unexpected(filter.error()); + } + auto const& snapshot = *input.snapshot; + auto const rowCount = snapshot.rowCount(); + std::vector listed; + if (validated.group.empty()) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): validate() resolved every column the request names. + listed.push_back(*findColumn(input.columns, validated.column)); + } else { + // A local, not the range-for's own temporary: the optional holding the span must outlive the loop. + auto const members = groupColumns(input.groups, validated.group); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): validate() resolved every column the request names. + for (auto const& columnId : *members) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): validate() resolved every column the request names. + listed.push_back(*findColumn(input.columns, columnId)); + } + } + for (auto const column : listed) { + if (auto missing = unitsMissing(input.columns[column], input.services)) { + return std::unexpected(std::move(*missing)); + } + } + std::vector> built(input.columns.size()); + std::vector pointers(input.columns.size(), nullptr); + auto const keysOf = [&](std::size_t column) { + if (column < input.keys.size() && input.keys[column] != nullptr) { + pointers[column] = input.keys[column].get(); + return; + } + auto keys = + std::make_shared(KeyColumn::forColumn(input.columns[column], input.services, rowCount)); + buildKeys(snapshot, column, input.columns[column], input.services, 0, rowCount, *keys); + pointers[column] = keys.get(); + built[column] = std::move(keys); + }; + for (auto const column : filter->columnsUsed()) { + keysOf(column); + } + for (auto const column : listed) { + if (pointers[column] == nullptr) { + keysOf(column); + } + } + // As a view job does: an unloaded cell in a base-level column the list reads is a broken source, not a + // list that may grow. + for (std::size_t at = 0; at < pointers.size(); ++at) { + if (pointers[at] != nullptr && input.columns[at].level.empty() && + std::ranges::contains(pointers[at]->states, CellState::Unloaded)) { + return std::unexpected(unloadedInBaseLevel(input.columns[at])); + } + } + std::vector candidates(rowCount); + for (std::size_t row = 0; row < rowCount; ++row) { + candidates[row] = static_cast(row); + } + DistinctValues out; + if (!filter->empty()) { + FilterRun run{*filter, pointers, std::move(candidates)}; + static_cast(run.run(kNoDeadline, ::core::async::StopToken{})); + out.partial = !std::move(run).takeUndecided().empty(); + // NOLINTNEXTLINE(bugprone-use-after-move): take and takeUndecided read different marks of the same rows and move nothing. + candidates = std::move(run).take(); + } + std::vector listedKeys; + listedKeys.reserve(listed.size()); + for (auto const column : listed) { + listedKeys.push_back(pointers[column]); + } + // Every listed column is of one kind: a declared group's are, by `checkGroups`. + auto const& info = input.columns[listed.front()]; + std::vector groups; + switch (info.kind) { + case ColumnKind::Text: + groupRows( + candidates, listedKeys, + [](KeyColumn const& keys, std::uint32_t row) { return std::string_view{keys.folded[row]}; }, + groups, out); + break; + case ColumnKind::Decimal: + case ColumnKind::Quantity: + groupRows( + candidates, listedKeys, [](KeyColumn const& keys, std::uint32_t row) { return keys.exact[row]; }, + groups, out); + break; + case ColumnKind::Measure: + groupRows( + candidates, listedKeys, + [](KeyColumn const& keys, std::uint32_t row) { + return MeasureKey{.place = keys.places[row], .amount = keys.exact[row]}; + }, + groups, out); + break; + case ColumnKind::Number: + groupRows( + candidates, listedKeys, + [](KeyColumn const& keys, std::uint32_t row) { + return keys.reals[row] == 0.0 ? 0.0 : keys.reals[row]; + }, + groups, out); + break; + case ColumnKind::Date: + case ColumnKind::DateTime: { + bool const dateTime = info.kind == ColumnKind::DateTime; + auto const bucket = validated.bucket; + groupRows( + candidates, listedKeys, + [dateTime, bucket](KeyColumn const& keys, std::uint32_t row) { + if (bucket == DateBucket::Value) { + return keys.ints[row]; + } + return bucketDays(dateTime ? dayOfSeconds(keys.ints[row]) : keys.ints[row], bucket).first; + }, + groups, out); + break; + } + case ColumnKind::Integer: + case ColumnKind::Key: + case ColumnKind::Bool: + case ColumnKind::Custom: + default: + groupRows( + candidates, listedKeys, [](KeyColumn const& keys, std::uint32_t row) { return keys.ints[row]; }, + groups, out); + break; + } + auto const describe = [&](DistinctGroup const& group) { + auto const column = listed[group.column]; + return describeValue(snapshot, column, input.columns[column], *listedKeys[group.column], group.first, + validated.bucket, input.services.units.get()); + }; + if (!validated.search.empty()) { + auto const& collator = collatorOf(input.services); + auto const needle = collator.fold(validated.search); + std::erase_if(groups, [&](DistinctGroup const& group) { + if (info.kind == ColumnKind::Text) { + return !std::string_view{listedKeys[group.column]->folded[group.first]}.contains(needle); + } + return !collator.fold(describe(group).text).contains(needle); + }); + } + auto const count = static_cast(groups.size()); + out.distinct = std::min(count, input.limits.totalCap); + out.distinctKind = count > input.limits.totalCap ? TotalKind::AtLeast : TotalKind::Exact; + auto const begin = std::min(validated.offset, count); + auto const end = validated.limit >= count - begin ? count : begin + validated.limit; + // Only the values up to the page's end are put in order: a menu's first page of 50,000 values sorts 200. + std::ranges::partial_sort(groups, groups.begin() + static_cast(end), + [&listedKeys](DistinctGroup const& left, DistinctGroup const& right) { + int const order = compareValues(*listedKeys[left.column], left.first, + *listedKeys[right.column], right.first); + return order != 0 ? order < 0 : left.first < right.first; + }); + for (auto at = begin; at < end; ++at) { + auto const& group = groups[static_cast(at)]; + auto value = describe(group); + value.count = group.count; + out.values.push_back(std::move(value)); + } + return out; + } catch (std::exception const& error) { + return std::unexpected(serviceFailed(error.what())); + } catch (...) { + return std::unexpected(serviceFailed("unknown exception")); + } +} + +void withoutOwnFilter(FilterSpec& filters, DistinctRequest const& request) { + if (request.group.empty()) { + filters.columns.erase(request.column); + return; + } + std::erase_if(filters.groups, [&request](GroupFilter const& group) { return group.group == request.group; }); +} + +} // namespace morph::table::detail + +namespace morph::table { + +std::expected distinctValues(DataSource const& source, TableQuery const& query, + DistinctRequest const& request, ApplyOptions const& options) { + if (auto error = detail::checkGroups(source.columns(), source.groups())) { + return std::unexpected(std::move(*error)); + } + TableQuery asked = query; + asked.distinct = request; + auto checked = validate(std::move(asked), source.columns(), options.limits, options.mayRead, source.groups()); + if (!checked) { + return std::unexpected(std::move(checked.error())); + } + detail::DistinctInput input{.snapshot = source.snapshot(), + .columns = source.columns(), + .keys = {}, + .filters = std::move(checked->filters), + .services = options.services.forTask(), + .limits = options.limits, + .groups = source.groups()}; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): validate() accepted the request as a distinct-values one. + detail::withoutOwnFilter(input.filters, *checked->distinct); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): validate() accepted the request as a distinct-values one. + return detail::distinctOver(input, *checked->distinct); +} + +std::expected apply(DataSource const& source, TableQuery const& query, + ApplyOptions const& options) { + if (auto error = detail::checkGroups(source.columns(), source.groups())) { + return std::unexpected(std::move(*error)); + } + auto const checked = validate(query, source.columns(), options.limits, options.mayRead, source.groups()); + if (!checked) { + return std::unexpected(checked.error()); + } + if (checked->distinct) { + auto values = distinctValues(source, *checked, *checked->distinct, options); + if (!values) { + return std::unexpected(std::move(values.error())); + } + return PageRows{.rows = {}, .distinct = std::move(*values)}; + } + auto const view = detail::computeView(source, *checked, options); + if (!view) { + return std::unexpected(view.error()); + } + // A source is read on its owner's thread, which this call is on, so this is the snapshot the view was + // computed over. + return detail::viewPage(*view, source, *source.snapshot(), *checked, options); +} + +std::vector changeKeys(std::span keys) { + std::vector out; + out.reserve(keys.size()); + for (auto const& key : keys) { + if (auto const* const integer = std::get_if(&key)) { + out.emplace_back(std::to_string(*integer)); + } else { + out.emplace_back(glz::write_json(std::get(key)).value_or(std::string{"\"\""})); + } + } + return out; +} + +std::optional rowIdOf(glz::raw_json const& key) { + constexpr std::string_view kSpace = " \t\n\r"; + std::string_view text = key.str; + auto const first = text.find_first_not_of(kSpace); + text = first == std::string_view::npos ? std::string_view{} + : text.substr(first, text.find_last_not_of(kSpace) - first + 1); + if (text.empty()) { + return std::nullopt; + } + if (text.front() == '"') { + std::string value; + std::string const buffer{text}; + if (glz::read_json(value, buffer)) { + return std::nullopt; + } + return RowId{std::move(value)}; + } + std::int64_t value = 0; + auto const* const end = std::to_address(text.end()); + auto const [rest, error] = std::from_chars(std::to_address(text.begin()), end, value); + if (error != std::errc{} || rest != end) { + return std::nullopt; + } + return RowId{value}; +} + +void MeasureValue::setWire(Wire const& wire) { + std::uint32_t places = math::kMaxDecimalPlaces; + std::int64_t power = 1; + for (std::uint32_t k = 0; k <= math::kMaxDecimalPlaces; ++k) { + if (power == wire.den) { + places = k; + break; + } + if (power > std::numeric_limits::max() / 10) { + break; + } + power *= 10; + } + amount = wire.den > 0 + ? math::Rational{math::Numerator{wire.num}, math::Denominator{wire.den}, math::DecimalPlaces{places}} + : math::Rational{}; + unit = wire.unit; +} + +} // namespace morph::table + +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) diff --git a/src/table/row_selection.cpp b/src/table/row_selection.cpp new file mode 100644 index 000000000..8308f67ab --- /dev/null +++ b/src/table/row_selection.cpp @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table::detail { + +std::string compactFilterJson(FilterSpec const& filters) { + glz::generic_u64 json; + if (glz::read_json(json, glz::write_json(filters).value_or("{}"))) { + return "{}"; + } + std::function prune = [&prune](glz::generic_u64& node) { + if (node.is_array()) { + for (auto& item : node.get_array()) { + prune(item); + } + return; + } + if (!node.is_object()) { + return; + } + auto& members = node.get_object(); + // NOLINTNEXTLINE(readability-qualified-auto): the iterator is a pointer in some standard libraries and a class in others. + for (auto at = members.begin(); at != members.end();) { + auto& value = at->second; + prune(value); + bool const empty = value.is_null() || (value.is_array() && value.get_array().empty()) || + (value.is_string() && value.get_string().empty()) || + (at->first == "combine" && value.is_string() && value.get_string() == "any"); + at = empty && at->first != "columns" ? members.erase(at) : std::next(at); + } + }; + prune(json); + return glz::write_json(json).value_or("{}"); +} + +std::string selectionJson(std::span keys, FilterSpec const* filters, std::span retained, + std::string_view revision, std::span except) { + auto const list = [](std::span items) { + return glz::write_json(std::vector(items.begin(), items.end())).value_or("[]"); + }; + if (filters == nullptr) { + return R"({"keys":)" + list(keys) + "}"; + } + return R"({"view":{"filters":)" + compactFilterJson(*filters) + R"(,"retained":)" + list(retained) + + R"(,"revision":)" + glz::write_json(revision).value_or(R"("")") + R"(},"except":)" + list(except) + "}"; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +std::expected membership(ServedTable const& served, FilterSpec const& filters, + std::span retained, ViewCache* views, + std::string_view record) { + if (served.source == nullptr) { + return std::unexpected( + TableError{.code = TableErrorCode::Unavailable, .column = {}, .message = "the table serves no source"}); + } + // A table built by hand may describe no columns: its source's are then the table's. + auto infos = columnInfos(served.description); + if (infos.empty()) { + auto const own = served.source->columns(); + infos.assign(own.begin(), own.end()); + } + auto const groups = served.source->groups(); + if (auto error = checkGroups(served.source->columns(), groups)) { + return std::unexpected(std::move(*error)); + } + TableQuery query; + query.filters = filters; + auto checked = validate(std::move(query), infos, served.limits, served.mayRead, groups); + if (!checked) { + return std::unexpected(std::move(checked.error())); + } + auto const needed = levelsNeeded(*checked, infos, served.mayRead, served.services.forTask(), groups); + std::vector inputs; + for (auto const& level : needed.order) { + for (auto const& source : served.levels) { + if (source != nullptr && source->level() == level) { + auto levelSnapshot = source->snapshot(); + inputs.push_back(LevelInput{.source = source, .snapshot = std::move(levelSnapshot)}); + } + } + } + LeveledSource const leveled{served.source, infos, inputs}; + ApplyOptions const options{.limits = served.limits, .services = served.services, .mayRead = served.mayRead}; + auto const compute = [&]() -> std::expected { + auto view = computeView(leveled, *checked, options); + if (!view) { + return std::unexpected(std::move(view.error())); + } + return ViewComputation{.view = std::move(*view), .awaiting = {}, .failed = {}, .orderKeys = {}}; + }; + std::shared_ptr entry; + // A filter that reads a level is computed here: a cached entry of it also holds what its levels want, which + // only a page query computes. + auto const viewQuery = + views != nullptr && !record.empty() && needed.order.empty() ? viewQueryOf(*checked) : std::nullopt; + if (viewQuery) { + auto const* const pinnedSource = dynamic_cast(served.source.get()); + auto found = views->find(ViewKey{.record = std::string{record}, .scope = served.scope, .query = *viewQuery}, + served.source->snapshot(), {}, compute, + pinnedSource != nullptr ? pinnedSource->pinnedAt() : 0); + if (!found) { + return std::unexpected(std::move(found.error())); + } + entry = std::move(*found); + } else { + auto computed = compute(); + if (!computed) { + return std::unexpected(std::move(computed.error())); + } + entry = std::make_shared( + served.source->snapshot(), std::vector>{}, std::move(*computed)); + } + Membership out{.rows = entry->view.rows, .digest = entry->view.digest}; + if (!retained.empty()) { + auto const snapshot = leveled.snapshot(); + std::unordered_set const wanted(retained.begin(), retained.end()); + std::unordered_set const inView(out.rows.begin(), out.rows.end()); + std::vector merged; + for (std::size_t row = 0; row < snapshot->rowCount() && merged.size() < wanted.size(); ++row) { + auto const rowIndex = static_cast(row); + if (wanted.contains(snapshot->rowId(row)) && !inView.contains(rowIndex)) { + merged.push_back(rowIndex); + out.digest.add(snapshot->rowId(row)); + } + } + auto const middle = static_cast(out.rows.size()); + out.rows.insert(out.rows.end(), merged.begin(), merged.end()); + std::ranges::inplace_merge(out.rows, out.rows.begin() + middle); + } + if (std::cmp_greater(out.rows.size(), served.limits.maxSelectedRows)) { + return std::unexpected(TableError{.code = TableErrorCode::LimitExceeded, + .column = {}, + .message = "a selection of the view holds at most " + + std::to_string(served.limits.maxSelectedRows) + " rows"}); + } + return out; +} + +std::expected resolveSelection(ServedTable const& served, PlainSelection const& selection, + SelectionPolicy policy, ViewCache* views, + std::string_view record, bool rowScoped) { + // A row-scoped table with no scope would let callers share views of different rows. + if (rowScoped && served.scope.empty()) { + return std::unexpected(TableError{ + .code = TableErrorCode::SourceContract, .column = {}, .message = "a row-scoped table needs a scope"}); + } + if (served.source == nullptr) { + return std::unexpected( + TableError{.code = TableErrorCode::Unavailable, .column = {}, .message = "the table serves no source"}); + } + SelectedRows out; + if (!selection.isView) { + std::unordered_set const wanted(selection.keys.begin(), selection.keys.end()); + if (std::cmp_greater(wanted.size(), served.limits.maxSelectedRows)) { + return std::unexpected(TableError{ + .code = TableErrorCode::LimitExceeded, + .column = {}, + .message = "a selection holds at most " + std::to_string(served.limits.maxSelectedRows) + " rows"}); + } + auto const snapshot = served.source->snapshot(); + for (std::size_t row = 0; row < snapshot->rowCount() && out.keys.size() < wanted.size(); ++row) { + if (auto key = snapshot->rowId(row); wanted.contains(key)) { + out.keys.push_back(std::move(key)); + } + } + out.dropped = static_cast(wanted.size() - out.keys.size()); + return out; + } + auto members = membership(served, selection.filters, selection.retained, views, record); + if (!members) { + return std::unexpected(std::move(members.error())); + } + if (policy == SelectionPolicy::Exact && members->digest.text() != selection.revision) { + return std::unexpected(TableError{.code = TableErrorCode::ViewChanged, + .column = {}, + .message = "the rows changed since they were selected"}); + } + std::unordered_set const except(selection.except.begin(), selection.except.end()); + auto const snapshot = served.source->snapshot(); + out.keys.reserve(members->rows.size()); + for (auto const row : members->rows) { + if (auto key = snapshot->rowId(row); !except.contains(key)) { + out.keys.push_back(std::move(key)); + } + } + return out; +} + +void ResolveInline::post(std::function task) { + if (task) { + ::core::async::ExecutorScope const scope{coreExecutor()}; + task(); + } +} + +} // namespace morph::table::detail diff --git a/src/table/state_store.cpp b/src/table/state_store.cpp new file mode 100644 index 000000000..0f5a639bc --- /dev/null +++ b/src/table/state_store.cpp @@ -0,0 +1,711 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::table::detail { + +StoredView storedView(SavedView const& view) { + StoredView out{.name = view.name, .layout = view.layout, .sort = {}, .filters = view.filters}; + out.sort.reserve(view.sort.size()); + for (auto const& key : view.sort) { + out.sort.push_back(StoredSortKey{.column = key.column, .direction = key.dir}); + } + return out; +} + +SavedView savedView(StoredView stored) { + SavedView out{.name = std::move(stored.name), + .layout = std::move(stored.layout), + .sort = {}, + .filters = std::move(stored.filters)}; + out.sort.reserve(stored.sort.size()); + for (auto& key : stored.sort) { + out.sort.push_back(SortKey{.column = std::move(key.column), .dir = key.direction}); + } + return out; +} + +std::unexpected viewsError(std::string message) { + return std::unexpected( + TableError{.code = TableErrorCode::InvalidSpec, .column = {}, .message = std::move(message)}); +} + +} // namespace morph::table::detail + +namespace morph::table { + +std::expected readViews(std::string_view json) { + auto const probe = detail::readViewsJson(json, "a views document"); + if (!probe) { + return std::unexpected(probe.error()); + } + if (probe->version != kViewsVersion) { + return detail::viewsError("a views document is version " + std::to_string(probe->version) + + "; this reads version " + std::to_string(kViewsVersion)); + } + auto stored = detail::readViewsJson(json, "a views document"); + if (!stored) { + return std::unexpected(stored.error()); + } + ViewsDocument document{.version = stored->version, + .defaultView = std::move(stored->defaultView), + .defaultOnMount = stored->defaultOnMount.value_or(false), + .views = {}}; + for (auto& view : stored->views) { + if (!std::ranges::contains(document.views, view.name, &SavedView::name)) { + document.views.push_back(detail::savedView(std::move(view))); + } + } + return document; +} + +std::string writeViews(ViewsDocument const& document, ViewsPart part) { + detail::StoredViews out; + if (part == ViewsPart::Own) { + out.defaultView = document.defaultView; + out.defaultOnMount = document.defaultOnMount; + } + out.views.reserve(document.views.size()); + for (auto const& view : document.views) { + out.views.push_back(detail::storedView(view)); + } + return detail::viewsJson(out); +} + +std::string writeViewOperation(ViewOperation const& operation) { + struct Writer { + std::string operator()(AddView const& add) const { + return R"({"add":)" + detail::viewsJson(detail::storedView(add.view)) + "}"; + } + std::string operator()(ReplaceView const& replace) const { + return R"({"replace":)" + detail::viewsJson(detail::storedView(replace.view)) + "}"; + } + std::string operator()(RenameView const& rename) const { + return R"({"rename":)" + detail::viewsJson(rename) + "}"; + } + std::string operator()(RemoveView const& remove) const { + return R"({"remove":)" + detail::viewsJson(remove.name) + "}"; + } + std::string operator()(SetDefaultView const& set) const { + return R"({"default":)" + (set.name ? detail::viewsJson(*set.name) : std::string{"null"}) + "}"; + } + std::string operator()(SetDefaultOnMount const& set) const { + return std::string{R"({"defaultOnMount":)"} + (set.on ? "true" : "false") + "}"; + } + }; + return std::visit(Writer{}, operation); +} + +std::expected readViewOperation(std::string_view json) { + auto const members = detail::readViewsJson>(json, "a views operation"); + if (!members) { + return std::unexpected(members.error()); + } + if (members->size() != 1) { + return detail::viewsError("a views operation has exactly one member"); + } + auto const& [name, raw] = *members->begin(); + std::string_view const text = raw.str; + auto const view = [text]() -> std::expected { + auto stored = detail::readViewsJson(text, "a saved view"); + if (!stored) { + return std::unexpected(stored.error()); + } + if (stored->name.empty()) { + return detail::viewsError("a saved view has a name"); + } + return detail::savedView(std::move(*stored)); + }; + if (name == "add" || name == "replace") { + auto read = view(); + if (!read) { + return std::unexpected(read.error()); + } + return name == "add" ? ViewOperation{AddView{std::move(*read)}} : ViewOperation{ReplaceView{std::move(*read)}}; + } + if (name == "rename") { + auto read = detail::readViewsJson(text, "a rename"); + if (!read) { + return std::unexpected(read.error()); + } + return ViewOperation{std::move(*read)}; + } + if (name == "remove") { + auto read = detail::readViewsJson(text, "a remove"); + if (!read) { + return std::unexpected(read.error()); + } + return ViewOperation{RemoveView{std::move(*read)}}; + } + if (name == "default") { + auto read = detail::readViewsJson>(text, "a default"); + if (!read) { + return std::unexpected(read.error()); + } + return ViewOperation{SetDefaultView{std::move(*read)}}; + } + if (name == "defaultOnMount") { + auto read = detail::readViewsJson(text, "a defaultOnMount"); + if (!read) { + return std::unexpected(read.error()); + } + return ViewOperation{SetDefaultOnMount{*read}}; + } + return detail::viewsError("a views operation `" + name + "` is not one this framework knows"); +} + +std::expected applyViewOperation(ViewsDocument document, ViewOperation const& operation, + ViewsPart part) { + auto const find = [&document](std::string const& name) { + return std::ranges::find(document.views, name, &SavedView::name); + }; + struct Applier { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members): the applier lives only inside this call, over its locals. + ViewsDocument& document; + ViewsPart part; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members): the applier lives only inside this call, over its locals. + decltype(find)& at; + + std::expected operator()(AddView const& add) const { + if (at(add.view.name) != document.views.end()) { + return std::unexpected(ViewError::NameTaken); + } + document.views.push_back(add.view); + return {}; + } + std::expected operator()(ReplaceView const& replace) const { + auto const found = at(replace.view.name); + if (found == document.views.end()) { + return std::unexpected(ViewError::NoSuchView); + } + *found = replace.view; + return {}; + } + std::expected operator()(RenameView const& rename) const { + auto const found = at(rename.from); + if (found == document.views.end()) { + return std::unexpected(ViewError::NoSuchView); + } + if (rename.to != rename.from && at(rename.to) != document.views.end()) { + return std::unexpected(ViewError::NameTaken); + } + found->name = rename.to; + if (document.defaultView == rename.from) { + document.defaultView = rename.to; + } + return {}; + } + std::expected operator()(RemoveView const& remove) const { + auto const found = at(remove.name); + if (found == document.views.end()) { + return std::unexpected(ViewError::NoSuchView); + } + document.views.erase(found); + if (document.defaultView == remove.name) { + document.defaultView.reset(); + } + return {}; + } + std::expected operator()(SetDefaultView const& set) const { + if (part == ViewsPart::Shared) { + return std::unexpected(ViewError::NotShared); + } + if (set.name && at(*set.name) == document.views.end()) { + return std::unexpected(ViewError::NoSuchView); + } + document.defaultView = set.name; + return {}; + } + std::expected operator()(SetDefaultOnMount const& set) const { + if (part == ViewsPart::Shared) { + return std::unexpected(ViewError::NotShared); + } + document.defaultOnMount = set.on; + return {}; + } + }; + if (auto const applied = std::visit(Applier{.document = document, .part = part, .at = find}, operation); + !applied) { + return std::unexpected(applied.error()); + } + return document; +} + +async::Completion ITableStateStore::refusePublish(exec::IExecutor& executor) { + auto [completion, promise] = async::Completion::makeSettleable(&executor); + promise.resolve( + SaveResult{.outcome = SaveOutcome::Refused, .revision = {}, .reason = "this store does not share views"}); + return std::move(completion); +} + +std::string viewErrorText(ViewError error, ViewOperation const& operation) { + std::string const name = std::visit( + [](Operation const& each) -> std::string { + if constexpr (std::is_same_v || std::is_same_v) { + return each.view.name; + } else if constexpr (std::is_same_v) { + return each.to; + } else if constexpr (std::is_same_v) { + return each.name; + } else if constexpr (std::is_same_v) { + return each.name.value_or(std::string{}); + } else { + return {}; + } + }, + operation); + switch (error) { + case ViewError::NameTaken: + return "A view named " + name + " exists"; + case ViewError::NoSuchView: + return "No view named " + + (std::holds_alternative(operation) ? std::get(operation).from : name); + case ViewError::NotShared: + return "The shared views have no default"; + default: + break; + } + return {}; +} + +async::Completion> MemoryTableStateStore::load(TableStateKey const& key) { + auto [completion, promise] = async::Completion>::makeSettleable(&_strand); + _strand.postTask([this, entry = tie(key), settle = std::move(promise)] mutable { + auto const found = _documents.find(entry); + settle.resolve(found == _documents.end() ? std::nullopt : std::optional{found->second}); + }); + return std::move(completion); +} + +async::Completion MemoryTableStateStore::save(TableStateKey const& key, std::string json, + std::string expected) { + auto [completion, promise] = async::Completion::makeSettleable(&_strand); + _strand.postTask([this, entry = tie(key), text = std::move(json), wanted = std::move(expected), + settle = std::move(promise)] mutable { settle.resolve(store(entry, std::move(text), wanted)); }); + return std::move(completion); +} + +async::Completion MemoryTableStateStore::publish(TableStateKey const& key, ViewOperation const& operation, + std::string expected) { + if (_sharing == Sharing::Private) { + return refusePublish(_strand); + } + auto [completion, promise] = async::Completion::makeSettleable(&_strand); + _strand.postTask([this, entry = tie(key), part = key.part, change = operation, wanted = std::move(expected), + settle = std::move(promise)] mutable { + auto const refuse = [&settle](std::string current, std::string reason) { + settle.resolve(SaveResult{ + .outcome = SaveOutcome::Refused, .revision = std::move(current), .reason = std::move(reason)}); + }; + auto const found = _documents.find(entry); + std::string const current = found == _documents.end() ? std::string{} : found->second.revision; + if (part != "shared") { + refuse(current, "views are published to the shared part"); + return; + } + if (auto conflict = conflictOf(found, wanted)) { + settle.resolve(std::move(*conflict)); + return; + } + ViewsDocument document; + if (found != _documents.end()) { + auto read = readViews(found->second.json); + if (!read) { + refuse(current, read.error().message); + return; + } + document = std::move(*read); + } + auto applied = applyViewOperation(std::move(document), change, ViewsPart::Shared); + if (!applied) { + refuse(current, viewErrorText(applied.error(), change)); + return; + } + settle.resolve(store(entry, writeViews(*applied, ViewsPart::Shared), wanted)); + }); + return std::move(completion); +} + +async::Completion MemoryTableStateStore::remove(TableStateKey const& key) { + auto [completion, promise] = async::Completion::makeSettleable(&_strand); + _strand.postTask([this, entry = tie(key), settle = std::move(promise)] mutable { + settle.resolve(_documents.erase(entry) != 0); + }); + return std::move(completion); +} + +std::optional MemoryTableStateStore::conflictOf(Documents::const_iterator found, + std::string const& wanted) const { + bool const stored = found != _documents.end(); + std::string const current = stored ? found->second.revision : std::string{}; + bool const holds = wanted.empty() || (wanted == kNoDocument ? !stored : stored && wanted == current); + if (holds) { + return std::nullopt; + } + return SaveResult{.outcome = SaveOutcome::Conflict, .revision = current, .reason = {}}; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the text to store, then the text the entry is expected to hold. +SaveResult MemoryTableStateStore::store(Key const& entry, std::string text, std::string const& wanted) { + if (auto conflict = conflictOf(_documents.find(entry), wanted)) { + return std::move(*conflict); + } + std::string revision = std::to_string(++_counts[entry]); + _documents.insert_or_assign(entry, StoredTableState{.json = std::move(text), .revision = revision}); + return SaveResult{.outcome = SaveOutcome::Saved, .revision = std::move(revision), .reason = {}}; +} + +} // namespace morph::table + +namespace morph::table::detail { + +bool listsUnit(TableDescription const& description, std::string_view dimension, std::string_view unit) { + return std::ranges::any_of( + description.units, [&](UnitInfo const& listed) { return listed.dimension == dimension && listed.id == unit; }); +} + +bool sameColumns(std::vector left, std::vector right) { + std::ranges::sort(left); + std::ranges::sort(right); + return left == right; +} + +std::string joinedColumns(std::vector const& columns) { + std::string out; + for (auto const& column : columns) { + out += out.empty() ? column : "," + column; + } + return out; +} + +} // namespace morph::table::detail + +namespace morph::table { + +std::expected readState(std::string_view json) { + detail::StateVersion probe; + if (auto const error = glz::read(probe, json); error) { + return std::unexpected("a table's state is not JSON: " + glz::format_error(error, json)); + } + if (probe.version > kStateVersion) { + return std::unexpected("a table's state is version " + std::to_string(probe.version) + "; this reads up to " + + std::to_string(kStateVersion)); + } + if (probe.version < kStateVersion) { + return std::unexpected("a table's state of version " + std::to_string(probe.version) + + " has no migration to version " + std::to_string(kStateVersion)); + } + detail::StoredState stored; + if (auto const error = glz::read(stored, json); error) { + return std::unexpected("a table's state does not read: " + glz::format_error(error, json)); + } + StateDocument document; + document.version = stored.version; + document.layout = std::move(stored.layout); + if (stored.sort) { + SortChain chain; + chain.reserve(stored.sort->size()); + for (auto& key : *stored.sort) { + chain.push_back(SortKey{.column = std::move(key.column), .dir = key.direction}); + } + document.sort = std::move(chain); + } + document.filters = std::move(stored.filters); + document.view = std::move(stored.view); + return document; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +std::string writeState(StateDocument const& document) { + CarriedState const& carried = document.carried; + detail::StoredState out; + out.version = kStateVersion; + out.view = document.view; + if (document.layout || !carried.columns.empty() || !carried.groups.empty()) { + ColumnLayoutValue layout = document.layout.value_or(ColumnLayoutValue{}); + std::unordered_set hidden{layout.hidden.begin(), layout.hidden.end()}; + // A stored `order` may leave columns out (fitting places them), so a hidden column it does not name is kept + // too, after those it does, in the order the layout listed it. + std::vector unordered; + for (auto const& column : carried.columns) { + auto place = layout.order.begin(); + if (!column.after.empty()) { + place = std::ranges::find(layout.order, column.after); + if (place != layout.order.end()) { + ++place; + } + } + layout.order.insert(place, column.id); + if (column.hidden) { + hidden.insert(column.id); + } + if (column.width) { + layout.widths.insert_or_assign(column.id, *column.width); + } + if (!column.units.empty()) { + layout.units.insert_or_assign(column.id, column.units); + } + } + for (auto const& columnId : layout.hidden) { + if (std::ranges::find(layout.order, columnId) == layout.order.end() && + std::ranges::find(unordered, columnId) == unordered.end()) { + unordered.push_back(columnId); + } + } + layout.hidden.clear(); + for (auto const& columnId : layout.order) { + if (hidden.contains(columnId)) { + layout.hidden.push_back(columnId); + } + } + layout.hidden.insert(layout.hidden.end(), unordered.begin(), unordered.end()); + layout.groups.insert(layout.groups.end(), carried.groups.begin(), carried.groups.end()); + out.layout = std::move(layout); + } + if (document.sort || !carried.sort.empty()) { + SortChain chain = document.sort.value_or(SortChain{}); + auto keys = carried.sort; + std::ranges::stable_sort(keys, {}, &std::pair::first); + for (auto const& [index, key] : keys) { + chain.insert(chain.begin() + static_cast(std::min(index, chain.size())), key); + } + std::vector stored; + stored.reserve(chain.size()); + for (auto const& key : chain) { + stored.push_back(detail::StoredSortKey{.column = key.column, .direction = key.dir}); + } + out.sort = std::move(stored); + } + if (document.filters || !carried.filters.empty() || !carried.groupFilters.empty()) { + FilterSpec filters = document.filters.value_or(FilterSpec{}); + for (auto const& [columnId, filter] : carried.filters) { + filters.columns.insert_or_assign(columnId, filter); + } + filters.groups.insert(filters.groups.end(), carried.groupFilters.begin(), carried.groupFilters.end()); + out.filters = std::move(filters); + } + return glz::write_json(out).value_or(std::string{}); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one sequential pass whose steps share its running state; splitting it would thread that state through parameters. +StateDocument fitState(StateDocument document, TableDescription const& description, FitReport& report) { + using What = FitDrop::What; + std::unordered_map columns; + columns.reserve(description.columns.size()); + for (auto const& column : description.columns) { + columns.emplace(column.info.id, &column); + } + auto const present = [&columns](std::string const& columnId) { return columns.contains(columnId); }; + auto const drop = [&report](What what, std::string columnId, bool isCarried) { + report.dropped.push_back(FitDrop{.what = what, .id = std::move(columnId), .carried = isCarried}); + }; + CarriedState carried; + + // Columns, and the fate of every stored user group, decided here and reported last. + enum class Fate : std::uint8_t { Kept, Carried, Gone }; + std::vector userGroups; + std::vector fates; + if (document.layout) { + ColumnLayoutValue& layout = *document.layout; + std::unordered_set const hidden{layout.hidden.begin(), layout.hidden.end()}; + std::unordered_set seen; + std::string previous; + for (auto const& columnId : layout.order) { + if (!present(columnId) && seen.insert(columnId).second) { + CarriedState::Column column{.id = columnId, .after = previous, .hidden = hidden.contains(columnId)}; + if (auto const width = layout.widths.find(columnId); width != layout.widths.end()) { + column.width = width->second; + } + if (auto const units = layout.units.find(columnId); units != layout.units.end()) { + column.units = units->second; + } + carried.columns.push_back(std::move(column)); + drop(What::Column, columnId, true); + } + previous = columnId; + } + userGroups = std::move(layout.groups); + layout.groups.clear(); + fates.assign(userGroups.size(), Fate::Kept); + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): fates has one slot per user group and at < userGroups.size() + for (std::size_t at = 0; at < userGroups.size(); ++at) { + if (std::ranges::all_of(userGroups[at].columns, present)) { + layout.groups.push_back(userGroups[at]); + } else { + fates[at] = Fate::Carried; + } + } + std::vector ids; + std::vector declaredHidden; + ids.reserve(description.columns.size()); + for (auto const& column : description.columns) { + ids.push_back(column.info.id); + if (!column.shown) { + declaredHidden.push_back(column.info.id); + } + } + ColumnLayout fitter{std::move(ids), std::move(declaredHidden)}; + fitter.apply(layout); + ColumnLayoutValue fitted = fitter.value(); + // The fitted groups are the kept ones, in order, with the dropped ones left out. + std::size_t next = 0; + for (std::size_t at = 0; at < userGroups.size(); ++at) { + if (fates[at] != Fate::Kept) { + continue; + } + if (next < fitted.groups.size() && fitted.groups[next].id == userGroups[at].id) { + ++next; + } else { + fates[at] = Fate::Gone; + } + } + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + layout = std::move(fitted); + } + + if (document.sort) { + SortChain kept; + for (std::size_t index = 0; index < document.sort->size(); ++index) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < document.sort->size() + SortKey const& key = (*document.sort)[index]; + auto const found = columns.find(key.column); + if (found == columns.end()) { + carried.sort.emplace_back(index, key); + drop(What::SortKey, key.column, true); + } else if (!found->second->sortable || std::ranges::contains(kept, key.column, &SortKey::column)) { + drop(What::SortKey, key.column, false); + } else { + kept.push_back(key); + } + } + document.sort = std::move(kept); + } + + // A user group's filter is decided with its group and reported after it. + std::vector> groupFilterDrops(userGroups.size()); + if (document.filters) { + FilterSpec& filters = *document.filters; + auto const infos = columnInfos(description); + // A measure operand compiles against the units the description lists, the only ones a client knows. + Services services; + services.units = registryOf(description).value_or(nullptr); + auto const compiles = [&infos, &description, &services](FilterSpec const& spec) { + return compileFilterGuarded(spec, infos, services, description.groups).has_value(); + }; + for (auto entry = filters.columns.begin(); entry != filters.columns.end();) { + auto const& [columnId, filter] = *entry; + if (!present(columnId)) { + carried.filters.insert_or_assign(columnId, filter); + drop(What::Filter, columnId, true); + } else if (!compiles(FilterSpec{.columns = {{columnId, filter}}, .groups = {}})) { + drop(What::Filter, columnId, false); + } else { + ++entry; + continue; + } + entry = filters.columns.erase(entry); + } + std::vector kept; + for (auto& filter : filters.groups) { + bool const compiled = compiles(FilterSpec{.columns = {}, .groups = {filter}}); + if (!filter.group.empty()) { + if (!std::ranges::contains(description.groups, filter.group, &ColumnGroupInfo::id)) { + drop(What::GroupFilter, filter.group, true); + carried.groupFilters.push_back(std::move(filter)); + } else if (!compiled) { + drop(What::GroupFilter, filter.group, false); + } else { + kept.push_back(std::move(filter)); + } + continue; + } + auto const owner = std::ranges::find_if(userGroups, [&filter](ColumnGroupInfo const& group) { + return detail::sameColumns(group.columns, filter.columns); + }); + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): groupIndex < userGroups.size() + if (owner != userGroups.end()) { + auto const groupIndex = static_cast(std::distance(userGroups.begin(), owner)); + if (fates[groupIndex] == Fate::Carried) { + groupFilterDrops[groupIndex].push_back( + {.what = What::GroupFilter, .id = owner->id, .carried = true}); + carried.groupFilters.push_back(std::move(filter)); + } else if (fates[groupIndex] == Fate::Gone || !compiled) { + groupFilterDrops[groupIndex].push_back( + {.what = What::GroupFilter, .id = owner->id, .carried = false}); + } else { + kept.push_back(std::move(filter)); + } + continue; + } + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + if (!std::ranges::all_of(filter.columns, present)) { + drop(What::GroupFilter, detail::joinedColumns(filter.columns), true); + carried.groupFilters.push_back(std::move(filter)); + } else if (!compiled) { + drop(What::GroupFilter, detail::joinedColumns(filter.columns), false); + } else { + kept.push_back(std::move(filter)); + } + } + filters.groups = std::move(kept); + } + + if (document.layout) { + auto& units = document.layout->units; + for (auto column = units.begin(); column != units.end();) { + auto& dimensions = column->second; + for (auto unit = dimensions.begin(); unit != dimensions.end();) { + if (detail::listsUnit(description, unit->first, unit->second)) { + ++unit; + } else { + drop(What::Unit, column->first + "/" + unit->first, false); + unit = dimensions.erase(unit); + } + } + column = dimensions.empty() ? units.erase(column) : std::next(column); + } + } + + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): fates and groupFilterDrops have one slot per user group and at < userGroups.size() + for (std::size_t at = 0; at < userGroups.size(); ++at) { + if (fates[at] == Fate::Carried) { + drop(What::Group, userGroups[at].id, true); + carried.groups.push_back(userGroups[at]); + } else if (fates[at] == Fate::Gone) { + drop(What::Group, userGroups[at].id, false); + } + report.dropped.insert(report.dropped.end(), groupFilterDrops[at].begin(), groupFilterDrops[at].end()); + } + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + document.carried = std::move(carried); + return document; +} + +} // namespace morph::table diff --git a/src/table/view_cache.cpp b/src/table/view_cache.cpp new file mode 100644 index 000000000..5074bb81e --- /dev/null +++ b/src/table/view_cache.cpp @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) -- source rows are below the snapshot's row count + +namespace morph::table { + +std::span ViewEntry::viewRowOf() const { + build(); + return _viewRowOf; +} + +std::optional ViewEntry::sourceRowOf(RowId const& key) const { + build(); + auto const hash = std::hash{}(key); + auto const [first, last] = + std::ranges::equal_range(_byHash, hash, {}, &std::pair::first); + for (auto at = first; at != last; ++at) { + if (snapshot->rowId(at->second) == key) { + return at->second; + } + } + return std::nullopt; +} + +std::size_t ViewEntry::bytes() const { + auto out = (4 * (view.rows.size() + view.undecided.size())) + _orderKeyBytes; + if (_built.load()) { + out += (sizeof(std::uint32_t) + sizeof(std::pair)) * snapshot->rowCount(); + } + return out; +} + +std::size_t ViewEntry::keysBytes(std::vector const* keys) noexcept { + if (keys == nullptr) { + return 0; + } + auto out = sizeof(std::vector) + ((keys->capacity() - keys->size()) * sizeof(RowId)); + for (auto const& key : *keys) { + out += rowIdBytes(key); + } + return out; +} + +void ViewEntry::build() const { + std::call_once(_once, [this] { + auto const rows = snapshot->rowCount(); + _viewRowOf.assign(rows, detail::kNotInView); + for (std::size_t at = 0; at < view.rows.size(); ++at) { + _viewRowOf[view.rows[at]] = static_cast(at); + } + _byHash.reserve(rows); + for (std::size_t row = 0; row < rows; ++row) { + _byHash.emplace_back(std::hash{}(snapshot->rowId(row)), static_cast(row)); + } + std::ranges::sort(_byHash); + _built.store(true); + }); +} + +ViewCache::Found ViewCache::find(ViewKey const& key, std::shared_ptr const& snapshot, + std::span const> levels, + std::function()> const& compute, + std::uint64_t newness) { + std::vector> const wanted(levels.begin(), levels.end()); + auto const* const identity = snapshot->identity(); + std::shared_ptr running; + // Entries leaving the cache: released after the mutex, since the last of one may free a whole snapshot. + std::vector> released; + { + std::unique_lock lock{_mutex}; + if (auto const found = _entries.find(key); found != _entries.end()) { + auto const& slot = found->second; + if (slot.entry->snapshot->identity() == identity && slot.entry->levels == wanted) { + _hits.fetch_add(1); + _recency.splice(_recency.begin(), _recency, slot.recency); + auto entry = slot.entry; + remeasure(found->second); + bound(released); + lock.unlock(); + released.clear(); + return entry; + } + if (atLeastAsNew(newness, wanted, slot.newness, slot.entry->levels)) { + drop(found, released); + _invalidations.fetch_add(1); + } + } + _misses.fetch_add(1); + for (auto const& other : _running) { + if (other->key == key && other->identity == identity && other->levels == wanted) { + _waits.fetch_add(1); + auto const done = other->done; + lock.unlock(); + return done.get(); + } + } + running = std::make_shared(); + running->key = key; + running->identity = identity; + running->levels = wanted; + running->snapshot = snapshot; + running->newness = newness; + running->order = ++_started; + running->done = running->promise.get_future().share(); + _running.push_back(running); + _computations.fetch_add(1); + } + Found result; + try { + if (_options.onCompute) { + _options.onCompute(); + } + auto computed = compute(); + if (computed) { + result = std::make_shared(snapshot, wanted, std::move(*computed)); + } else { + result = std::unexpected(std::move(computed.error())); + } + } catch (...) { + finish(running, {}); + running->promise.set_exception(std::current_exception()); + throw; + } + finish(running, result); + running->promise.set_value(result); + return result; +} + +void ViewCache::finish(std::shared_ptr const& running, Found const& result) { + std::vector> released; + std::unique_lock lock{_mutex}; + std::erase(_running, running); + if (!result || *result == nullptr) { + return; + } + if (auto const found = _entries.find(running->key); found != _entries.end()) { + auto const& slot = found->second; + // Replaced only by an entry at least as new in its rows and in every order level; of two equally new, + // the later computation's. + bool const newer = atLeastAsNew(running->newness, running->levels, slot.newness, slot.entry->levels); + bool const same = newer && atLeastAsNew(slot.newness, slot.entry->levels, running->newness, running->levels); + if (!newer || (same && slot.order > running->order)) { + return; + } + drop(found, released); + } + _recency.push_front(running->key); + auto [slot, inserted] = _entries.emplace(running->key, Slot{.entry = *result, + .newness = running->newness, + .order = running->order, + .bytes = 0, + .recency = _recency.begin()}); + static_cast(inserted); + remeasure(slot->second); + bound(released); + lock.unlock(); + released.clear(); +} + +void ViewCache::remeasure(Slot& slot) { + auto const now = slot.entry->bytes(); + _held = _held - slot.bytes + now; + slot.bytes = now; + _bytes.store(_held); +} + +bool ViewCache::atLeastAsNew(std::uint64_t newness, std::vector> const& levels, + std::uint64_t otherNewness, + std::vector> const& otherLevels) { + if (newness < otherNewness) { + return false; + } + for (auto const& [level, generation] : otherLevels) { + auto const found = std::ranges::find(levels, level, &std::pair::first); + if (found != levels.end() && found->second < generation) { + return false; + } + } + return true; +} + +void ViewCache::drop(Entries::iterator found, std::vector>& released) { + _held -= found->second.bytes; + _bytes.store(_held); + _recency.erase(found->second.recency); + released.push_back(std::move(found->second.entry)); + _entries.erase(found); +} + +void ViewCache::bound(std::vector>& released) { + while (_held > _options.maxBytes && !_recency.empty()) { + auto const found = _entries.find(_recency.back()); + drop(found, released); + _evictions.fetch_add(1); + } +} + +} // namespace morph::table + +// NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) diff --git a/src/tui/backend.cpp b/src/tui/backend.cpp index 81fb2826d..d6fed760f 100644 --- a/src/tui/backend.cpp +++ b/src/tui/backend.cpp @@ -1,9 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 +#include +#include +#include #include #include #include #include +#include #include #include "tui/container_widgets.hpp" @@ -203,6 +207,11 @@ bool Backend::spotlightMisplaced() const { return _impl->context.spotlightMispla std::string Backend::widthClass() const { return ui::widthClassOf(_impl->context.screen->viewportArea().width); } +bool Backend::copyText(std::string_view text) { + _impl->context.screen->surface().output().copyToClipboard(text); + return true; +} + void Backend::setOnWidthClass(std::function onWidthClass) { _impl->onWidthClass = std::move(onWidthClass); _impl->reported = widthClass(); diff --git a/src/tui/container_widgets.cpp b/src/tui/container_widgets.cpp index 010e03d14..0fb51a48d 100644 --- a/src/tui/container_widgets.cpp +++ b/src/tui/container_widgets.cpp @@ -93,12 +93,26 @@ void StackImpl::setColumnLayout(std::vector extents, int gap, std::vector slots) { _slots = std::move(slots); } + ::core::tui::Size StackImpl::naturalSize() const { auto const inner = innerNaturalSize(); return {.width = inner.width + leadingColumns() + _paddingColumns, .height = inner.height + (2 * _paddingRows)}; } +// NOLINTNEXTLINE(readability-function-cognitive-complexity): sums the children's natural sizes along the axis and takes the maximum across it, with the gap and fill rules in one pass ::core::tui::Size StackImpl::innerNaturalSize() const { + if (!_slots.empty()) { + int width = 0; + int height = 0; + for (auto const [child, slot] : std::views::zip(children(), _slots)) { + if (child->shown() && slot.width > 0) { + width = std::max(width, slot.x + slot.width); + height = std::max(height, requestedSize(*child).height); + } + } + return {.width = width, .height = height}; + } if (_wrap && _axis == ui::Axis::Horizontal && _extents.empty()) { // One line is the natural width; the height is that of the lines at the width the row was last drawn at. // A child with no width takes no gap, as `planWrap` places it, so a shown but empty child does not widen the @@ -146,7 +160,7 @@ ::core::tui::Size StackImpl::innerNaturalSize() const { } int StackImpl::contentMinimumWidth() const { - if (!_extents.empty()) { + if (!_extents.empty() || !_slots.empty()) { return 0; } bool const along = _axis == ui::Axis::Horizontal && !_wrap; @@ -183,7 +197,31 @@ std::vector<::core::tui::Rect> StackImpl::childAreas(::core::tui::Size size) con return areas; } +// NOLINTNEXTLINE(readability-function-cognitive-complexity): assigns each child its area along the axis in one pass; the stretch weights and leftover cells depend on the running offset std::vector<::core::tui::Rect> StackImpl::innerAreas(::core::tui::Size size) const { + if (!_slots.empty()) { + std::vector<::core::tui::Rect> areas(children().size()); + for (auto const [child, slot, area] : std::views::zip(children(), _slots, areas)) { + if (!child->shown() || slot.width <= 0) { + continue; + } + int const height = slot.place.down == ui::Align::Stretch + ? size.height + : std::min(requestedSize(*child).height, size.height); + area = {.x = slot.x, + .y = alignedOffset(slot.place.down, height, size.height), + .width = slot.width, + .height = height}; + // A cell placed at its natural width sits where its column asks; a wider one fills the column. + if (child->placedAcrossColumn() && + (slot.place.across == ui::Align::Center || slot.place.across == ui::Align::End)) { + int const natural = std::min(requestedSize(*child).width, slot.width); + area.x += alignedOffset(slot.place.across, natural, slot.width); + area.width = natural; + } + } + return areas; + } if (_wrap && _axis == ui::Axis::Horizontal && _extents.empty()) { WrappedLines const lines = wrappedLines(size.width); int const rowGap = layout::stepCells(_gapStep, ui::Axis::Vertical); diff --git a/src/tui/container_widgets.hpp b/src/tui/container_widgets.hpp index 8b3783210..439a71c57 100644 --- a/src/tui/container_widgets.hpp +++ b/src/tui/container_widgets.hpp @@ -55,6 +55,10 @@ class StackImpl final : public TuiContainer { /// their column rather than by the row's own alignment; an empty list returns the row to the solver and its own /// alignment. void setColumnLayout(std::vector extents, int gap, std::vector places); + /// One slot per child, in order, for a row of a table whose columns the mount lays out: each child is placed in + /// its slot whatever the others, and a child with no slot, or one of width 0, is given no area. An empty list + /// returns the row to `setColumnLayout`'s extents. + void setCellSlots(std::vector slots); [[nodiscard]] ::core::tui::Size naturalSize() const override; /// Along a row the shown children's content minimums with the gaps and the padding, across a column the largest /// with the padding; zero while no child has a content minimum, and for a table row, which its table places. @@ -93,6 +97,7 @@ class StackImpl final : public TuiContainer { int _drawnWidth = 0; std::vector _extents; std::vector _places; + std::vector _slots; int _extentGap = 0; ui::Align _align = ui::Align::Stretch; ui::Justify _justify = ui::Justify::Start; diff --git a/src/tui/context.cpp b/src/tui/context.cpp index c80f9b0e1..5ba861813 100644 --- a/src/tui/context.cpp +++ b/src/tui/context.cpp @@ -30,6 +30,8 @@ void Context::forget(WidgetBase& widget) { } std::erase_if(spanTables, [&widget](TableImpl const* table) { return static_cast(table) == &widget; }); + std::erase_if(windowTables, + [&widget](TableImpl const* table) { return static_cast(table) == &widget; }); if (pressed == &widget) { pressed = nullptr; } diff --git a/src/tui/context.hpp b/src/tui/context.hpp index 8c8cfbf2a..74f074e02 100644 --- a/src/tui/context.hpp +++ b/src/tui/context.hpp @@ -63,6 +63,9 @@ struct Context { std::vector spotlights; /// The widget an open spotlight rings, drawn in reverse video; null for none. WidgetBase const* spotlit = nullptr; + /// Tables over a `TableSource` whose last frame found the rows or the columns in view changed: `fit` reports + /// them before any size is asked, so the mount realizes them outside a frame's drawing. + std::vector windowTables; /// The clock every widget reads the time from (a table telling a double click from two clicks); a test may /// replace it. std::function now = [] { return std::chrono::steady_clock::now(); }; diff --git a/src/tui/list_widgets.cpp b/src/tui/list_widgets.cpp index b1a58f23b..7c9b49952 100644 --- a/src/tui/list_widgets.cpp +++ b/src/tui/list_widgets.cpp @@ -1185,6 +1185,250 @@ bool MenuButtonImpl::triggerDrawn() const { return view().screen() != nullptr && bool MenuButtonImpl::listUsable() const { return actionable() && triggerDrawn() && _popupRows > 0; } +/// A `MenuPopup`'s list, shown as an overlay. It has no parent, so the keys it leaves go no further. +class MenuPopup::Popup final : public ::core::tui::List { +public: + explicit Popup(MenuPopup& owner) : _owner{&owner} {} + + void render(::core::tui::Canvas& canvas) override { + _owner->_top = scrolledTop(*this, {.top = _owner->_top, .rows = canvas.height()}); + paintRows(*this, _owner->_top, {.reachable = true, .focused = true}, canvas); + } + + [[nodiscard]] ::core::tui::Size preferredSize() const override { return _owner->size(); } + + [[nodiscard]] bool visible() const noexcept override { return List::visible() && _owner->usable(); } + + /// Choosing may end in a handler that destroys the owner and this list with it, so nothing is touched after it. + [[nodiscard]] EventResult onEvent(::core::tui::InputEvent const& event) override { + auto* const owner = _owner; + if (escapeEndsDrag(owner->_owner->context(), event)) { + return EventResult::Handled; + } + if (!owner->usable()) { + owner->close(); + return EventResult::Ignored; + } + if (auto const* mouse = std::get_if<::core::tui::MouseEvent>(&event)) { + return pointer(*mouse); + } + if (auto const* key = std::get_if<::core::tui::KeyEvent>(&event)) { + if (auto const handled = levelKey(*key)) { + return *handled; + } + } + return List::onEvent(event); + } + + void onBlur() override { _owner->close(); } + +private: + [[nodiscard]] std::optional levelKey(::core::tui::KeyEvent const& key) { + auto* const owner = _owner; + if (isActivation(key)) { + owner->pick(selectedIndex()); + return EventResult::Handled; + } + if (isKey(key, KeyCode::Escape)) { + owner->close(); + return EventResult::Handled; + } + if (isKey(key, KeyCode::Tab)) { + owner->close(); + return EventResult::Ignored; + } + if (!isPlain(key)) { + return std::nullopt; + } + auto const& level = menuLevel(owner->_entries, owner->_path); + if (isKey(key, KeyCode::Right) && selectedIndex() < level.size() && !level.at(selectedIndex()).items.empty()) { + owner->enter(selectedIndex()); + return EventResult::Handled; + } + if ((isKey(key, KeyCode::Left) || isKey(key, KeyCode::Backspace)) && !owner->_path.empty()) { + owner->leave(); + return EventResult::Handled; + } + return std::nullopt; + } + + [[nodiscard]] EventResult pointer(::core::tui::MouseEvent const& mouse) { + using Type = ::core::tui::MouseEvent::Type; + if (mouse.type == Type::ScrollUp || mouse.type == Type::ScrollDown) { + if (mouse.type == Type::ScrollUp) { + selectPrevious(); + } else { + selectNext(); + } + invalidate(); + return EventResult::Handled; + } + if (mouse.type == Type::Press) { + _owner->_owner->context().endPress(); + _pressed = mouse.button == 0; + return EventResult::Handled; + } + if (mouse.type != Type::Release || !std::exchange(_pressed, false)) { + return EventResult::Handled; + } + auto const bounds = screenBounds(); + ::core::tui::Point const cell{.x = mouse.x - 1, .y = mouse.y - 1}; + if (cell.x >= 0 && cell.y >= 0 && cell.x < bounds.width && cell.y < bounds.height) { + _owner->pick(_owner->_top + static_cast(cell.y)); + } + return EventResult::Handled; + } + + MenuPopup* _owner; + bool _pressed = false; +}; + +MenuPopup::MenuPopup(WidgetBase& owner) : _owner{&owner}, _list{std::make_unique(*this)} {} + +MenuPopup::~MenuPopup() { + if (!_open) { + return; + } + _open = false; + auto& context = _owner->context(); + std::erase(context.popups, _owner); + if (context.screen->focusedComponent() == _list.get()) { + static_cast(focusWidget(context, nullptr)); + } + context.screen->hideOverlay(*_list); +} + +::core::tui::Component const* MenuPopup::list() const noexcept { return _open ? _list.get() : nullptr; } + +// The list takes the focus last: the focus leaving its old place may run a handler, which may destroy the owner. +bool MenuPopup::open(std::vector entries, ::core::tui::Rect anchor, + std::function)> onChoose) { + if (_open || !_owner->actionable() || entries.empty()) { + return false; + } + _entries = std::move(entries); + _onChoose = std::move(onChoose); + _anchor = anchor; + _path.clear(); + _top = 0; + auto const where = placement(); + if (where.rows == 0) { + return false; + } + fill(0); + _rows = where.rows; + _at = where.origin; + _open = true; + auto& context = _owner->context(); + context.popups.push_back(_owner); + context.screen->showOverlay(*_list, where.origin); + _owner->refresh(); + return focusPopup(context, *_owner, *_list); +} + +// Nothing here runs a handler: the focus going back to the owner leaves only the list, whose blur ends here at once. +void MenuPopup::close() { + if (!_open) { + return; + } + _open = false; + _path.clear(); + auto& context = _owner->context(); + std::erase(context.popups, _owner); + auto& screen = *context.screen; + bool const hadFocus = screen.focusedComponent() == _list.get(); + screen.hideOverlay(*_list); + _owner->refresh(); + if (hadFocus) { + static_cast(focusWidget(context, _owner->view().screen() != nullptr ? _owner : nullptr)); + } +} + +void MenuPopup::pick(std::size_t index) { + auto const& level = menuLevel(_entries, _path); + if (index >= level.size() || !_owner->actionable()) { + return; + } + if (!level.at(index).items.empty()) { + if (level.at(index).enabled) { + enter(index); + } + return; + } + auto choice = menuChoice(_entries, _path, index); + if (!choice) { + return; + } + // A copy: the handler may destroy the owner, and this popup with it. + auto const handler = _onChoose; + close(); + if (handler) { + handler(std::move(*choice)); + } +} + +void MenuPopup::enter(std::size_t index) { + _path.push_back(index); + _top = 0; + fill(0); + place(); +} + +void MenuPopup::leave() { + if (_path.empty()) { + return; + } + auto const from = _path.back(); + _path.pop_back(); + _top = 0; + fill(from); + place(); +} + +// The highlight starts on @p highlighted, or the first entry after it the cursor can rest on. +void MenuPopup::fill(std::size_t highlighted) { + auto rows = menuRows(menuLevel(_entries, _path), menuPathEnabled(_entries, _path)); + auto const count = rows.size(); + _list->setItems(std::move(rows)); + if (count > 0) { + _list->setSelectedIndex(std::min(highlighted, count - 1)); + if (!_list->items().at(_list->selectedIndex()).enabled) { + _list->selectNext(); + } + } + _owner->refresh(); +} + +MenuPopup::Placement MenuPopup::placement() const { + auto const viewport = _owner->context().screen->viewportArea(); + int const count = static_cast(menuLevel(_entries, _path).size()); + int const below = std::max(0, viewport.y + viewport.height - (_anchor.y + _anchor.height)); + int const above = std::max(0, _anchor.y - viewport.y); + int const width = size().width; + Placement where{.origin = {.x = popupColumn(_anchor, viewport, width), .y = _anchor.y + _anchor.height}, + .rows = std::min(count, below)}; + if (below < count && above > below) { + where.rows = std::min(count, above); + where.origin.y = _anchor.y - where.rows; + } + return where; +} + +void MenuPopup::place() { + auto& screen = *_owner->context().screen; + auto const where = placement(); + _rows = where.rows; + if (where.origin != _at || !screen.isOverlayVisible(*_list)) { + _at = where.origin; + screen.showOverlay(*_list, where.origin); + } +} + +// As wide as the widest entry of any level and the marker before it. +::core::tui::Size MenuPopup::size() const { return {.width = widestMenuRow(_entries) + 2, .height = _rows}; } + +bool MenuPopup::usable() const { return _owner->actionable() && _owner->view().screen() != nullptr && _rows > 0; } + void TabsImpl::setTabs(std::vector const& tabs) { _labels = tabs; refresh(); diff --git a/src/tui/list_widgets.hpp b/src/tui/list_widgets.hpp index 6c7a39c1d..057358686 100644 --- a/src/tui/list_widgets.hpp +++ b/src/tui/list_widgets.hpp @@ -294,6 +294,61 @@ class MenuButtonImpl final : public TuiWidget { bool _open = false; }; +/// A menu's entries shown as an overlay list for a widget that is not a menu (a table's header): it opens below an +/// anchor the owner names (above it when there is more room there), takes the focus, and drills into submenus as a +/// button-style menu's list does. Choosing an entry, Esc, or the focus leaving closes it and hands the focus back to +/// the owner; Tab closes it and leaves the key to the frontend. While open, the owner is in `Context::popups`, and +/// answers `closePopup` and `openPopup` from `close` and `list`. +class MenuPopup { +public: + explicit MenuPopup(WidgetBase& owner); + /// Closes the list, if open, taking the focus off it first. + ~MenuPopup(); + MenuPopup(MenuPopup const&) = delete; + MenuPopup& operator=(MenuPopup const&) = delete; + MenuPopup(MenuPopup&&) = delete; + MenuPopup& operator=(MenuPopup&&) = delete; + + /// Opens @p entries at the top level below @p anchor, in screen cells; @p onChoose gets the chosen entry's path. + /// Whether the list is open and has the focus afterwards: none opens without entries, or without room. + bool open(std::vector entries, ::core::tui::Rect anchor, + std::function)> onChoose); + /// Closes the list, running no handler. + void close(); + [[nodiscard]] bool isOpen() const noexcept { return _open; } + /// The open list, or null. + [[nodiscard]] ::core::tui::Component const* list() const noexcept; + /// The entries the list was opened with. + [[nodiscard]] std::vector const& entries() const noexcept { return _entries; } + +private: + class Popup; + struct Placement { + ::core::tui::Point origin{}; + int rows = 0; + }; + /// Opens the submenu of, or chooses, the entry at @p index of the level shown. Choosing may destroy the owner. + void pick(std::size_t index); + void enter(std::size_t index); + void leave(); + void fill(std::size_t highlighted); + [[nodiscard]] Placement placement() const; + void place(); + [[nodiscard]] ::core::tui::Size size() const; + [[nodiscard]] bool usable() const; + + WidgetBase* _owner; + std::vector _entries; + std::vector _path; + std::function)> _onChoose; + std::unique_ptr<::core::tui::List> _list; + ::core::tui::Rect _anchor{}; + ::core::tui::Point _at{}; + int _rows = 0; + std::size_t _top = 0; + bool _open = false; +}; + /// Tabs: a bar above the body. Left and Right while the tabs hold the focus select the previous and the next tab, /// and a click on a tab's label selects it and focuses the tabs; a key a focused page widget leaves, and a press on /// the body, leave the tabs alone. diff --git a/src/tui/table_widget.cpp b/src/tui/table_widget.cpp index 85ca52c86..b9dc673f3 100644 --- a/src/tui/table_widget.cpp +++ b/src/tui/table_widget.cpp @@ -3,11 +3,14 @@ #include "tui/table_widget.hpp" #include +#include #include #include #include #include #include +#include +#include #include #include #include @@ -35,14 +38,59 @@ constexpr int kBoxWidth = 3; constexpr int kColumnGap = 1; /// The cells of a sort mark after a header label: a space and an arrow. constexpr int kSortMark = 2; +/// The cells of a filter button at a header's end: a space and the button. +constexpr int kFilterMark = 2; +/// A filter button, empty and filled. +constexpr std::string_view kFilterEmpty = "\u25BF"; +constexpr std::string_view kFilterFilled = "\u25BE"; +/// What the gutter's last cell shows for a row an action is working on, and for a row another user holds. +constexpr std::string_view kBusyGlyph = "\u2026"; +constexpr std::string_view kLockGlyph = "#"; +/// The gutter cells a busy or locked glyph takes: the glyph, and a gap, so the ellipsis is not read as the first +/// cell's truncation. +constexpr int kMarkCells = 2; +/// What a busy or locked row says on hover when its marks carry no text of their own. +constexpr std::string_view kBusyText = "Saving this row"; +constexpr std::string_view kLockText = "Locked by another user"; +/// The button at the header line's end that opens the table's menu. +constexpr std::string_view kTableMenu = "\u22EF"; +/// The cells the header line keeps for the table menu: a gap and the button. +constexpr int kTableMenuRoom = 2; /// The width a column that may shrink gives up to: room for a few characters and an ellipsis. constexpr int kShrunkColumn = 4; /// How soon a second click on a row must follow the first to make a double click. constexpr auto kDoubleClick = std::chrono::milliseconds{500}; +/// What a cell whose level has not loaded draws, and one whose level failed to. +constexpr std::string_view kUnloadedMark = "···"; +constexpr std::string_view kFailedMark = "!"; +constexpr std::string_view kRetry = "[Retry]"; +/// What separates the parts of the status line. +constexpr std::string_view kStatusGap = " "; /// Whether @p key is the special key @p code, not a typed character whose codepoint has the same value. bool isKey(::core::tui::KeyEvent const& key, KeyCode code) noexcept { return key.codepoint == 0 && key.key == code; } +/// A codepoint as UTF-8. +std::string utf8Of(char32_t codepoint) { + std::string out; + if (codepoint < 0x80) { + out += static_cast(codepoint); + } else if (codepoint < 0x800) { + out += static_cast(0xC0 | (codepoint >> 6)); + out += static_cast(0x80 | (codepoint & 0x3F)); + } else if (codepoint < 0x10000) { + out += static_cast(0xE0 | (codepoint >> 12)); + out += static_cast(0x80 | ((codepoint >> 6) & 0x3F)); + out += static_cast(0x80 | (codepoint & 0x3F)); + } else { + out += static_cast(0xF0 | (codepoint >> 18)); + out += static_cast(0x80 | ((codepoint >> 12) & 0x3F)); + out += static_cast(0x80 | ((codepoint >> 6) & 0x3F)); + out += static_cast(0x80 | (codepoint & 0x3F)); + } + return out; +} + /// The lines a row takes: its natural height, and a line even when it has nothing to show. int rowHeight(WidgetBase const& row) { return std::max(1, row.naturalSize().height); } @@ -105,6 +153,15 @@ void TableImpl::setRowHeading(ui::Widget& row) { refresh(); } +void TableImpl::setRowSummary(ui::Widget& row) { + auto const& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setRowSummary of a widget that is not this table's row"}; + } + _summaries.insert(&base); + refresh(); +} + void TableImpl::setRowSpans(ui::Widget& row, std::vector const& spans) { auto& base = WidgetBase::of(row); if (base.container() != this) { @@ -122,12 +179,16 @@ void TableImpl::setRowSpans(ui::Widget& row, std::vector const& spa } int TableImpl::heightOf(WidgetBase const& row) const { + if (_source) { + return 1; + } auto const extra = _extraLines.find(&row); return rowHeight(row) + (extra == _extraLines.end() ? 0 : extra->second); } // The rows' order decides coverage, so it is worked out here, from the rows as they are, and never when a row is told // its spans: rows moving under an unchanged span change what is covered. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): plans spans in one pass in the rows' order: the spans carried from earlier rows decide what each next row covers void TableImpl::planSpans() { if (_spans.empty() && _plan.empty()) { std::erase(context().spanTables, this); @@ -149,10 +210,12 @@ void TableImpl::planSpans() { } auto const cells = cellsOf(rows.at(index)); for (ui::RowSpan const& span : found->second) { - if (span.column >= _columns.size() || span.column >= cells.size() || span.rows < 2 || + if (span.column >= _columns.size() || span.column >= cells.size() || span.rows == 0 || coveredUntil.at(span.column) > index) { continue; } + // The columns it covers, its own and the next ones, clipped at the last column. + std::size_t const wide = std::max(1, std::min(span.columns, _columns.size() - span.column)); std::size_t last = std::min(index + span.rows, rows.size()) - 1; for (std::size_t between = index + 1; between <= last; ++between) { if (isHeading(rows.at(between))) { @@ -160,19 +223,24 @@ void TableImpl::planSpans() { break; } } - if (last == index) { + if (last == index && wide == 1) { continue; } - coveredUntil.at(span.column) = last + 1; + for (std::size_t column = span.column; column < span.column + wide; ++column) { + coveredUntil.at(column) = last + 1; + } plan.push_back({.origin = rows.at(index), .cell = cells.at(span.column), .column = span.column, + .columns = wide, .first = index, .last = last}); - for (std::size_t between = index + 1; between <= last; ++between) { + for (std::size_t between = index; between <= last; ++between) { auto const coveredCells = cellsOf(rows.at(between)); - if (span.column < coveredCells.size()) { - covered.insert(coveredCells.at(span.column)); + for (std::size_t column = span.column; column < span.column + wide; ++column) { + if ((between != index || column != span.column) && column < coveredCells.size()) { + covered.insert(coveredCells.at(column)); + } } } } @@ -226,8 +294,8 @@ std::vector<::core::tui::Rect> TableImpl::spanAreas(::core::tui::Size size, std::vector<::core::tui::Rect>& block = blocks != nullptr ? *blocks : unused; block.assign(_plan.size(), {}); auto const rows = shownChildren(); - auto const widths = columnWidths(size.width); - int const header = _showHeader ? 1 : 0; + auto const widths = columnWidths(size.width - menuRoom()); + int const header = headerLines(); // The line of each row as if every row were drawn: the first one drawn starts under the header, the ones above it // before that. std::vector start(rows.size(), 0); @@ -258,11 +326,14 @@ std::vector<::core::tui::Rect> TableImpl::spanAreas(::core::tui::Size size, ui::Align const down = _columns.at(place.column).valign; int const space = bottom - top; int const height = down == ui::Align::Stretch ? space : std::min(requestedSize(*place.cell).height, space); - area = {.x = left, - .y = top + alignedOffset(down, height, space), - .width = widths.at(place.column), - .height = height}; - lines = {.x = left, .y = top, .width = widths.at(place.column), .height = space}; + // Across the columns it covers and the gaps between them. + int across = widths.at(place.column); + for (std::size_t index = place.column + 1; index < place.column + place.columns && index < widths.size(); + ++index) { + across += kColumnGap + widths.at(index); + } + area = {.x = left, .y = top + alignedOffset(down, height, space), .width = across, .height = height}; + lines = {.x = left, .y = top, .width = across, .height = space}; } return areas; } @@ -283,7 +354,7 @@ WidgetBase* TableImpl::spanOriginAt(::core::tui::Point cell) const { std::size_t TableImpl::dataPlace(std::span rows, std::size_t place, Direction direction) const { auto const data = [&](std::size_t candidate) { - return candidate < rows.size() && !isHeading(rows.subspan(candidate).front()); + return candidate < rows.size() && !isPassive(rows.subspan(candidate).front()); }; for (std::size_t index = place; index < rows.size(); direction == Direction::Forward ? ++index : --index) { if (data(index)) { @@ -305,11 +376,13 @@ std::size_t TableImpl::dataPlace(std::span rows, std::size_t return place; } -int TableImpl::gutter() const noexcept { return _selectColumn ? kSelectGutter : kGutter; } +int TableImpl::gutter() const noexcept { + return (_selectColumn ? kSelectGutter : kGutter) + (_markGutter ? kMarkCells : 0); +} std::string TableImpl::headerBox() const { auto const rows = shownChildren(); - auto const data = std::ranges::count_if(rows, [this](WidgetBase const* row) { return !isHeading(row); }); + auto const data = std::ranges::count_if(rows, [this](WidgetBase const* row) { return !isPassive(row); }); auto const marked = std::ranges::count_if(rows, [this](WidgetBase const* row) { return isMarked(row); }); if (marked == 0) { return "[ ]"; @@ -318,56 +391,414 @@ std::string TableImpl::headerBox() const { } void TableImpl::setSelection(std::vector const& selection) { + _viewExcept.reset(); _selection = selection; refresh(); } +void TableImpl::setSelectionView(std::vector const& except) { + _viewExcept = except; + refresh(); +} + +void TableImpl::setOnStatusEntry(std::function onStatusEntry) { + _onStatusEntry = std::move(onStatusEntry); +} + +void TableImpl::setRowMarks(ui::Widget& row, ui::RowMarks const& marks) { + auto& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setRowMarks of a widget that is not this table's row"}; + } + if (marks == ui::RowMarks{}) { + _marks.erase(&base); + } else { + _marks.insert_or_assign(&base, marks); + } + base.applyRowMuted(marks.unmatched); + // The marks' text wins over the row's own tooltip while it lasts; a busy or locked row always says why. + std::string_view said = marks.tooltip; + if (said.empty()) { + if (marks.locked) { + said = kLockText; + } else if (marks.busy) { + said = kBusyText; + } + } + base.applyMarksTooltip(said); + // The gutter takes cells for the glyph from the first busy or locked row on, and keeps it, so the columns do not + // move as rows start and stop being busy. + _markGutter = _markGutter || marks.busy || marks.locked; + refresh(); +} + void TableImpl::setOnSelectionChange( std::function, ui::SelectionChange)> onSelectionChange) { _onSelectionChange = std::move(onSelectionChange); } +void TableImpl::setOnSelectAll(std::function onSelectAll) { _onSelectAll = std::move(onSelectAll); } + void TableImpl::setOnActivate(std::function onActivate) { _onActivate = std::move(onActivate); } -void TableImpl::setSort(std::optional sort) { - _sort = sort; +void TableImpl::setSort(std::vector const& chain) { + _chain = chain; + refresh(); +} + +void TableImpl::setOnSort(std::function onSort) { _onSort = std::move(onSort); } + +void TableImpl::setMenu(std::function(std::optional)> entries, + std::function, std::vector)> onChoose) { + _menu = std::move(entries); + _onMenu = std::move(onChoose); + refresh(); +} + +void TableImpl::setVisibleColumns(std::vector const& visible) { + _visible = visible; + auto const order = visibleOrder(); + if (_headerFocus && std::ranges::find(order, *_headerFocus) == order.end()) { + _headerFocus.reset(); + } + refresh(); +} + +void TableImpl::setOnColumnMove(std::function handler) { + _onColumnMove = std::move(handler); +} + +void TableImpl::setOnFilter(std::function handler) { _onFilter = std::move(handler); } + +void TableImpl::setFiltered(std::vector const& columns) { + _filtered = columns; + refresh(); +} + +void TableImpl::setColumnGroups(std::vector const& groups) { + _groups = groups; + refresh(); +} + +void TableImpl::setBands(std::vector const& runs) { + _bands = runs; refresh(); } -void TableImpl::setOnSort(std::function onSort) { _onSort = std::move(onSort); } +void TableImpl::setOnGroupFilter(std::function handler) { _onGroupFilter = std::move(handler); } + +void TableImpl::setOnCopy(std::function onCopy) { _onCopy = std::move(onCopy); } + +std::optional TableImpl::chainPlace(std::size_t index) const { + auto const found = std::ranges::find(_chain, index, &ui::TableSort::column); + if (found == _chain.end()) { + return std::nullopt; + } + return static_cast(std::distance(_chain.begin(), found)); +} std::string TableImpl::headerText(std::size_t index) const { - std::string text = _columns.at(index).label; - if (_sort && _sort->column == index) { - text += _sort->direction == ui::SortDirection::Ascending ? " ▲" : " ▼"; + std::string text = ui::headerText(_columns.at(index).label, _columns.at(index).unit); + if (auto const place = chainPlace(index)) { + text += ui::sortMarkText(_chain.at(*place).direction, *place + 1, _chain.size()); } return text; } -int TableImpl::headerWidth(ui::TableColumn const& column) { - return displayWidth(column.label) + (column.sortable ? kSortMark : 0); +std::string TableImpl::headerName(std::size_t index) const { + std::string name = ui::headerAccessibleName(_columns.at(index).label, _columns.at(index).unit); + if (_columns.at(index).filterable && std::ranges::find(_filtered, index) != _filtered.end()) { + name += ", filtered"; + } + return name; +} + +std::string TableImpl::headerDescription(std::size_t index) const { + auto const place = chainPlace(index); + return place ? ui::sortDescription(_chain.at(*place).direction, *place + 1, _chain.size()) : std::string{}; +} + +// A one-key mark fits the room a sortable header keeps; a longer chain's places widen the headers it marks. +int TableImpl::headerWidth(ui::TableColumn const& column) const { + int mark = column.sortable ? kSortMark : 0; + if (column.sortable && _chain.size() > 1) { + mark = displayWidth(ui::sortMarkText(ui::SortDirection::Ascending, _chain.size(), _chain.size())); + } + return displayWidth(ui::headerText(column.label, column.unit)) + mark + (column.filterable ? kFilterMark : 0); +} + +int TableImpl::headerLines() const noexcept { + if (!_showHeader) { + return 0; + } + return bandLines() + (_groups.empty() ? 1 : 2); +} + +int TableImpl::bandLines() const noexcept { + std::size_t levels = 0; + for (ui::BandRun const& run : _bands) { + levels = std::max(levels, run.level + 1); + } + return static_cast(levels); +} + +std::vector TableImpl::visibleOrder() const { + if (!_visible.empty()) { + return _visible; + } + std::vector order(_columns.size()); + // NOLINTNEXTLINE(modernize-use-ranges): std::ranges::iota is missing from Emscripten's libc++. + std::iota(order.begin(), order.end(), std::size_t{0}); + return order; +} + +void TableImpl::clickHeader(int x, ::core::tui::Modifier modifiers) { + if (_menu && x == _size.width - 1) { + openMenu(std::nullopt); + return; + } + for (DrawnColumn const& drawn : drawnColumns(_size.width)) { + int const left = gutter() + drawn.x; + if (x < left || x >= left + drawn.width) { + continue; + } + if (std::optional const place = visiblePlace(drawn.column); + _onCellSelect && place && + ::core::tui::hasModifier(::core::tui::withoutLockKeys(modifiers), ::core::tui::Modifier::Ctrl)) { + if (_total > 0) { + auto const handler = _onCellSelect; + handler(0, *place, _total - 1, *place); + } + return; + } + ui::TableColumn const& column = _columns.at(drawn.column); + if (column.filterable && x == left + drawn.width - 1) { + if (auto const handler = _onFilter) { + handler(drawn.column); + } + return; + } + auto const handler = _onSort; + if (column.sortable && handler) { + bool const shift = + ::core::tui::hasModifier(::core::tui::withoutLockKeys(modifiers), ::core::tui::Modifier::Shift); + handler(drawn.column, shift ? ui::HeaderClick::Shift : ui::HeaderClick::Plain); + } + return; + } +} + +// A group's span is the drawn columns at the visible places it names; its filter button is the span's last cell. +std::optional TableImpl::groupFilterX(std::size_t group) const { + if (group >= _groups.size()) { + return std::nullopt; + } + auto const order = visibleOrder(); + ui::TableColumnGroup const& shown = _groups.at(group); + int right = -1; + for (DrawnColumn const& column : drawnColumns(_size.width)) { + auto const place = std::ranges::find(order, column.column); + auto const index = static_cast(std::distance(order.begin(), place)); + if (place != order.end() && index >= shown.first && index < shown.first + shown.count) { + right = std::max(right, gutter() + column.x + column.width - 1); + } + } + return right >= 0 ? std::optional{right} : std::nullopt; } -void TableImpl::clickHeader(int x) { - int left = gutter(); - for (auto const [index, width] : std::views::zip(std::views::iota(std::size_t{0}), columnWidths(_size.width))) { - if (x >= left && x < left + width) { - auto const handler = _onSort; - if (_columns.at(index).sortable && handler) { - handler(index); +void TableImpl::clickGroups(int x) { + for (std::size_t group = 0; group < _groups.size(); ++group) { + if (groupFilterX(group) == x) { + if (auto const handler = _onGroupFilter) { + handler(group); } return; } - left += width + kColumnGap; } } +void TableImpl::focusHeader() { + auto const order = visibleOrder(); + if (order.empty()) { + return; + } + _headerFocus = order.front(); + if (!_chain.empty() && std::ranges::find(order, _chain.front().column) != order.end()) { + _headerFocus = _chain.front().column; + } + refresh(); +} + +void TableImpl::openMenu(std::optional column) { + if (!_menu) { + return; + } + auto const bounds = view().screenBounds(); + int const line = bounds.y + headerLines() - 1; + ::core::tui::Rect anchor{.x = bounds.x + bounds.width - 1, .y = line, .width = 1, .height = 1}; + if (column) { + for (DrawnColumn const& drawn : drawnColumns(_size.width)) { + if (drawn.column == *column) { + anchor = {.x = bounds.x + gutter() + drawn.x, .y = line, .width = drawn.width, .height = 1}; + } + } + } + auto const entries = _menu; + auto const onChoose = _onMenu; + // A menu asked for while another is open replaces it: a right click on another header moves the menu there. + _menuPopup.close(); + static_cast(_menuPopup.open(entries(column), anchor, [onChoose, column](std::vector path) { + if (onChoose) { + onChoose(column, std::move(path)); + } + })); +} + +void TableImpl::setCellMenu(std::function(ui::Key const&, std::size_t)> entries, + std::function const&)> chosen) { + _cellMenu = std::move(entries); + _cellChosen = std::move(chosen); +} + +void TableImpl::openCellMenu(WidgetBase const& row, std::size_t column) { + std::optional const rowKey = keyOf(&row); + if (!_cellMenu || !rowKey || isPassive(&row)) { + return; + } + // A row already selected keeps the selection, so the menu acts on every selected row. + if (_mode != ui::SelectionMode::None && !isMarked(&row) && + !change(std::vector{*rowKey}, ui::SelectionChange::Replace)) { + return; + } + auto const bounds = view().screenBounds(); + ::core::tui::Rect anchor{.x = bounds.x, .y = bounds.y, .width = 1, .height = 1}; + for (auto const [child, area] : std::views::zip(children(), childAreas(_size))) { + if (child == &row) { + anchor.y = bounds.y + area.y; + } + } + for (DrawnColumn const& drawn : drawnColumns(_size.width)) { + if (drawn.column == column) { + anchor.x = bounds.x + gutter() + drawn.x; + anchor.width = std::max(1, drawn.width); + } + } + auto const entries = _cellMenu; + auto const chosen = _cellChosen; + std::vector shown = entries(*rowKey, column); + _menuPopup.close(); + static_cast(_menuPopup.open(std::move(shown), anchor, + [chosen, key = *rowKey, column](std::vector const& path) { + if (chosen) { + chosen(key, column, path); + } + })); +} + +EventResult TableImpl::cellKey(::core::tui::KeyEvent const& key) { + WidgetBase const* const row = _focusCell ? rowAtView(_focusCell->first) : nullptr; + std::optional const rowKey = row == nullptr ? std::nullopt : keyOf(row); + if (!_cellMenu || !rowKey || !_focusCell) { + return EventResult::Ignored; + } + std::size_t const column = _focusCell->second; + if (matchesChord("Shift+F10", key) || isKey(key, KeyCode::Menu)) { + openCellMenu(*row, column); + return EventResult::Handled; + } + if (std::ranges::none_of(_cellMenuKeys, [&key](std::string const& chord) { return matchesChord(chord, key); })) { + return EventResult::Ignored; + } + auto const entries = _cellMenu; + auto const chosen = _cellChosen; + std::vector path; + std::function const&)> const find = [&](std::vector const& level) { + for (std::size_t at = 0; at < level.size(); ++at) { + ui::MenuEntry const& entry = level.at(at); + if (entry.separator || entry.heading || !entry.enabled) { + continue; + } + path.push_back(at); + if (entry.items.empty() ? !entry.keys.empty() && matchesChord(entry.keys, key) : find(entry.items)) { + return true; + } + path.pop_back(); + } + return false; + }; + if (!chosen || !find(entries(*rowKey, column))) { + return EventResult::Ignored; + } + chosen(*rowKey, column, path); + return EventResult::Handled; +} + +// Left and Right walk the visible columns; a move is reported one place over and the table waits for the mount to +// rearrange it, the focus staying on the moved column. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): Left, Right, Down and the chords each move the header focus; the branches share the visible order and the focused place +EventResult TableImpl::headerKey(::core::tui::KeyEvent const& key) { + if (!_headerFocus) { + return EventResult::Ignored; + } + auto const order = visibleOrder(); + auto const found = std::ranges::find(order, *_headerFocus); + if (found == order.end()) { + _headerFocus.reset(); + return EventResult::Ignored; + } + auto const place = static_cast(std::distance(order.begin(), found)); + std::size_t const column = *_headerFocus; + if (isKey(key, KeyCode::Down) && ::core::tui::withoutLockKeys(key.modifiers) == ::core::tui::Modifier::None) { + _headerFocus.reset(); + refresh(); + return EventResult::Handled; + } + if (matchesChord("Left", key) || matchesChord("Right", key)) { + bool const right = matchesChord("Right", key); + if (right && place + 1 < order.size()) { + _headerFocus = order.at(place + 1); + } else if (!right && place > 0) { + _headerFocus = order.at(place - 1); + } + refresh(); + return EventResult::Handled; + } + bool const shifted = matchesChord("Shift+Enter", key) || matchesChord("Shift+Space", key); + if (shifted || matchesChord("Enter", key) || matchesChord("Space", key)) { + if (auto const handler = _onSort; handler && _columns.at(column).sortable) { + handler(column, shifted ? ui::HeaderClick::Shift : ui::HeaderClick::Plain); + } + return EventResult::Handled; + } + bool const later = matchesChord("Ctrl+Shift+Right", key); + if (later || matchesChord("Ctrl+Shift+Left", key)) { + if (auto const handler = _onColumnMove; handler && (later ? place + 1 < order.size() : place > 0)) { + handler(column, later ? place + 1 : place - 1); + } + return EventResult::Handled; + } + if (matchesChord("Shift+F10", key) || isKey(key, KeyCode::Menu)) { + openMenu(column); + return EventResult::Handled; + } + return EventResult::Ignored; +} + // The cursor goes to the row that took the removed one's place, or to the last row. void TableImpl::childForgotten(WidgetBase& child) { _keys.erase(&child); _headings.erase(&child); + _summaries.erase(&child); + _marks.erase(&child); _spans.erase(&child); _extraLines.erase(&child); + _viewRows.erase(&child); + _cellColumns.erase(&child); + _loads.erase(&child); + _accents.erase(&child); + _editors.erase(&child); + _cellMarks.erase(&child); + _modifiedRows.erase(&child); // The plan points at rows and at the cells lifted out of them, and is rebuilt only by the next fit: until then a // click would hit-test a block of a row that is gone, and read its freed cell. _plan.clear(); @@ -405,10 +836,13 @@ std::vector TableImpl::naturalWidths() const { if (cells == nullptr || !row->shown() || isHeading(row)) { continue; } - for (auto const [width, cell] : std::views::zip(widths, cells->children())) { - // A hidden cell is drawn as nothing, so it asks for no room. - if (cell->shown()) { - width = std::max(width, requestedSize(*cell).width); + std::size_t position = 0; + for (auto const* const cell : cells->children()) { + auto const column = columnOf(row, cell, position++); + // A hidden cell is drawn as nothing, and a mark in place of a cell widens nothing, so neither asks for + // room. + if (column && *column < widths.size() && cell->shown() && loadOf(row, *column) == ui::CellLoad::Loaded) { + widths.at(*column) = std::max(widths.at(*column), requestedSize(*cell).width); } } } @@ -427,12 +861,16 @@ std::vector TableImpl::leastWidths() const { if (cells == nullptr || !row->shown() || isHeading(row)) { continue; } - for (auto const [width, column, cell] : std::views::zip(widths, _columns, cells->children())) { - if (!column.wrap || !cell->shown()) { + std::size_t position = 0; + for (auto const* const cell : cells->children()) { + auto const column = columnOf(row, cell, position++); + if (!column || *column >= widths.size() || !_columns.at(*column).wrap || !cell->shown() || + loadOf(row, *column) != ui::CellLoad::Loaded) { continue; } auto const* const text = dynamic_cast(cell); - width = std::max(width, text != nullptr ? text->leastWidth() : requestedSize(*cell).width); + widths.at(*column) = + std::max(widths.at(*column), text != nullptr ? text->leastWidth() : requestedSize(*cell).width); } } return widths; @@ -463,14 +901,22 @@ std::vector TableImpl::columnWidths(int width) const { } ::core::tui::Size TableImpl::naturalSize() const { - auto const widths = naturalWidths(); - int const width = gutter() + std::accumulate(widths.begin(), widths.end(), 0) + - (kColumnGap * std::max(0, static_cast(widths.size()) - 1)); - int height = _showHeader ? 1 : 0; - for (auto const* row : shownChildren()) { - height += heightOf(*row); + int width = gutter() + _totalWidth + menuRoom(); + if (!_arranged) { + auto const widths = naturalWidths(); + width = gutter() + std::accumulate(widths.begin(), widths.end(), 0) + + (kColumnGap * std::max(0, static_cast(widths.size()) - 1)) + menuRoom(); + } + std::int64_t height = headerLines() + (_status.shown ? 1 : 0); + if (_source) { + height += static_cast(_total); // a line for each row of the view, realized or not + } else { + for (auto const* row : shownChildren()) { + height += heightOf(*row); + } } - return {.width = width, .height = height}; + return {.width = width, + .height = static_cast(std::min(height, std::numeric_limits::max()))}; } std::optional TableImpl::keyOf(WidgetBase const* row) const { @@ -487,10 +933,13 @@ WidgetBase* TableImpl::rowWith(ui::Key const& key) const { } bool TableImpl::isMarked(WidgetBase const* row) const { - if (isHeading(row)) { + if (isPassive(row)) { return false; } auto const rowKey = keyOf(row); + if (_viewExcept) { + return rowKey && !std::ranges::contains(*_viewExcept, *rowKey); + } return rowKey && std::ranges::find(_selection, *rowKey) != _selection.end(); } @@ -582,7 +1031,23 @@ void TableImpl::showCursor(std::span rows) { std::vector<::core::tui::Rect> TableImpl::childAreas(::core::tui::Size size) const { std::vector<::core::tui::Rect> areas(children().size()); - int line = _showHeader ? 1 : 0; + int line = headerLines(); + if (_source) { + // Each realized row on the line of its view index; the line below the rows is the status line's. + int const room = rowRoomOf(size.height); + for (auto const [row, area] : std::views::zip(children(), areas)) { + auto const found = _viewRows.find(row); + if (!row->shown() || found == _viewRows.end() || found->second < _top || + found->second - _top >= static_cast(room)) { + continue; + } + area = {.x = gutter(), + .y = line + static_cast(found->second - _top), + .width = std::max(0, size.width - gutter()), + .height = 1}; + } + return areas; + } std::size_t place = 0; for (auto const [row, area] : std::views::zip(children(), areas)) { if (!row->shown()) { @@ -590,7 +1055,8 @@ std::vector<::core::tui::Rect> TableImpl::childAreas(::core::tui::Size size) con } bool const above = place < _top; ++place; - if (above || line >= size.height) { + // The status line, while shown, is the last line: no row is drawn over it. + if (above || line >= size.height - (_status.shown ? 1 : 0)) { continue; } int const height = heightOf(*row); @@ -600,34 +1066,134 @@ std::vector<::core::tui::Rect> TableImpl::childAreas(::core::tui::Size size) con return areas; } -void TableImpl::paintHeader(::core::tui::Canvas& canvas, std::vector const& widths) const { +void TableImpl::paintHeader(::core::tui::Canvas& canvas, std::vector const& columns) const { auto const& theme = canvas.theme(); + int const line = headerLines() - 1; + if (!_bands.empty()) { + paintBands(canvas, columns); + } + if (!_groups.empty()) { + paintGroups(canvas, columns); + } if (_selectColumn) { - canvas.putString(0, 0, headerBox(), theme.textNormal); + canvas.putString(line, 0, headerBox(), theme.textNormal); } - int left = gutter(); - for (auto const [index, column, width] : std::views::zip(std::views::iota(std::size_t{0}), _columns, widths)) { - auto label = canvas.subcanvas({.x = left, .y = 0, .width = width, .height = 1}); + bool const focused = hasFocus(); + for (DrawnColumn const& drawn : columns) { + ui::TableColumn const& column = _columns.at(drawn.column); + // The filter button takes the column's last cell; the label is aligned in the cells before it. + int const button = column.filterable ? kFilterMark : 0; + auto label = canvas.subcanvas( + {.x = gutter() + drawn.x, .y = line, .width = std::max(0, drawn.width - button), .height = 1}); // Over its cells: a number column's header ends where its digits do. - std::string const text = headerText(index); - label.putString(0, alignedOffset(column.align, displayWidth(text), width), text, theme.textBold); - left += width + kColumnGap; + std::string const text = headerText(drawn.column); + bool const current = focused && _headerFocus == drawn.column; + label.putString(0, alignedOffset(column.align, displayWidth(text), std::max(0, drawn.width - button)), text, + current ? theme.listItemSelected : theme.textBold); + if (column.filterable && drawn.width > 0) { + bool const filtered = std::ranges::find(_filtered, drawn.column) != _filtered.end(); + canvas.putString(line, gutter() + drawn.x + drawn.width - 1, filtered ? kFilterFilled : kFilterEmpty, + theme.textNormal); + } + } + if (_menu && canvas.width() > 0) { + canvas.putString(line, canvas.width() - 1, kTableMenu, theme.textNormal); + } +} + +void TableImpl::paintGroups(::core::tui::Canvas& canvas, std::vector const& columns) const { + auto const& theme = canvas.theme(); + auto const order = visibleOrder(); + for (ui::TableColumnGroup const& group : _groups) { + int left = -1; + int right = -1; + for (DrawnColumn const& drawn : columns) { + auto const place = std::ranges::find(order, drawn.column); + auto const index = static_cast(std::distance(order.begin(), place)); + if (place != order.end() && index >= group.first && index < group.first + group.count) { + left = left < 0 ? gutter() + drawn.x : std::min(left, gutter() + drawn.x); + right = std::max(right, gutter() + drawn.x + drawn.width); + } + } + if (left < 0 || right <= left) { + continue; + } + int const y = bandLines(); + auto span = + canvas.subcanvas({.x = left, .y = y, .width = std::max(0, right - left - kFilterMark), .height = 1}); + span.putString(0, 0, group.label, theme.textBold); + canvas.putString(y, right - 1, group.filtered ? kFilterFilled : kFilterEmpty, theme.textNormal); + } +} + +// A run spans the drawn columns at the visible places it names, as the mount cut it: a band never covers a column that +// is not its own. +void TableImpl::paintBands(::core::tui::Canvas& canvas, std::vector const& columns) const { + auto const& theme = canvas.theme(); + auto const order = visibleOrder(); + for (ui::BandRun const& run : _bands) { + int left = -1; + int right = -1; + for (DrawnColumn const& drawn : columns) { + auto const place = std::ranges::find(order, drawn.column); + auto const index = static_cast(std::distance(order.begin(), place)); + if (place != order.end() && index >= run.first && index < run.first + run.count) { + left = left < 0 ? gutter() + drawn.x : std::min(left, gutter() + drawn.x); + right = std::max(right, gutter() + drawn.x + drawn.width); + } + } + if (left < 0 || right <= left) { + continue; + } + auto span = + canvas.subcanvas({.x = left, .y = static_cast(run.level), .width = right - left, .height = 1}); + span.putString(0, 0, ui::headerText(run.label, run.unit), theme.textBold); } } std::string TableImpl::rowMark(WidgetBase const* row, bool cursor) const { - // With a select column the box shows the mark; without, `*` does. + // With a select column the box shows the mark; without, `*` does, for a selected row or a row of the selected + // cells. std::string mark; if (isHeading(row)) { mark.assign(static_cast(gutter()), ' '); return mark; } + if (_summaries.contains(row)) { + mark = "\u03A3"; + mark.append(static_cast(std::max(0, gutter() - 1)), ' '); + return mark; + } + bool inCells = false; + if (auto const index = _viewRows.find(row); _cellRect && index != _viewRows.end()) { + inCells = index->second >= _cellRect->at(0) && index->second < _cellRect->at(0) + _cellRect->at(1); + } if (_selectColumn) { mark = isMarked(row) ? "[x]" : "[ ]"; } else { - mark = isMarked(row) ? "*" : " "; + std::string_view marker = " "; + if (isMarked(row) || inCells) { + marker = "*"; + } else if (_modifiedRows.contains(row)) { + marker = "+"; + } + mark = marker; } mark += cursor ? ">" : " "; + // A busy or locked row's glyph takes the gutter's own cells, after the selection and cursor marks. + if (_markGutter) { + auto const found = _marks.find(row); + bool const busy = found != _marks.end() && found->second.busy; + bool const locked = found != _marks.end() && found->second.locked; + if (busy) { + mark += kBusyGlyph; + } else if (locked) { + mark += kLockGlyph; + } else { + mark += ' '; + } + mark += ' '; + } return mark; } @@ -661,31 +1227,48 @@ void TableImpl::arrangeRows(std::vector const& widths) { } } +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one paint walks the header, the rows and the status line against a shared canvas and column layout void TableImpl::paint(::core::tui::Canvas& canvas) { auto const& theme = canvas.theme(); _size = canvas.size(); - auto const widths = columnWidths(canvas.width()); + int const room = rowRoomOf(canvas.height()); + if (_source) { + _rowRoom = room; + clampView(); + reportBeforeNextFrame(); + } + auto const drawn = drawnColumns(canvas.width()); if (_showHeader) { - paintHeader(canvas, widths); + paintHeader(canvas, drawn); } auto const rows = shownChildren(); - int const room = std::max(0, canvas.height() - (_showHeader ? 1 : 0)); - if (room != _rowRoom) { - _rowRoom = room; - _follow = true; - } - followFocus(rows); - if (_follow) { - _follow = false; - showCursor(rows); + if (!_source) { + if (room != _rowRoom) { + _rowRoom = room; + _follow = true; + } + followFocus(rows); + if (_follow) { + _follow = false; + showCursor(rows); + } + _top = std::min(_top, lastTop(rows)); + _cursorPlace = cursorPlace(rows); } - _top = std::min(_top, lastTop(rows)); - _cursorPlace = cursorPlace(rows); planSpans(); - arrangeRows(widths); + if (_source) { + slotCells(drawn); + } else { + std::vector widths; + widths.reserve(drawn.size()); + for (DrawnColumn const& column : drawn) { + widths.push_back(column.width); + } + arrangeRows(widths); + } auto const areas = childAreas(_size); placeChildren(areas); for (auto const [place, area] : std::views::zip(_plan, spanAreas(_size))) { @@ -697,9 +1280,56 @@ void TableImpl::paint(::core::tui::Canvas& canvas) { if (area.empty()) { continue; } - bool const cursor = focused && row == rows.at(_cursorPlace); + bool cursor = false; + if (_source) { + auto const found = _viewRows.find(row); + cursor = focused && _focusCell && found != _viewRows.end() && found->second == _focusCell->first; + } else { + cursor = focused && row == rows.at(_cursorPlace); + } canvas.putString(area.y, 0, rowMark(row, cursor), cursor ? theme.listItemSelected : theme.textNormal); } + if (_source) { + paintLoads(canvas, drawn, areas); + paintMarks(canvas, drawn, areas); + // Focus that left the table and everything in it, an open popup of a widget in it (an editor's list) + // included, is reported before the next frame, outside this one. + auto const* const focusedNow = context().screen->focusedComponent(); + bool within = isWithin(focusedNow, view()); + for (WidgetBase const* const owner : context().popups) { + if (!within && owner->openPopup() != nullptr && isWithin(&owner->view(), view())) { + within = isWithin(focusedNow, *owner->openPopup()); + } + } + if (std::exchange(_focusWithin, within) && !within && _onFocusOut) { + _focusLeft = true; + if (std::ranges::find(context().windowTables, this) == context().windowTables.end()) { + context().windowTables.push_back(this); + } + refresh(); + } + } + paintStatus(canvas); +} + +void TableImpl::paintMarks(::core::tui::Canvas& canvas, std::vector const& drawn, + std::vector<::core::tui::Rect> const& areas) const { + auto const& theme = canvas.theme(); + for (auto const [row, area] : std::views::zip(children(), areas)) { + auto const marks = _cellMarks.find(row); + if (area.empty() || marks == _cellMarks.end()) { + continue; + } + for (DrawnColumn const& column : drawn) { + auto const found = marks->second.find(column.column); + if (found == marks->second.end() || column.width <= 0 || + (!found->second.error && !found->second.modified)) { + continue; + } + canvas.putString(area.y, gutter() + column.x + column.width - 1, found->second.error ? "!" : "+", + found->second.error ? theme.error : theme.textMuted); + } + } } // Shift with an arrow moves as the arrow does and, in Multiple mode, selects from the anchor to the new cursor row; @@ -725,6 +1355,12 @@ EventResult TableImpl::modifiedKey(::core::tui::KeyEvent const& key) { return EventResult::Handled; } if (matchesChord("Ctrl+A", key) && _mode == ui::SelectionMode::Multiple) { + if (_onSelectAll) { + // A copy: the handler may destroy this table. + auto const handler = _onSelectAll; + handler(); + return EventResult::Handled; + } static_cast(change(allOrNone(), ui::SelectionChange::Extend)); return EventResult::Handled; } @@ -732,8 +1368,55 @@ EventResult TableImpl::modifiedKey(::core::tui::KeyEvent const& key) { } // Any key ends a double click: the click after it is a first click. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): maps each key to the table's mode (header, cell menu, source or plain rows); the modes share the focus and anchor state EventResult TableImpl::key(::core::tui::KeyEvent const& key) { _lastClick = {}; + if (matchesChord("Ctrl+C", key) && _onCopy) { + // A copy: the handler may destroy this table. + auto const handler = _onCopy; + handler(); + return EventResult::Handled; + } + if (_headerFocus) { + return headerKey(key); + } + // Up on the first row goes to the header. + if (_showHeader && headerActs() && isKey(key, KeyCode::Up) && + ::core::tui::withoutLockKeys(key.modifiers) == ::core::tui::Modifier::None) { + bool const first = _source ? (!_focusCell || _focusCell->first == 0) : cursorPlace(shownChildren()) == 0; + if (first) { + focusHeader(); + return EventResult::Handled; + } + } + // The status line's entries, by the key each shows: `Alt+`. + for (std::size_t at = 0; at < _entriesDrawn.size() && at < 9; ++at) { + if (matchesChord("Alt+" + std::to_string(at + 1), key) && _onStatusEntry) { + auto const handler = _onStatusEntry; + handler(_entriesDrawn.at(at).entryId); + return EventResult::Handled; + } + } + if (_source && _onText && _focusCell && key.codepoint >= U' ' && key.codepoint != 0x7f && + (::core::tui::withoutLockKeys(key.modifiers) == ::core::tui::Modifier::None || + ::core::tui::withoutLockKeys(key.modifiers) == ::core::tui::Modifier::Shift)) { + // A copy: the handler may destroy this table. + auto const handler = _onText; + handler(utf8Of(key.codepoint)); + return EventResult::Handled; + } + if (_source) { + if (auto const result = sourceKey(key); result == EventResult::Handled) { + return result; + } + if (cellKey(key) == EventResult::Handled) { + return EventResult::Handled; + } + // A modified key the source path leaves goes on outwards: no range runs over the realized rows alone. + if (::core::tui::withoutLockKeys(key.modifiers) != ::core::tui::Modifier::None) { + return EventResult::Ignored; + } + } if (::core::tui::withoutLockKeys(key.modifiers) != ::core::tui::Modifier::None) { return modifiedKey(key); } @@ -782,26 +1465,64 @@ WidgetBase* TableImpl::rowAtLine(int line) const { return nullptr; } +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a click resolves to the header, the gutter, a cell or the status line from one hit test, each target needing the modifier state void TableImpl::clickWith(::core::tui::Point cell, ::core::tui::Modifier modifiers) { + if (_status.shown && cell.y == _size.height - 1) { + if (_retryX >= 0 && cell.x >= _retryX && cell.x < _retryX + displayWidth(kRetry) && _onRetry) { + auto const handler = _onRetry; + handler(); + return; + } + for (DrawnEntry const& entry : _entriesDrawn) { + if (cell.x >= entry.x && cell.x < entry.x + entry.width && _onStatusEntry) { + auto const handler = _onStatusEntry; + handler(entry.entryId); + return; + } + } + return; + } bool const onBox = _selectColumn && cell.x < kBoxWidth; - // The header box is Ctrl+A; it does nothing while the table shows no rows. - if (onBox && _showHeader && cell.y == 0) { + // The header box is Ctrl+A; it does nothing while the table shows no rows. Over a source it selects the view. + int const headerLine = headerLines() - 1; + if (_showHeader && !_groups.empty() && cell.y == bandLines()) { + clickGroups(cell.x); + return; + } + if (onBox && _showHeader && cell.y == headerLine) { + if (_source) { + if (_mode == ui::SelectionMode::Multiple && _onSelectAll) { + auto const handler = _onSelectAll; + handler(); + } else if (_total > 0) { + static_cast(selectRange(0, _total - 1, ui::SelectionChange::Extend)); + } + return; + } if (_mode == ui::SelectionMode::Multiple && !shownChildren().empty()) { + if (_onSelectAll) { + auto const handler = _onSelectAll; + handler(); + return; + } static_cast(change(allOrNone(), ui::SelectionChange::Extend)); } return; } - if (_showHeader && cell.y == 0) { - clickHeader(cell.x); + if (_showHeader && cell.y == headerLine) { + clickHeader(cell.x, modifiers); return; } // A spanning cell drawn over a covered row's line is its origin row's. auto* const spanning = spanOriginAt(cell); auto* const row = spanning != nullptr ? spanning : rowAtLine(cell.y); - if (row == nullptr || isHeading(row)) { + if (row == nullptr || isPassive(row)) { return; } auto const held = ::core::tui::withoutLockKeys(modifiers); + if (_onCellSelect && selectCellsAt(row, cell, held)) { + return; + } ui::RowClick click = ui::RowClick::Only; // A row's box is a Ctrl-click on the row. if (onBox || ::core::tui::hasModifier(held, ::core::tui::Modifier::Ctrl)) { @@ -809,6 +1530,15 @@ void TableImpl::clickWith(::core::tui::Point cell, ::core::tui::Modifier modifie } else if (::core::tui::hasModifier(held, ::core::tui::Modifier::Shift)) { click = ui::RowClick::Range; } + // Over a source a Shift-click is a range through the mount, from the anchor; any other click makes the row the + // anchor. + if (auto const index = _viewRows.find(row); _source && index != _viewRows.end()) { + if (click == ui::RowClick::Range && + selectRange(_anchorRow.value_or(index->second), index->second, ui::SelectionChange::Replace)) { + return; + } + _anchorRow = index->second; + } // Only plain clicks make a double click, so two quick Ctrl-clicks toggle a row twice. auto const now = context().now(); bool const twice = click == ui::RowClick::Only && _lastClick.row == row && now - _lastClick.at <= kDoubleClick; @@ -816,19 +1546,98 @@ void TableImpl::clickWith(::core::tui::Point cell, ::core::tui::Modifier modifie auto const rows = shownChildren(); moveCursor(rows, static_cast(std::distance(rows.begin(), std::ranges::find(rows, row)))); refresh(); - if (!twice) { - static_cast(choose(*row, click)); - } else if (auto const rowKey = keyOf(row)) { + if (!twice && !choose(*row, click)) { + return; + } + if (clickCell(row, cell.x, twice) || !twice) { + return; + } + if (auto const rowKey = keyOf(row)) { activateRow(*rowKey); } } -// A move the user asked for counts as having followed the cursor and the focus as they are now, so the next frame -// does not undo it when either moved since the last one. -bool TableImpl::wheel(int delta) { - auto const rows = shownChildren(); - auto const target = delta < 0 ? _top - std::min(_top, static_cast(-delta)) - : std::min(_top + static_cast(delta), lastTop(rows)); +bool TableImpl::selectCellsAt(WidgetBase const* row, ::core::tui::Point cell, ::core::tui::Modifier held) { + auto const index = _viewRows.find(row); + std::size_t const places = visibleOrder().size(); + if (index == _viewRows.end() || places == 0) { + return false; + } + // A copy: the handler may destroy this table. + auto const handler = _onCellSelect; + if (cell.x < gutter()) { + handler(index->second, 0, index->second, places - 1); + return true; + } + if (!::core::tui::hasModifier(held, ::core::tui::Modifier::Shift) || !_focusCell) { + return false; + } + std::optional const anchor = visiblePlace(_focusCell->second); + int const across = cell.x - gutter(); + // NOLINTNEXTLINE(readability-use-anyofallof): the loop calls the range handler for the first matching column and returns; `any_of` would hide the call in its predicate + for (DrawnColumn const& column : drawnColumns(_size.width)) { + std::optional const place = visiblePlace(column.column); + if (across >= column.x && across <= column.x + column.width && anchor && place) { + handler(_focusCell->first, *anchor, index->second, *place); + return true; + } + } + return false; +} + +std::optional TableImpl::visiblePlace(std::size_t column) const { + std::vector const order = visibleOrder(); + auto const found = std::ranges::find(order, column); + return found == order.end() ? std::nullopt : std::optional{static_cast(found - order.begin())}; +} + +void TableImpl::setCellSelection(std::optional> rect) { + _cellRect = rect; + refresh(); +} + +void TableImpl::setOnCellSelect(std::function onSelect) { + _onCellSelect = std::move(onSelect); +} + +bool TableImpl::clickCell(WidgetBase const* row, int x, bool twice) { + auto const index = _viewRows.find(row); + if (!_source || !_onCellClick || index == _viewRows.end()) { + return false; + } + int const across = x - gutter(); + // NOLINTNEXTLINE(readability-use-anyofallof): the loop runs the cell handler for the first column under the click; `any_of` would hide the call in its predicate + for (DrawnColumn const& column : drawnColumns(_size.width)) { + if (across >= column.x && across <= column.x + column.width) { + // A copy: the handler may destroy this table. + auto const handler = _onCellClick; + std::size_t const viewRow = index->second; + // The first click of a double click was reported on its own: the second is reported once, as the second. + handler(viewRow, column.column, twice); + return true; + } + } + return false; +} + +// A move the user asked for counts as having followed the cursor and the focus as they are now, so the next frame +// does not undo it when either moved since the last one. +bool TableImpl::wheel(int delta) { + if (_source) { + std::size_t const before = _top; + _top = delta < 0 ? _top - std::min(_top, static_cast(-static_cast(delta))) + : _top + static_cast(delta); + clampView(); + if (_top == before) { + return false; + } + reportRanges(); + refresh(); + return true; + } + auto const rows = shownChildren(); + auto const target = delta < 0 ? _top - std::min(_top, static_cast(-delta)) + : std::min(_top + static_cast(delta), lastTop(rows)); if (target == _top) { return false; } @@ -845,7 +1654,7 @@ bool TableImpl::pick(WidgetBase const& row) { bool TableImpl::choose(WidgetBase const& row, ui::RowClick click) { auto const rowKey = keyOf(&row); - if (_mode == ui::SelectionMode::None || !rowKey || !row.actionable() || isHeading(&row)) { + if (_mode == ui::SelectionMode::None || !rowKey || !row.actionable() || isPassive(&row)) { return true; } if (_mode == ui::SelectionMode::Single || click == ui::RowClick::Only) { @@ -855,6 +1664,25 @@ bool TableImpl::choose(WidgetBase const& row, ui::RowClick click) { if (click == ui::RowClick::Range) { return change(rangeTo(row), ui::SelectionChange::Replace); } + // A selection of the view: the keys now marked among the rows held, the clicked one toggled. + if (_viewExcept) { + std::vector next; + for (WidgetBase const* const shown : shownChildren()) { + auto const key = keyOf(shown); + if (key && !isPassive(shown) && !std::ranges::contains(*_viewExcept, *key) && *key != *rowKey) { + next.push_back(*key); + } + } + if (std::ranges::contains(*_viewExcept, *rowKey)) { + next.push_back(*rowKey); + } + _anchor = *rowKey; + auto const handler = _onSelectionChange; + if (handler) { + handler(std::move(next), ui::SelectionChange::Extend); + } + return true; + } // A user's change drops a requested key still waiting for its row. std::vector next; for (auto const& selected : _selection) { @@ -885,7 +1713,7 @@ std::vector TableImpl::rangeTo(WidgetBase const& row) const { auto const [low, high] = std::minmax(from, target); std::vector keys; for (auto const* const between : std::ranges::subrange(low, std::next(high))) { - if (auto const betweenKey = keyOf(between); betweenKey && between->actionable() && !isHeading(between)) { + if (auto const betweenKey = keyOf(between); betweenKey && between->actionable() && !isPassive(between)) { keys.push_back(*betweenKey); } } @@ -895,7 +1723,7 @@ std::vector TableImpl::rangeTo(WidgetBase const& row) const { std::vector TableImpl::allOrNone() const { std::vector keys; for (auto const* const row : shownChildren()) { - if (auto const rowKey = keyOf(row); rowKey && row->actionable() && !isHeading(row)) { + if (auto const rowKey = keyOf(row); rowKey && row->actionable() && !isPassive(row)) { keys.push_back(*rowKey); } } @@ -928,7 +1756,7 @@ bool TableImpl::report(std::vector keys, ui::SelectionChange change) { void TableImpl::activateRow(ui::Key const& key) { auto const* const row = rowWith(key); - if (row == nullptr || !row->actionable() || isHeading(row)) { + if (row == nullptr || !row->actionable() || isPassive(row)) { return; } auto const handler = _onActivate; @@ -937,4 +1765,709 @@ void TableImpl::activateRow(ui::Key const& key) { } } +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`first`, `count`, `total`): the window then the full row count, passed by name at both call sites in the mount +void TableImpl::setRealizedWindow(std::size_t first, std::size_t count, std::size_t total) { + static_cast(first); + static_cast(count); + _total = total; + refresh(); +} + +void TableImpl::setOnVisibleRangeChanged(std::function onVisibleRangeChanged) { + _onVisibleRange = std::move(onVisibleRangeChanged); +} + +void TableImpl::setRowIndex(ui::Widget& row, std::size_t viewRow) { + auto const& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setRowIndex of a widget that is not this table's row"}; + } + _viewRows.insert_or_assign(&base, viewRow); + refresh(); +} + +void TableImpl::setStatus(ui::TableStatus const& status) { + _status = status; + refresh(); +} + +void TableImpl::setOnRetry(std::function onRetry) { _onRetry = std::move(onRetry); } + +void TableImpl::setCellLoad(ui::Widget& row, std::size_t column, ui::CellLoad load) { + auto const& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setCellLoad of a widget that is not this table's row"}; + } + if (load == ui::CellLoad::Loaded) { + if (auto const found = _loads.find(&base); found != _loads.end()) { + found->second.erase(column); + } + } else { + _loads[&base].insert_or_assign(column, load); + } + refresh(); +} + +void TableImpl::setCellAccent(ui::Widget& row, std::size_t column, ui::CellAccent const& accent) { + auto& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setCellAccent of a widget that is not this table's row"}; + } + if (accent == ui::CellAccent{}) { + if (auto const found = _accents.find(&base); found != _accents.end()) { + found->second.erase(column); + } + } else { + _accents[&base].insert_or_assign(column, accent); + } + // The cell's own tone wins over its row's: the nearest tone is the one drawn. + if (auto const* const stack = dynamic_cast(&base)) { + for (auto* const cell : stack->children()) { + if (columnOf(&base, cell, 0) == column) { + cell->applyRowTone(accent.tone); + } + } + } + refresh(); +} + +void TableImpl::setColumnWindow( + std::span columns, std::span offsets, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): overrides `Table::setColumnWindow`; the declaration says how its totals are told apart + std::span widths, int totalWidth, std::size_t pinned) { + _arranged = true; + _window.clear(); + for (auto const [column, offset, width] : std::views::zip(columns, offsets, widths)) { + _window.push_back(WindowColumn{.column = column, .offset = offset, .width = std::max(width, 0)}); + } + _pinned = std::min(pinned, _window.size()); + _totalWidth = std::max(totalWidth, 0); + refresh(); +} + +// Only a table over a `TableSource` is given one, before any row: its rows are then placed by their view index and its +// cells by their column. A table over `rows` is told its realized window too, once it is long enough, and is no +// source. +void TableImpl::setOnHorizontalRange(std::function handler) { + _onHorizontalRange = std::move(handler); + _source = true; +} + +ui::TableMeasure TableImpl::tableMeasure() const { + return ui::TableMeasure{.unit = 1.0, + .monoUnit = 1.0, + .contentEstimate = 12, + .padding = kColumnGap, + .shrinkFloor = kShrunkColumn + kColumnGap}; +} + +void TableImpl::setOnColumnMeasured( + std::function handler) { + _onColumnMeasured = std::move(handler); + _reportedMeasures.clear(); +} + +std::vector> TableImpl::grownMeasures() const { + std::vector> grown; + if (!_onColumnMeasured) { + return grown; + } + auto const naturals = naturalWidths(); + auto const leasts = leastWidths(); + for (std::size_t column = 0; column < _columns.size(); ++column) { + ui::ColumnMeasure const before = + column < _reportedMeasures.size() ? _reportedMeasures.at(column) : ui::ColumnMeasure{}; + // The widths of the cells and the header each carry the gap after the column, as the mount's widths do. + ui::ColumnMeasure const now{.header = std::max(before.header, headerWidth(_columns.at(column)) + kColumnGap), + .natural = std::max(before.natural, naturals.at(column) + kColumnGap), + .least = std::max(before.least, leasts.at(column) + kColumnGap)}; + if (now != before) { + grown.emplace_back(column, now); + } + } + return grown; +} + +void TableImpl::setOnSelectRange( + std::function handler) { + _onSelectRange = std::move(handler); +} + +bool TableImpl::selectRange(std::size_t anchorRow, std::size_t focusRow, ui::SelectionChange change) { + if (_mode != ui::SelectionMode::Multiple || !_onSelectRange) { + return false; + } + auto const handler = _onSelectRange; + handler(anchorRow, focusRow, change); + return true; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): the source table's keys share the focus, the selection range and the edit state +EventResult TableImpl::sourceKey(::core::tui::KeyEvent const& key) { + // The whole view: through the select-all handler when the table has one, else through the mount, which resolves + // it over the rows not realized; in Single mode it goes on outwards. + if (matchesChord("Ctrl+A", key) && _mode == ui::SelectionMode::Multiple) { + if (_onSelectAll) { + // A copy: the handler may destroy this table. + auto const handler = _onSelectAll; + handler(); + return EventResult::Handled; + } + if (_total > 0) { + _anchorRow = 0; + static_cast(selectRange(0, _total - 1, ui::SelectionChange::Extend)); + } + return EventResult::Handled; + } + bool const upward = matchesChord("Shift+Up", key); + if ((upward || matchesChord("Shift+Down", key)) && _onFocusMove && !_onCellSelect) { + // Without an anchor, the range starts at the row the focus leaves. + if (!_anchorRow) { + _anchorRow = _focusCell ? _focusCell->first : 0; + } + auto const move = _onFocusMove; + move(upward ? ui::FocusMove::Up : ui::FocusMove::Down); + if (_focusCell) { + static_cast(selectRange(*_anchorRow, _focusCell->first, ui::SelectionChange::Replace)); + } + return EventResult::Handled; + } + if (auto const move = focusMoveOf(key); move && _onFocusMove) { + auto const handler = _onFocusMove; + handler(*move); + return EventResult::Handled; + } + WidgetBase const* const row = _focusCell ? rowAtView(_focusCell->first) : nullptr; + if (::core::tui::withoutLockKeys(key.modifiers) == ::core::tui::Modifier::None && row != nullptr && _focusCell) { + if (key.codepoint == U' ') { + _anchorRow = _focusCell->first; + static_cast(pick(*row)); + return EventResult::Handled; + } + if (isKey(key, KeyCode::Enter)) { + if (auto const rowKey = keyOf(row); rowKey && (_mode != ui::SelectionMode::Single || pick(*row))) { + activateRow(*rowKey); + } + return EventResult::Handled; + } + } + return EventResult::Ignored; +} + +// The mount moved the view to keep the columns in view where they were: it knows the offset, so it is not told. +void TableImpl::setHorizontalOffset(int scrollX) { + _scrollX = std::max(scrollX, 0); + if (_reportedColumns) { + _reportedColumns->first = _scrollX; + } + refresh(); +} + +// Inside the mount's pass: the view follows the cell now, and the mount hears of the move before the next frame. +void TableImpl::setFocusCell(std::size_t viewRow, std::size_t column) { + _focusCell = std::pair{viewRow, column}; + scrollToRow(viewRow); + int pinnedEdge = 0; + for (std::size_t at = 0; at < _pinned; ++at) { + pinnedEdge = std::max(pinnedEdge, _window.at(at).offset + _window.at(at).width); + } + for (std::size_t at = _pinned; at < _window.size(); ++at) { + WindowColumn const& shown = _window.at(at); + if (shown.column != column) { + continue; + } + if (shown.offset - _scrollX < pinnedEdge) { + _scrollX = shown.offset - pinnedEdge; + } else if (shown.offset + shown.width - _scrollX > viewport()) { + _scrollX = std::min(shown.offset - pinnedEdge, shown.offset + shown.width - viewport()); + } + } + clampView(); + reportBeforeNextFrame(); + refresh(); +} + +void TableImpl::setOnFocusMove(std::function handler) { _onFocusMove = std::move(handler); } + +void TableImpl::setOnText(std::function onText) { _onText = std::move(onText); } + +void TableImpl::setOnCellClick(std::function onClick) { + _onCellClick = std::move(onClick); +} + +void TableImpl::setOnFocusOut(std::function onFocusOut) { _onFocusOut = std::move(onFocusOut); } + +void TableImpl::setCellEditor(ui::Widget& row, std::size_t column, ui::Widget* editor) { + auto const& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setCellEditor of a widget that is not this table's row"}; + } + if (editor == nullptr) { + auto const found = _editors.find(&base); + bool const focused = found != _editors.end() && found->second.second->hasFocus(); + _editors.erase(&base); + if (focused) { + takeFocus(); + } + } else { + _editors.insert_or_assign(&base, std::pair{column, &WidgetBase::of(*editor)}); + } + refresh(); +} + +void TableImpl::setCellMarks(ui::Widget& row, std::size_t column, ui::CellMarks const& marks) { + auto const& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setCellMarks of a widget that is not this table's row"}; + } + if (marks == ui::CellMarks{}) { + if (auto const found = _cellMarks.find(&base); found != _cellMarks.end()) { + found->second.erase(column); + } + } else { + _cellMarks[&base].insert_or_assign(column, marks); + } + refresh(); +} + +void TableImpl::setRowModified(ui::Widget& row, bool modified) { + auto const& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setRowModified of a widget that is not this table's row"}; + } + if (modified) { + _modifiedRows.insert(&base); + } else { + _modifiedRows.erase(&base); + } + refresh(); +} + +void TableImpl::scrollToRow(std::size_t viewRow) { + auto const room = static_cast(std::max(_rowRoom, 1)); + if (viewRow < _top) { + _top = viewRow; + } else if (viewRow >= _top + room) { + _top = viewRow + 1 - room; + } + clampView(); + reportBeforeNextFrame(); + refresh(); +} + +void TableImpl::setCellColumn(ui::Widget& row, ui::Widget& cell, std::optional column) { + auto const& base = WidgetBase::of(row); + if (base.container() != this) { + throw std::logic_error{"morph::tui: setCellColumn of a widget that is not this table's row"}; + } + _cellColumns[&base].insert_or_assign(&WidgetBase::of(cell), column); + refresh(); +} + +void TableImpl::scrollColumnsTo(int scrollX) { + _scrollX = scrollX; + clampView(); + reportRanges(); + refresh(); +} + +// Columns first: the rows the mount realizes next are then built with the columns in view only. +void TableImpl::reportRanges() { + if (std::exchange(_focusLeft, false) && _onFocusOut) { + // A copy: the handler may destroy this table, and then nothing more is reported. + auto const handler = _onFocusOut; + Context& held = context(); + WidgetBase* alive = this; + held.watches.push_back(&alive); + handler(); + std::erase(held.watches, &alive); + if (alive == nullptr) { + return; + } + } + if (!_source || _size.width <= 0) { + return; + } + std::pair const columns{_scrollX, viewport()}; + if (_onHorizontalRange && _reportedColumns != columns) { + _reportedColumns = columns; + auto const handler = _onHorizontalRange; + handler(columns.first, columns.second); + } + // The mount fits the columns to the table from these, so they go before the rows are asked for. + if (auto const grown = grownMeasures(); !grown.empty()) { + _reportedMeasures.resize(_columns.size()); + auto const handler = _onColumnMeasured; + Context& held = context(); + WidgetBase* alive = this; + held.watches.push_back(&alive); + for (auto const& [column, measure] : grown) { + _reportedMeasures.at(column) = measure; + handler(column, measure); + if (alive == nullptr) { + break; + } + } + std::erase(held.watches, &alive); + if (alive == nullptr) { + return; + } + } + auto const rows = rowsInView(); + if (_onVisibleRange && _reportedRows != rows) { + _reportedRows = rows; + auto const handler = _onVisibleRange; + handler(rows.first, rows.second); + } +} + +std::vector TableImpl::drawnColumns(int width) const { + std::vector drawn; + if (!_arranged) { + int x = 0; + for (auto const [index, columnWidth] : + std::views::zip(std::views::iota(std::size_t{0}), columnWidths(width - menuRoom()))) { + drawn.push_back(DrawnColumn{.column = index, .x = x, .width = columnWidth}); + x += columnWidth + kColumnGap; + } + return drawn; + } + // The pinned columns stay where they are; the rest scroll under them, cut where they pass under the last. + int pinnedEdge = 0; + for (std::size_t at = 0; at < _pinned; ++at) { + pinnedEdge = std::max(pinnedEdge, _window.at(at).offset + _window.at(at).width); + } + int const room = std::max(0, width - gutter() - menuRoom()); + for (std::size_t at = 0; at < _window.size(); ++at) { + WindowColumn const& shown = _window.at(at); + int x = shown.offset; + int extent = shown.width; + if (at >= _pinned) { + x -= _scrollX; + if (x < pinnedEdge) { + extent -= pinnedEdge - x; + x = pinnedEdge; + } + } + extent = std::min(extent, room - x) - kColumnGap; + if (extent > 0 && shown.column < _columns.size()) { + drawn.push_back(DrawnColumn{.column = shown.column, .x = x, .width = extent}); + } + } + return drawn; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`row`, `cell`): the row's stack then the cell inside it, as the two callers pass them +std::optional TableImpl::columnOf(WidgetBase const* row, WidgetBase const* cell, + std::size_t position) const { + if (!_source) { + return position; + } + auto const cells = _cellColumns.find(row); + if (cells == _cellColumns.end()) { + return std::nullopt; + } + auto const found = cells->second.find(cell); + return found == cells->second.end() ? std::nullopt : found->second; +} + +ui::CellLoad TableImpl::loadOf(WidgetBase const* row, std::size_t column) const { + if (auto const cells = _loads.find(row); cells != _loads.end()) { + if (auto const found = cells->second.find(column); found != cells->second.end()) { + return found->second; + } + } + if (auto const accents = _accents.find(row); accents != _accents.end()) { + if (auto const found = accents->second.find(column); found != accents->second.end() && found->second.invalid) { + return ui::CellLoad::Failed; + } + } + return ui::CellLoad::Loaded; +} + +std::string TableImpl::focusedTooltip() const { + if (!_focusCell) { + return {}; + } + WidgetBase const* const row = rowAtView(_focusCell->first); + auto const accents = row != nullptr ? _accents.find(row) : _accents.end(); + if (accents == _accents.end()) { + return {}; + } + auto const found = accents->second.find(_focusCell->second); + return found == accents->second.end() ? std::string{} : found->second.tooltip; +} + +// A cell takes its column's slot; a pooled cell, one whose column is not drawn and one a mark stands for take none. +// A heading's one cell takes every column drawn. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): assigns every cell its slot in one pass over the rows; pooled, undrawn, marked and heading cells each take none or all of the columns +void TableImpl::slotCells(std::vector const& drawn) { + std::unordered_map byColumn; + int across = 0; + for (DrawnColumn const& column : drawn) { + byColumn.emplace(column.column, &column); + across = std::max(across, column.x + column.width); + } + for (auto* const row : children()) { + auto* const stack = dynamic_cast(row); + if (stack == nullptr) { + continue; + } + std::vector slots; + slots.reserve(stack->children().size()); + auto const editor = _editors.find(row); + for (auto* const cell : stack->children()) { + CellSlot slot; + auto const column = columnOf(row, cell, 0); + if (editor != _editors.end() && (cell == editor->second.second || column == editor->second.first)) { + // An open editor is drawn in its cell's slot, the cell it edits in none. + if (auto const found = byColumn.find(editor->second.first); + cell == editor->second.second && found != byColumn.end()) { + slot = CellSlot{.x = found->second->x, + .width = found->second->width, + .place = CellPlace{.across = ui::Align::Stretch, .down = ui::Align::Center}}; + } + } else if (isHeading(row)) { + if (!_cellColumns.contains(row) || !_cellColumns.at(row).contains(cell)) { + slot = CellSlot{.x = 0, .width = across, .place = CellPlace{.across = ui::Align::Start}}; + } + } else if (auto const found = column ? byColumn.find(*column) : byColumn.end(); + column && found != byColumn.end() && loadOf(row, *column) == ui::CellLoad::Loaded) { + ui::TableColumn const& spec = _columns.at(*column); + slot = CellSlot{.x = found->second->x, + .width = found->second->width, + .place = CellPlace{.across = spec.align, .down = spec.valign}}; + // The terminal cannot wrap, so a text cell a column cuts ends in an ellipsis. + if (auto* const text = dynamic_cast(cell)) { + text->setElided(spec.wrap ? TextImpl::Elision::PerLine : TextImpl::Elision::OneLine); + } else if (auto* const badge = dynamic_cast(cell)) { + badge->setElided(true); + } + } + slots.push_back(slot); + } + // A row with no cell keeps one empty slot, so it is never laid out by extents it was not given. + if (slots.empty()) { + slots.push_back(CellSlot{}); + } + // A cell that is gone leaves its row: what is kept is the row's children's columns. + if (auto const cells = _cellColumns.find(row); + cells != _cellColumns.end() && cells->second.size() > stack->children().size()) { + std::erase_if(cells->second, [stack](auto const& entry) { + return !std::ranges::contains(stack->children(), entry.first); + }); + } + stack->setCellSlots(std::move(slots)); + } +} + +int TableImpl::rowRoomOf(int height) const noexcept { + return std::max(0, height - headerLines() - (_status.shown ? 1 : 0)); +} + +int TableImpl::viewport() const noexcept { return std::max(0, _size.width - gutter() - menuRoom()); } + +std::optional<::core::tui::Rect> TableImpl::headerLabelArea(std::size_t column) const { + if (!_showHeader || column >= _columns.size()) { + return std::nullopt; + } + for (DrawnColumn const& drawn : drawnColumns(_size.width)) { + if (drawn.column == column) { + int const button = _columns.at(column).filterable ? kFilterMark : 0; + return ::core::tui::Rect{.x = gutter() + drawn.x, + .y = headerLines() - 1, + .width = std::max(0, drawn.width - button), + .height = 1}; + } + } + return std::nullopt; +} + +int TableImpl::menuRoom() const noexcept { return _menu && _showHeader ? kTableMenuRoom : 0; } + +bool TableImpl::headerActs() const { + return _menu || _onColumnMove || + std::ranges::any_of(_columns, [](ui::TableColumn const& column) { return column.sortable; }); +} + +// A right press on a header opens its menu; on the header line's `⋯`, the table's. +bool TableImpl::contextPress(::core::tui::Point cell) { + // A right press on a row's cell opens the cell's menu. + if (_cellMenu && cell.y >= headerLines()) { + WidgetBase const* const row = rowAtLine(cell.y); + if (row == nullptr) { + return false; + } + // NOLINTNEXTLINE(readability-use-anyofallof): the loop opens the cell menu for the first column under the click; `any_of` would hide the call in its predicate + for (DrawnColumn const& drawn : drawnColumns(_size.width)) { + int const left = gutter() + drawn.x; + if (cell.x >= left && cell.x < left + drawn.width) { + openCellMenu(*row, drawn.column); + return true; + } + } + return false; + } + if (!_menu || !_showHeader || cell.y != headerLines() - 1) { + return false; + } + if (cell.x == _size.width - 1) { + openMenu(std::nullopt); + return true; + } + // NOLINTNEXTLINE(readability-use-anyofallof): the loop opens the column menu for the first header under the click; `any_of` would hide the call in its predicate + for (DrawnColumn const& drawn : drawnColumns(_size.width)) { + int const left = gutter() + drawn.x; + if (cell.x >= left && cell.x < left + drawn.width) { + openMenu(drawn.column); + return true; + } + } + return false; +} + +std::pair TableImpl::rowsInView() const noexcept { + return {_top, static_cast(std::max(_rowRoom, 0))}; +} + +void TableImpl::clampView() { + auto const room = static_cast(std::max(_rowRoom, 0)); + _top = std::min(_top, _total > room ? _total - room : std::size_t{0}); + _scrollX = std::clamp(_scrollX, 0, std::max(0, _totalWidth - viewport())); +} + +void TableImpl::reportBeforeNextFrame() { + // A table drawn at no width reports nothing (`reportRanges`), so it asks for no frame either. + if (_size.width <= 0) { + return; + } + bool const columnsDue = _onHorizontalRange && _reportedColumns != std::pair{_scrollX, viewport()}; + bool const rowsDue = _onVisibleRange && _reportedRows != rowsInView(); + bool const measuresDue = !grownMeasures().empty(); + if (!columnsDue && !rowsDue && !measuresDue) { + return; + } + if (std::ranges::find(context().windowTables, this) == context().windowTables.end()) { + context().windowTables.push_back(this); + } + refresh(); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): draws the status text, the retry button and the gap in one left-to-right pass over a running column +void TableImpl::paintStatus(::core::tui::Canvas& canvas) { + _retryX = -1; + _entriesDrawn.clear(); + if (!_status.shown || canvas.height() <= 0) { + return; + } + auto const& theme = canvas.theme(); + int const line = canvas.height() - 1; + std::string lead = _status.counts; + if (!_status.state.empty()) { + lead += (lead.empty() ? "" : std::string{kStatusGap}) + _status.state; + } + canvas.putString(line, 0, lead, theme.textMuted); + int x = displayWidth(lead); + if (_status.retry) { + x += lead.empty() ? 0 : displayWidth(kStatusGap); + _retryX = x; + canvas.putString(line, x, kRetry, theme.textAccent); + x += displayWidth(kRetry); + } + // What stays while its cause lasts, then each choice as `[Alt+ label]`, the key that chooses it. + auto const entries = [&](std::vector const& list) { + for (ui::StatusEntry const& entry : list) { + std::string const drawn = "[Alt+" + std::to_string(_entriesDrawn.size() + 1) + " " + entry.label + "]"; + x += x == 0 ? 0 : displayWidth(kStatusGap); + canvas.putString(line, x, drawn, theme.textAccent); + _entriesDrawn.push_back(DrawnEntry{.x = x, .width = displayWidth(drawn), .entryId = entry.id}); + x += displayWidth(drawn); + } + }; + if (!_status.standing.empty()) { + x += x == 0 ? 0 : displayWidth(kStatusGap); + canvas.putString(line, x, _status.standing, theme.textNormal); + x += displayWidth(_status.standing); + } + entries(_status.standingEntries); + if (!_status.entries.empty()) { + if (!_status.message.empty()) { + x += x == 0 ? 0 : displayWidth(kStatusGap); + canvas.putString(line, x, _status.message, theme.textNormal); + x += displayWidth(_status.message); + } + entries(_status.entries); + return; + } + // The latest message, else the focused cell's tooltip: a terminal has no hover to show it on. + std::string const message = _status.message.empty() ? focusedTooltip() : _status.message; + if (!message.empty()) { + // At the trailing edge, or after the rest when the line is too short for both. + int const width = displayWidth(message); + int const gap = x == 0 ? 0 : displayWidth(kStatusGap); + canvas.putString(line, std::max(x + gap, canvas.width() - width), message, theme.textNormal); + } +} + +void TableImpl::paintLoads(::core::tui::Canvas& canvas, std::vector const& drawn, + std::vector<::core::tui::Rect> const& areas) const { + auto const& theme = canvas.theme(); + for (auto const [row, area] : std::views::zip(children(), areas)) { + if (area.empty() || isHeading(row)) { + continue; + } + for (DrawnColumn const& column : drawn) { + ui::CellLoad const load = loadOf(row, column.column); + if (load == ui::CellLoad::Loaded) { + continue; + } + bool const failed = load == ui::CellLoad::Failed; + std::string const mark{failed ? kFailedMark : kUnloadedMark}; + auto cell = canvas.subcanvas({.x = gutter() + column.x, .y = area.y, .width = column.width, .height = 1}); + cell.putString(0, alignedOffset(_columns.at(column.column).align, displayWidth(mark), column.width), mark, + failed ? theme.error : theme.textMuted); + } + } +} + +WidgetBase* TableImpl::rowAtView(std::size_t viewRow) const { + auto const found = std::ranges::find_if(children(), [this, viewRow](WidgetBase const* row) { + auto const index = _viewRows.find(row); + return index != _viewRows.end() && index->second == viewRow; + }); + return found == children().end() ? nullptr : *found; +} + +std::optional TableImpl::focusMoveOf(::core::tui::KeyEvent const& key) { + auto const held = ::core::tui::withoutLockKeys(key.modifiers); + if (held == ::core::tui::Modifier::Ctrl) { + if (isKey(key, KeyCode::Home)) { + return ui::FocusMove::First; + } + if (isKey(key, KeyCode::End)) { + return ui::FocusMove::Last; + } + return std::nullopt; + } + if (held != ::core::tui::Modifier::None) { + return std::nullopt; + } + static constexpr std::array, 8> kMoves{{ + {KeyCode::Up, ui::FocusMove::Up}, + {KeyCode::Down, ui::FocusMove::Down}, + {KeyCode::Left, ui::FocusMove::Left}, + {KeyCode::Right, ui::FocusMove::Right}, + {KeyCode::Home, ui::FocusMove::Home}, + {KeyCode::End, ui::FocusMove::End}, + {KeyCode::PageUp, ui::FocusMove::PageUp}, + {KeyCode::PageDown, ui::FocusMove::PageDown}, + }}; + for (auto const& [code, move] : kMoves) { + if (isKey(key, code)) { + return move; + } + } + return std::nullopt; +} + } // namespace morph::tui::detail diff --git a/src/tui/table_widget.hpp b/src/tui/table_widget.hpp index b1717e380..fc457c285 100644 --- a/src/tui/table_widget.hpp +++ b/src/tui/table_widget.hpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once +#include #include #include #include @@ -16,9 +17,11 @@ #include #include #include +#include #include #include "tui/context.hpp" +#include "tui/list_widgets.hpp" #include "tui/widget.hpp" namespace morph::tui::detail { @@ -29,10 +32,32 @@ namespace morph::tui::detail { /// focus, the cursor row `>`. With a select column the gutter is five cells: a `[x]` or `[ ]` box per row in place of /// the `*`, under a header box that reads `[x]`, `[-]` or `[ ]`; a click on a row's box toggles the row as Ctrl+click /// does, and a click on the header box is Ctrl+A. A click on a sortable column's header asks to sort by it -/// (`setOnSort`), and the sorted column's label is followed by ` ▲` or ` ▼`; a sortable column's header keeps room -/// for the mark, so the columns do not move when the sort does. The header takes no keyboard focus. A heading row +/// (`setOnSort`), `Plain`, or `Shift` with Shift held; each header of the sort chain is followed by its mark +/// (`ui::sortMarkText`: ` ▲` or ` ▼`, with its place from 1 when the chain has two or more keys), and a sortable +/// column's header keeps room for the mark, so the columns do not move when a one-key sort does. A filterable column's +/// header ends in its filter button, `▿`, drawn `▾` while `setFiltered` names the column, which a click presses +/// (`setOnFilter`). Groups (`setColumnGroups`) draw a line above the headers: each group's label over the visible +/// columns it names, ending in its own filter button. Bands (`setBands`) draw a line per level above that, outermost +/// first: each run's label, then its unit in brackets, from the run's first drawn column, cut at its last. With menus +/// (`setMenu`), the header line keeps its last two cells for a `⋯` that opens the table's menu, so no column's header +/// or filter button lies under it; a header's menu opens on a right click on the header, or with Shift+F10 or the +/// context-menu key on the focused header. A menu is a list below its header, as a button-style menu's is. The +/// terminal draws no drag or resize handle: a move is Ctrl+Shift+Left and Ctrl+Shift+Right on the focused header, and +/// nothing resizes a column. With a cell menu +/// (`setCellMenu`), a right click on a row's cell opens it below the cell, after selecting the row alone when it is +/// not selected; over a source, Shift+F10 or the context-menu key opens it on the focused cell, and a key the table +/// leaves that is one of `setCellMenuKeys` runs the focused cell's entry whose chord it is. +/// +/// While a header can act (a column sorts, or the table has menus or moves columns), it takes the keyboard focus +/// within the table: Up on the first row (the first view row over a source) focuses the header of the chain's first +/// key, or the first visible column, drawn highlighted while the table has +/// the focus. Left and Right move along the visible columns, Enter and Space sort (`Plain`), Shift+Enter and +/// Shift+Space extend (`Shift`), Ctrl+Shift+Left and Ctrl+Shift+Right report a move one place over, Shift+F10 opens +/// its menu, and Down returns to the rows. Ctrl+C on the table asks to copy (`setOnCopy`) wherever its focus is. A +/// heading row /// (`setRowHeading`) is one cell across every column; it draws no mark or box, the cursor passes over it, a click on -/// it does nothing, and Ctrl+A, a range and the header box leave it out. +/// it does nothing, and Ctrl+A, a range and the header box leave it out. A summary row (`setRowSummary`) draws its +/// cells as any row does and `Σ` in its gutter; like a heading, it is never selected, activated or the cursor's. /// /// Up, Down, Home and End move the cursor, and PageUp and PageDown by as many rows as fill the room below the header; /// Space selects the cursor row (Single) or toggles it and makes it the anchor (Multiple); Enter selects it in Single @@ -56,6 +81,21 @@ namespace morph::tui::detail { /// row, or the room for rows changes, the view brings the cursor row into view. The wheel moves the view one row and /// is left to the table's surroundings when the view cannot move that way. A row scrolled out of view is given no /// area, so it neither draws nor takes a click. +/// +/// A table over a `TableSource` draws what the mount realizes. Its view scrolls over every row of the view, one line +/// each, and each realized row is drawn on the line of its view index (`setRowIndex`); a line whose row is not +/// realized is blank. Each cell is drawn in the column `setCellColumn` gave it, and a cell with none is not drawn. +/// Once the mount lays the columns out (`setColumnWindow`), the header and the cells show the window's columns only, +/// at the mount's offsets and widths in cells, the last cell of each its gap; the pinned columns stay at the leading +/// edge and the rest scroll under them. The table reports the columns and the rows in view (`setOnHorizontalRange`, +/// `setOnVisibleRangeChanged`) before the next frame's layout whenever a frame found them changed, and at once when +/// the wheel or `scrollColumnsTo` moves the view. The arrows, Home, End, PageUp, PageDown, Ctrl+Home and Ctrl+End go +/// to the mount (`setOnFocusMove`), and the focused cell (`setFocusCell`) is kept in view: Left and Right are how the +/// user scrolls sideways. A row is one line, so no row grows, and none above the view moves the rows in it. An +/// `Unloaded` cell draws `···` and a `Failed` one `!`, in its column's alignment, in place of its content. +/// +/// The status line (`setStatus`), while shown, is the table's last line: the counts, the state, `[Retry]` while the +/// state offers it, which a click chooses, and the message at the trailing edge. class TableImpl final : public TuiContainer { public: explicit TableImpl(Context& context) : TuiContainer{context} { adopt(makeView(*this)); } @@ -72,14 +112,122 @@ class TableImpl final : public TuiContainer { void setRowLabel(ui::Widget& row, std::string_view label) override; /// Throws std::logic_error when @p row is not one of this table's rows. void setRowHeading(ui::Widget& row) override; + void setRowSummary(ui::Widget& row) override; /// Throws std::logic_error when @p row is not one of this table's rows. void setRowSpans(ui::Widget& row, std::vector const& spans) override; void setSelection(std::vector const& selection) override; void setOnSelectionChange( std::function, ui::SelectionChange)> onSelectionChange) override; + void setOnSelectAll(std::function onSelectAll) override; + void setSelectionView(std::vector const& except) override; + void setOnStatusEntry(std::function onStatusEntry) override; + /// An unmatched row's cells draw dim; a busy row shows the busy glyph and a locked row the lock glyph in gutter + /// cells of their own (the glyph and a gap), after the selection and cursor marks; the marks' tooltip, or for a + /// busy or locked row without one a text saying why, is the row's hover text over its own tooltip. Throws + /// std::logic_error when + /// @p row is not one of this table's rows. + void setRowMarks(ui::Widget& row, ui::RowMarks const& marks) override; void setOnActivate(std::function onActivate) override; - void setSort(std::optional sort) override; - void setOnSort(std::function onSort) override; + void setSort(std::vector const& chain) override; + void setOnSort(std::function onSort) override; + void setMenu(std::function(std::optional)> entries, + std::function, std::vector)> onChoose) override; + void setCellMenu( + std::function(ui::Key const&, std::size_t)> entries, + std::function const&)> chosen) override; + void setCellMenuKeys(std::vector const& chords) override { _cellMenuKeys = chords; } + void setVisibleColumns(std::vector const& visible) override; + void setOnColumnMove(std::function handler) override; + void setOnFilter(std::function handler) override; + void setFiltered(std::vector const& columns) override; + void setColumnGroups(std::vector const& groups) override; + void setBands(std::vector const& runs) override; + void setOnGroupFilter(std::function handler) override; + void setOnCopy(std::function onCopy) override; + void closePopup() override { _menuPopup.close(); } + [[nodiscard]] ::core::tui::Component const* openPopup() const override { return _menuPopup.list(); } + /// The column whose header has the focus within the table, or none while the rows have it. + [[nodiscard]] std::optional focusedHeader() const noexcept { return _headerFocus; } + /// The cells the header line keeps at its end for the `⋯`: a gap and the button, while the table has menus. + [[nodiscard]] int menuRoom() const noexcept; + /// Whether a focused header could act: a column sorts, or the table has menus or moves columns. + [[nodiscard]] bool headerActs() const; + /// The visible columns in layout order: as `setVisibleColumns` told them, or every column. + [[nodiscard]] std::vector visibleOrder() const; + /// The entries of the open header or table menu; empty while none is open. + [[nodiscard]] std::vector openMenuEntries() const { + return _menuPopup.isOpen() ? _menuPopup.entries() : std::vector{}; + } + /// The header text of the column at @p index: its label with its unit (`Mass [kg]`), then its sort key's mark + /// when it is in the chain. + [[nodiscard]] std::string headerText(std::size_t index) const; + /// The accessible name of a column's header: its label with its unit (`ui::headerAccessibleName`), followed by + /// `, filtered` while it has a filter. + [[nodiscard]] std::string headerName(std::size_t index) const; + /// The accessible description of a column's header: its sort key's (`ui::sortDescription`), or empty. + [[nodiscard]] std::string headerDescription(std::size_t index) const; + void setRealizedWindow(std::size_t first, std::size_t count, std::size_t total) override; + void setOnVisibleRangeChanged(std::function onVisibleRangeChanged) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setRowIndex(ui::Widget& row, std::size_t viewRow) override; + /// The terminal measures in cells: a unit, and a monospace character, is one cell; a column takes its gap after it + /// beyond its content, as an unwindowed column does; a column that declares no width starts at twelve; a column + /// that shrinks goes down to a few cells and its gap. + [[nodiscard]] ui::TableMeasure tableMeasure() const override; + void setStatus(ui::TableStatus const& status) override; + void setOnRetry(std::function onRetry) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setCellLoad(ui::Widget& row, std::size_t column, ui::CellLoad load) override; + /// A tone tints the cell's text in the tone's style, `invalid` draws the error glyph in place of the text, and a + /// tooltip is shown in the status line while the cell has the focus. Throws std::logic_error when @p row is not + /// one of this table's rows. + void setCellAccent(ui::Widget& row, std::size_t column, ui::CellAccent const& accent) override; + void setColumnWindow(std::span columns, std::span offsets, + std::span widths, int totalWidth, std::size_t pinned) override; + void setOnHorizontalRange(std::function handler) override; + /// Reports the widths of the headers and of the shown cells, with the gap after the column, when one grew since it + /// was last reported, so the mount can fit the columns to the table. + void setOnColumnMeasured( + std::function handler) override; + void setHorizontalOffset(int scrollX) override; + void setFocusCell(std::size_t viewRow, std::size_t column) override; + void setOnFocusMove(std::function handler) override; + /// Printable text typed on a focused cell of a table over a source, with no chord of the table's for the key. + void setOnText(std::function onText) override; + void setOnCellClick( + std::function onClick) override; + /// Reported before the frame after the one that found the focus outside the table and everything in it. + void setOnFocusOut(std::function onFocusOut) override; + /// The editor takes the cell's slot and the cell none; an editor that had the focus gives it back to the table + /// when it goes. Throws std::logic_error when @p row is not one of this table's rows. + void setCellEditor(ui::Widget& row, std::size_t column, ui::Widget* editor) override; + /// An error mark draws `!` and a modified one `+` at the cell's trailing edge. Throws std::logic_error when @p row + /// is not one of this table's rows. + void setCellMarks(ui::Widget& row, std::size_t column, ui::CellMarks const& marks) override; + /// A modified row draws `+` in its selection mark's cell while it is not selected. Throws std::logic_error when + /// @p row is not one of this table's rows. + void setRowModified(ui::Widget& row, bool modified) override; + /// The rows a rectangle of cells spans draw `*` in the gutter, as selected rows do; the terminal draws no column + /// of it. + void setCellSelection(std::optional> rect) override; + /// In cell mode a click in a row's gutter selects the row's cells, a Shift-click the cells from the focused one to + /// the one clicked, and a Ctrl-click on a column's header the column's cells. + void setOnCellSelect(std::function + onSelect) override; + /// Over a source, Shift with Up or Down, a Shift-click and Ctrl+A (and the header box) go to the handler as view + /// rows; the mount resolves them over rows not realized. + void setOnSelectRange( + std::function handler) override; + void scrollToRow(std::size_t viewRow) override; + /// Throws std::logic_error when @p row is not one of this table's rows. + void setCellColumn(ui::Widget& row, ui::Widget& cell, std::optional column) override; + /// Moves the view sideways to @p scrollX cells into the columns, kept within them, and reports the columns in + /// view. + void scrollColumnsTo(int scrollX); + /// Reports the columns, then the rows, in view, each when it changed since it was last reported. `fit` calls it + /// before a frame's layout for a table whose last frame found them changed. + void reportRanges(); /// The positions among `children()` of the rows the table marks as selected, ascending. [[nodiscard]] std::vector markedRows() const; [[nodiscard]] ::core::tui::Size naturalSize() const override; @@ -88,6 +236,12 @@ class TableImpl final : public TuiContainer { void paint(::core::tui::Canvas& canvas) override; [[nodiscard]] ::core::tui::EventResult key(::core::tui::KeyEvent const& key) override; void clickWith(::core::tui::Point cell, ::core::tui::Modifier modifiers) override; + [[nodiscard]] bool contextPress(::core::tui::Point cell) override; + /// The cells of the header line a column's label is drawn in, relative to the table, the filter button left out; + /// none while the column's header is not drawn. + [[nodiscard]] std::optional<::core::tui::Rect> headerLabelArea(std::size_t column) const; + /// The cell of a group's filter button on the group line, relative to the table; none while it is not drawn. + [[nodiscard]] std::optional groupFilterX(std::size_t group) const; [[nodiscard]] bool wheel(int delta) override; /// Works out which cells span and which are covered from the shown rows' order and their spans, clipping a span @@ -101,13 +255,20 @@ class TableImpl final : public TuiContainer { void childForgotten(WidgetBase& child) override; private: + /// A column as it is drawn: its index into `_columns`, and where its cells go, from the end of the gutter. + struct DrawnColumn { + std::size_t column = 0; + int x = 0; + int width = 0; ///< Without the gap after it. + }; /// A spanning cell as the last plan found it: lifted out of its origin row and drawn over the rows it covers. struct SpanPlace { WidgetBase* origin = nullptr; ///< The row that gives the span. WidgetBase* cell = nullptr; ///< The spanning cell, a child of the table's view while the plan holds it. std::size_t column = 0; - std::size_t first = 0; ///< The origin's place among the shown rows. - std::size_t last = 0; ///< The last covered row's place. + std::size_t columns = 1; ///< How many columns it covers from `column`, its own included. + std::size_t first = 0; ///< The origin's place among the shown rows. + std::size_t last = 0; ///< The last covered row's place. }; /// The lines of @p row: its natural height, a line at least, and what a spanning cell it ends needs besides. [[nodiscard]] int heightOf(WidgetBase const& row) const; @@ -122,14 +283,44 @@ class TableImpl final : public TuiContainer { [[nodiscard]] int gutter() const noexcept; /// The header's box: `[x]` while every shown row is selected, `[-]` while some are, `[ ]` while none are. [[nodiscard]] std::string headerBox() const; - /// The header text of the column at @p index: its label, then the sort mark when it is the sorted column. - [[nodiscard]] std::string headerText(std::size_t index) const; - /// The cells a column's header needs: its label, and room for the sort mark when it is sortable. - [[nodiscard]] static int headerWidth(ui::TableColumn const& column); - /// Calls onSort when the header click at column @p x lands on a sortable column. - void clickHeader(int x); + /// The cells a column's header needs: its label with its unit, room for the sort mark when it is sortable, and + /// its filter button when it is filterable. + [[nodiscard]] int headerWidth(ui::TableColumn const& column) const; + /// The lines above the rows: none without a header, else the header line, under the group line when there are + /// groups. + [[nodiscard]] int headerLines() const noexcept; + /// The lines the bands take: one per level. + [[nodiscard]] int bandLines() const noexcept; + /// The sort chain's place of @p index, from 0, or none. + [[nodiscard]] std::optional chainPlace(std::size_t index) const; + /// Acts on a click on the header line at column @p x: the `⋯`, a filter button, or a sortable column's header; + /// in cell mode a Ctrl-click on a column's header selects its cells. + void clickHeader(int x, ::core::tui::Modifier modifiers); + /// In cell mode, a click in @p row's gutter or a Shift-click on one of its cells, reported as a rectangle; whether + /// the click was one of those. + [[nodiscard]] bool selectCellsAt(WidgetBase const* row, ::core::tui::Point cell, ::core::tui::Modifier held); + /// A column's place among the visible columns, or none while it is hidden. + [[nodiscard]] std::optional visiblePlace(std::size_t column) const; + /// Acts on a click on the group line at column @p x: a group's filter button. + void clickGroups(int x); + /// Draws the group line above the headers. + void paintGroups(::core::tui::Canvas& canvas, std::vector const& columns) const; + /// Draws each band run on its level's line, over the drawn columns at the visible places it names. + void paintBands(::core::tui::Canvas& canvas, std::vector const& columns) const; + /// The keys of a focused header; Ignored for any other key, which then goes on outwards. + [[nodiscard]] ::core::tui::EventResult headerKey(::core::tui::KeyEvent const& key); + /// Focuses the header of the chain's first key, or the first visible column. + void focusHeader(); + /// Opens the menu of @p column's header, or the table's menu, below its place on the header line. + void openMenu(std::optional column); + /// Opens the menu of @p row's cell in @p column below the cell, after making the row the selection alone when it + /// is not selected. + void openCellMenu(WidgetBase const& row, std::size_t column); + /// The menu key on the focused cell of a table over a source, and the chords of the focused cell's entries; + /// Ignored for any other key. + [[nodiscard]] ::core::tui::EventResult cellKey(::core::tui::KeyEvent const& key); /// Draws the header line: the header box, then each column's label at its alignment. - void paintHeader(::core::tui::Canvas& canvas, std::vector const& widths) const; + void paintHeader(::core::tui::Canvas& canvas, std::vector const& columns) const; /// Gives each row its column layout. void arrangeRows(std::vector const& widths); /// The gutter of @p row: its selection mark, or its box, then the cursor mark when @p cursor. @@ -147,6 +338,10 @@ class TableImpl final : public TuiContainer { [[nodiscard]] WidgetBase* rowWith(ui::Key const& key) const; [[nodiscard]] bool isMarked(WidgetBase const* row) const; [[nodiscard]] bool isHeading(WidgetBase const* row) const { return _headings.contains(row); } + /// Whether a row is never selected, activated or the cursor's: a heading or a summary row. + [[nodiscard]] bool isPassive(WidgetBase const* row) const { + return _headings.contains(row) || _summaries.contains(row); + } /// The first place from @p place among @p rows, toward the end (or the start when there is none there), that is /// not a heading; @p place itself when every row is one. [[nodiscard]] std::size_t dataPlace(std::span rows, std::size_t place, @@ -188,23 +383,74 @@ class TableImpl final : public TuiContainer { /// Calls onActivate with @p key when a row the user can reach has it; the handler may destroy this table. void activateRow(ui::Key const& key); + /// The columns drawn in a table @p width cells wide: the mount's window once it lays the columns out, else every + /// column at its solved width. + [[nodiscard]] std::vector drawnColumns(int width) const; + /// The column a cell of @p row is in: by `setCellColumn` in a table over a source, else its @p position. + [[nodiscard]] std::optional columnOf(WidgetBase const* row, WidgetBase const* cell, + std::size_t position) const; + /// The load state of @p row's cell in @p column; a loaded cell whose value could not be read is `Failed`, so it + /// draws the error glyph in place of its text. + [[nodiscard]] ui::CellLoad loadOf(WidgetBase const* row, std::size_t column) const; + /// The tooltip of the focused cell; empty when it has none. + [[nodiscard]] std::string focusedTooltip() const; + /// Gives each row of a table over a source a slot per cell: its column's, or none. + void slotCells(std::vector const& drawn); + /// The lines below the header that rows take in a table @p height lines tall: all but the status line. + [[nodiscard]] int rowRoomOf(int height) const noexcept; + /// The view's width across the columns: the table's, less the gutter. + [[nodiscard]] int viewport() const noexcept; + /// The rows in view, as the mount is told them: the first view row drawn and how many lines rows take. + [[nodiscard]] std::pair rowsInView() const noexcept; + /// Keeps the view within the rows and the columns. + void clampView(); + /// Has the next frame report the ranges in view, when they changed. + void reportBeforeNextFrame(); + /// The columns whose measure grew past what was last reported, with the measure to report. + [[nodiscard]] std::vector> grownMeasures() const; + /// Draws the status line on the last line. + void paintStatus(::core::tui::Canvas& canvas); + /// Draws the marks of the cells that are not loaded, in their rows' @p areas. + void paintLoads(::core::tui::Canvas& canvas, std::vector const& drawn, + std::vector<::core::tui::Rect> const& areas) const; + /// Draws the marks of the cells that have some, in their rows' @p areas. + void paintMarks(::core::tui::Canvas& canvas, std::vector const& drawn, + std::vector<::core::tui::Rect> const& areas) const; + /// Calls onCellClick for a click at column @p x of @p row, a second time for a double click; whether it did. + bool clickCell(WidgetBase const* row, int x, bool twice); + /// The realized row at view row @p viewRow, or null. + [[nodiscard]] WidgetBase* rowAtView(std::size_t viewRow) const; + /// Calls onSelectRange with a range of view rows in `Multiple` mode; whether it was called. + bool selectRange(std::size_t anchorRow, std::size_t focusRow, ui::SelectionChange change); + /// The keys of a table over a source: moves and ranges through the mount, Space and Enter on the focused row; + /// Ignored for any other key. + [[nodiscard]] ::core::tui::EventResult sourceKey(::core::tui::KeyEvent const& key); + /// The move a key asks of the mount in a table over a source, or none. + [[nodiscard]] static std::optional focusMoveOf(::core::tui::KeyEvent const& key); + std::vector _columns; bool _showHeader = true; bool _selectColumn = false; ui::SelectionMode _mode = ui::SelectionMode::None; std::unordered_map _keys; std::unordered_set _headings; + std::unordered_set _summaries; + // The marks of each row that has any, and whether the gutter holds a cell for a busy or locked glyph. + std::unordered_map _marks; + bool _markGutter = false; std::unordered_map> _spans; ///< Each row's effective spans. std::vector _plan; ///< The spanning cells, as last planned. std::unordered_map _extraLines; ///< The lines a spanning cell adds to its last row. std::vector _selection; ///< The keys requested or selected by the user, in that order. - WidgetBase* _cursor = nullptr; ///< The cursor row; null for the first shown row. - std::optional _anchor; ///< Where a range starts: the row last clicked or toggled. - std::size_t _cursorPlace = 0; ///< The cursor's position among the shown rows, when last known. - std::size_t _top = 0; ///< The first shown row drawn. - ::core::tui::Size _size{}; ///< The table's size, as of the last frame. - int _rowRoom = 0; ///< Lines below the header, as of the last frame. - bool _follow = true; ///< Whether the next frame brings the cursor row into view. + /// Engaged while the selection is of the view: every row but these keys is marked, until the next `setSelection`. + std::optional> _viewExcept; + WidgetBase* _cursor = nullptr; ///< The cursor row; null for the first shown row. + std::optional _anchor; ///< Where a range starts: the row last clicked or toggled. + std::size_t _cursorPlace = 0; ///< The cursor's position among the shown rows, when last known. + std::size_t _top = 0; ///< The first shown row drawn. + ::core::tui::Size _size{}; ///< The table's size, as of the last frame. + int _rowRoom = 0; ///< Lines below the header, as of the last frame. + bool _follow = true; ///< Whether the next frame brings the cursor row into view. /// The focused view the table last looked at, compared by address only: it may be gone by the next frame. ::core::tui::Component const* _focusSeen = nullptr; @@ -215,9 +461,85 @@ class TableImpl final : public TuiContainer { }; LastClick _lastClick; std::function, ui::SelectionChange)> _onSelectionChange; + /// Ctrl+A's and the header box's handler in place of selecting the rows held; empty for none. + std::function _onSelectAll; std::function _onActivate; - std::optional _sort; - std::function _onSort; + std::vector _chain; + std::function _onSort; + std::function(std::optional)> _menu; + std::function, std::vector)> _onMenu; + std::function(ui::Key const&, std::size_t)> _cellMenu; + std::function const&)> _cellChosen; + std::vector _cellMenuKeys; ///< The chords that ask for the focused cell's entries. + std::vector _visible; ///< The visible columns, as `setVisibleColumns` told them; empty: every one. + std::function _onColumnMove; + std::function _onFilter; + std::vector _filtered; + std::vector _groups; + std::vector _bands; + std::function _onGroupFilter; + std::function _onCopy; + std::optional _headerFocus; ///< The focused header's column; none while the rows have the focus. + MenuPopup _menuPopup{*this}; + + /// Whether the rows come from a `TableSource`: the mount places each row by its view index and each cell by its + /// column. + bool _source = false; + std::size_t _total = 0; ///< The rows of the view. + std::unordered_map _viewRows; ///< Each realized row's view index. + /// Each row's cells' columns, by `setCellColumn`; none for a pooled cell. + std::unordered_map>> + _cellColumns; + /// Each row's cells that are not loaded, by column. + std::unordered_map> _loads; + /// Each row's cells' accents, by column; a cell with none has no entry. + std::unordered_map> _accents; + /// A column of the mount's window: its index into `_columns`, its offset and its width. + struct WindowColumn { + std::size_t column = 0; + int offset = 0; + int width = 0; + }; + bool _arranged = false; ///< Whether the mount lays the columns out. + std::vector _window; + std::size_t _pinned = 0; + int _totalWidth = 0; + int _scrollX = 0; + std::function _onVisibleRange; + std::function _onHorizontalRange; + std::optional> _reportedRows; + std::optional> _reportedColumns; + std::function _onColumnMeasured; + std::vector _reportedMeasures; + std::function _onFocusMove; + std::function _onText; + std::function _onCellClick; + std::function _onFocusOut; + bool _focusWithin = false; ///< Whether the focus was in the table at the last frame. + bool _focusLeft = false; ///< Whether the next fit reports that the focus left the table. + /// Each row's open cell editor and the column it is drawn over. + std::unordered_map> _editors; + /// Each row's cells' marks, by column; a cell with none has no entry. + std::unordered_map> _cellMarks; + std::unordered_set _modifiedRows; + std::function _onSelectRange; + std::optional _anchorRow; ///< Over a source, where a range starts: a view row. + std::optional> _focusCell; ///< The focused cell's view row and column. + /// In cell mode, what a gesture that selects cells reports; empty selects rows. + std::function _onCellSelect; + /// The rectangle of selected cells, `{firstRow, rowCount, firstPosition, positionCount}`; none while empty. + std::optional> _cellRect; + ui::TableStatus _status; + std::function _onRetry; + int _retryX = -1; ///< Where `[Retry]` starts on the status line; -1 while it is not drawn. + std::function _onStatusEntry; + /// The status line's entries as drawn: where each starts, its width and its id; the n-th is chosen by `Alt+`. + struct DrawnEntry { + int x = 0; + int width = 0; + std::string entryId; + }; + std::vector _entriesDrawn; }; } // namespace morph::tui::detail diff --git a/src/tui/widget.cpp b/src/tui/widget.cpp index 3d1114cb9..c20fd1b86 100644 --- a/src/tui/widget.cpp +++ b/src/tui/widget.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -217,6 +218,15 @@ std::optional WidgetBase::effectiveRowTone() const noexcept { return std::nullopt; } +bool WidgetBase::effectiveRowMuted() const noexcept { + for (WidgetBase const* widget = this; widget != nullptr; widget = widget->_container) { + if (widget->_rowMuted) { + return true; + } + } + return false; +} + namespace { /// Whether the terminal draws a surface inverted: the dark navigator column and the top bar of the app shell, joined @@ -260,6 +270,17 @@ void colour(::core::tui::Buffer& buffer, ::core::tui::Rect area, ::core::tui::Co } } +/// Marks every cell of @p area dim: what a muted table row does to what its cells painted. +void dim(::core::tui::Buffer& buffer, ::core::tui::Rect area) { + for (int row = area.y; row < area.y + area.height; ++row) { + for (int col = area.x; col < area.x + area.width; ++col) { + if (auto* const cell = buffer.cellAt({.x = col, .y = row})) { + cell->style.dim = true; + } + } + } +} + } // namespace // A view whose drawn bounds are not a part of where it was laid out was not placed by a parent's area (an @@ -277,6 +298,9 @@ void WidgetBase::render(::core::tui::Canvas& canvas) { if (auto const tone = effectiveRowTone()) { colour(canvas.buffer(), drawn, toneStyle(canvas.theme(), *tone).fg); } + if (effectiveRowMuted()) { + dim(canvas.buffer(), drawn); + } if (invertsSurface(effectiveSurface())) { invert(canvas.buffer(), drawn); } @@ -555,11 +579,16 @@ ::core::tui::Point WidgetBase::viewportCellOf(::core::tui::MouseEvent const& mou } // Any press ends an earlier gesture whose release never arrived, whether or not this widget takes the new one, and -// the drag it started. Handling the press makes this view the screen's pointer capture target, so the moves and the -// release that follow come here wherever the pointer goes. A widget with a drag key arms a drag, and still takes the -// press as any other (a slider's thumb jumps to it). +// the drag it started. A right press goes to `contextPress`. Handling a left press makes this view the screen's +// pointer capture target, so the moves and the release that follow come here wherever the pointer goes. A widget with +// a drag key arms a drag, and still takes the press as any other (a slider's thumb jumps to it). EventResult WidgetBase::press(::core::tui::MouseEvent const& mouse) { _context->endPress(); + // The right button opens a context menu where the widget has one; it starts no gesture, so its release clicks + // nothing. + if (mouse.button == 2) { + return actionable() && contextPress(cellOf(mouse)) ? EventResult::Handled : EventResult::Ignored; + } if (mouse.button != 0 || !actionable() || !(takesPress() || _dragKey)) { return EventResult::Ignored; } @@ -1150,6 +1179,37 @@ ::core::tui::Point centredIn(::core::tui::Screen const& screen, ::core::tui::Siz .y = area.y + std::max(0, (area.height - size.height) / 2)}; } +namespace { + +// Reports the ranges of @p tables, skipping one a handler destroyed meanwhile. The watches are removed on every exit, +// a throwing handler's included. +void reportWindowRanges(Context& context, std::vector const& tables) { + std::vector alive(tables.begin(), tables.end()); + for (auto& each : alive) { + context.watches.push_back(&each); + } + auto const unwatch = [&context, &alive] { + for (auto& each : alive) { + std::erase(context.watches, &each); + } + }; + try { + for (std::size_t i = 0; i < tables.size(); ++i) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `i` is the loop index over `alive` + if (alive[i] != nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `tables` is built beside `alive` with one entry each, and `i` is the loop index over `alive` + tables[i]->reportRanges(); + } + } + } catch (...) { + unwatch(); + throw; + } + unwatch(); +} + +} // namespace + // A root view's own bounds are enough: hit-testing descends only into a view whose bounds hold the point, and a // root that is drawn empties those of its descendants itself (see View). A frame is no widget's view, so its // descendants are emptied here. @@ -1158,6 +1218,11 @@ void fit(Context& context) { if (context.pressed != nullptr && screen.pointerCapture() != &context.pressed->view()) { context.endPress(); } + // The rows and columns a table's last frame found in view, reported before any size is asked: the mount realizes + // them here, outside a frame's drawing. The list is taken first, so a report that asks for another frame adds + // its table for that frame. Each table taken is watched: a report's handler may destroy another one still to come, + // which is then skipped. + reportWindowRanges(context, std::exchange(context.windowTables, {})); // Before any size is asked: what a span lifts or covers decides its table's rows' heights. Planning may drop the // table from the list, so the loop walks a copy. for (auto* const table : std::vector{context.spanTables}) { diff --git a/src/tui/widget.hpp b/src/tui/widget.hpp index 50dfaa2d8..444d34d0c 100644 --- a/src/tui/widget.hpp +++ b/src/tui/widget.hpp @@ -123,12 +123,18 @@ class WidgetBase { [[nodiscard]] std::string const& effectiveSurface() const noexcept; /// Keeps a table row's tone, which its cells draw in. void applyRowTone(std::optional tone) noexcept { _rowTone = tone; } + /// Keeps whether a table row is muted, which its cells draw dim. + void applyRowMuted(bool muted) noexcept { _rowMuted = muted; } + /// Whether the widget draws dim: its own row is muted, or its nearest container's. + [[nodiscard]] bool effectiveRowMuted() const noexcept; /// The tone the widget draws in: its own row tone, or else its nearest container's; none for no toned row. [[nodiscard]] std::optional effectiveRowTone() const noexcept; /// Sets the text core::tui's hover shows; empty shows none. void applyTooltip(std::string_view text) { _tooltip = text; } - /// What the hover shows: the tooltip, and a field adds its messages. - [[nodiscard]] virtual std::string hoverText() const { return _tooltip; } + /// Sets what a table row's marks say on hover, which wins over its own tooltip; empty leaves the tooltip. + void applyMarksTooltip(std::string_view text) { _marksTooltip = text; } + /// What the hover shows: a row's marks' text, else the tooltip, and a field adds its messages. + [[nodiscard]] virtual std::string hoverText() const { return _marksTooltip.empty() ? _tooltip : _marksTooltip; } /// What assistive technology reads as the widget's description; none for a widget that is not described. [[nodiscard]] virtual std::string accessibleDescription() const { return {}; } /// Declares the chords this widget handles while the focus is inside it. @@ -196,6 +202,12 @@ class WidgetBase { /// A left press on @p cell (0-based, relative to this widget) that this widget took, after it took the focus /// when it takes it on a press. It may destroy the widget. virtual void pressAt(::core::tui::Point cell); + /// A right press on @p cell (0-based, relative to this widget), while the widget is actionable: a context menu's + /// gesture. Returns whether the widget took it; by default none does, and the press goes on outwards. + [[nodiscard]] virtual bool contextPress(::core::tui::Point cell) { + static_cast(cell); + return false; + } /// The pointer moved to @p cell (relative to this widget, and possibly outside it) while a press this widget took /// lasts and the widget is actionable. It may destroy the widget. virtual void dragTo(::core::tui::Point cell); @@ -265,7 +277,9 @@ class WidgetBase { std::uint64_t _sequence; std::string _surface; std::optional _rowTone; + bool _rowMuted = false; std::string _tooltip; + std::string _marksTooltip; std::vector _chords; std::function _onChord; ::core::tui::Point _drawShift{}; @@ -607,6 +621,13 @@ struct CellPlace { ui::Align down = ui::Align::Center; ///< Start, Center or End; Stretch fills the row's height. }; +/// Where a table cell is drawn in its row when the table places each cell by its column: from @p x, @p width cells. +struct CellSlot { + int x = 0; ///< The slot's start, from the row's start. + int width = 0; ///< The cells it takes; 0 gives the child no area. + CellPlace place; ///< Where the cell sits in the slot. +}; + /// How `arrangeStack` places children. struct StackSpec { ui::Axis axis = ui::Axis::Vertical; ///< The main axis. diff --git a/src/ui/cell_format.cpp b/src/ui/cell_format.cpp new file mode 100644 index 000000000..11012aa86 --- /dev/null +++ b/src/ui/cell_format.cpp @@ -0,0 +1,513 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui::detail::cells { + +std::optional digitsOf(std::string_view text) { + Digits out; + if (text.starts_with('-')) { + out.negative = true; + text.remove_prefix(1); + } + auto const dot = text.find('.'); + out.whole = std::string{text.substr(0, dot)}; + if (dot != std::string_view::npos) { + out.fraction = std::string{text.substr(dot + 1)}; + } + auto const digit = [](char glyph) { return glyph >= '0' && glyph <= '9'; }; + if (out.whole.empty() || !std::ranges::all_of(out.whole, digit) || !std::ranges::all_of(out.fraction, digit) || + (dot != std::string_view::npos && out.fraction.empty())) { + return std::nullopt; + } + return out; +} + +std::string textOf(Digits const& digits) { + bool const zero = std::ranges::all_of(digits.whole, [](char glyph) { return glyph == '0'; }) && + std::ranges::all_of(digits.fraction, [](char glyph) { return glyph == '0'; }); + std::string out = digits.negative && !zero ? "-" : ""; + out += digits.whole; + if (!digits.fraction.empty()) { + out += '.'; + out += digits.fraction; + } + return out; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): the rounding decision reads the dropped tail, the half cases of each Rounding mode and the pad rule in sequence, each step needing the digits the one before left +std::string roundText(Digits digits, std::size_t places, table::Rounding rounding, bool pad) { + if (digits.fraction.size() > places) { + std::string_view const dropped = std::string_view{digits.fraction}.substr(places); + bool const restZero = std::ranges::all_of(dropped.substr(1), [](char glyph) { return glyph == '0'; }); + char const first = dropped.front(); + digits.fraction.resize(places); + bool roundUp = false; + if (first > '5' || (first == '5' && !restZero)) { + roundUp = true; + } else if (first == '5') { + char const last = places > 0 ? digits.fraction.back() : digits.whole.back(); + roundUp = rounding == table::Rounding::HalfUp || ((last - '0') % 2) != 0; + } + if (roundUp) { + std::string all = digits.whole + digits.fraction; + std::size_t index = all.size(); + while (index > 0) { + --index; + if (all.at(index) == '9') { + all.at(index) = '0'; + } else { + ++all.at(index); + break; + } + if (index == 0) { + all.insert(all.begin(), '1'); + } + } + digits.whole = all.substr(0, all.size() - places); + digits.fraction = all.substr(all.size() - places); + } + } + if (pad) { + digits.fraction.resize(places, '0'); + } else { + while (!digits.fraction.empty() && digits.fraction.back() == '0') { + digits.fraction.pop_back(); + } + } + return textOf(digits); +} + +std::string exactText(math::Rational const& value, std::uint32_t places) { + auto const den = static_cast(value.denominator); + std::uint64_t const magnitude = math::detail::absU64(value.numerator); + Digits out{.negative = value.numerator < 0, .whole = std::to_string(magnitude / den), .fraction = {}}; + std::uint64_t remainder = magnitude % den; + for (std::uint32_t at = 0; at < places; ++at) { + // The next digit of remainder * 10 / den, without forming remainder * 10, which may not fit in 64 bits. + std::uint64_t accumulated = 0; + std::uint64_t digit = 0; + for (int step = 0; step < 10; ++step) { + accumulated += remainder; + while (accumulated >= den) { + accumulated -= den; + ++digit; + } + } + remainder = accumulated; + out.fraction.push_back(static_cast('0' + digit)); + } + return textOf(out); +} + +std::optional doubleText(double value) { + if (!std::isfinite(value)) { + return std::nullopt; + } + // The longest fixed text of a finite double: 309 integer digits, a sign, a point and 767 fraction digits. + std::array buffer{}; + auto const written = std::to_chars(buffer.data(), std::to_address(buffer.end()), value, std::chars_format::fixed); + if (written.ec != std::errc{}) { + return std::nullopt; + } + return std::string{buffer.data(), written.ptr}; +} + +std::optional readText(std::string const& text, table::ColumnKind kind) { + using table::ColumnKind; + switch (kind) { + case ColumnKind::Integer: + case ColumnKind::Key: { + std::int64_t value = 0; + auto const read = std::from_chars(text.data(), std::to_address(text.end()), value); + if (read.ec == std::errc{} && read.ptr == std::to_address(text.end()) && !text.empty()) { + return table::Cell{value}; + } + if (kind == ColumnKind::Key) { + return table::Cell{text}; + } + return std::nullopt; + } + case ColumnKind::Decimal: + case ColumnKind::Quantity: + if (auto parsed = table::parseDecimal(text)) { + return table::Cell{*parsed}; + } + return std::nullopt; + case ColumnKind::Number: { + if (auto parsed = table::parseDecimal(text)) { + return table::Cell{*parsed}; + } + // A double no exact decimal holds (1e+21, 1e-20, 9.3e+18) is its own text in a record; it is still a + // number, shown from its shortest fixed-notation text. + if (auto const number = table::detail::parseReal(text)) { + return table::Cell{*number}; + } + return std::nullopt; + } + case ColumnKind::Bool: + if (text == "true" || text == "false") { + return table::Cell{text == "true"}; + } + return std::nullopt; + case ColumnKind::Text: + case ColumnKind::Date: + case ColumnKind::DateTime: + case ColumnKind::Custom: + case ColumnKind::Measure: + default: + return table::Cell{text}; + } +} + +std::optional normalized(table::Cell const& cell, table::ColumnKind kind) { + if (auto const* const text = std::get_if(&cell)) { + return readText(*text, kind); + } + return cell; +} + +std::optional numberText(table::Cell const& cell, table::ColumnDisplay const& display) { + auto const ofRational = [&display](math::Rational const& value) -> std::optional { + std::uint32_t const places = + std::min(display.decimals.value_or(value.decimalPlaces.value), math::kMaxDecimalPlaces); + math::RoundingMode const mode = + display.decimals ? modeOf(display.rounding) : math::RoundingMode::HalfAwayFromZero; + auto const rounded = math::checkedRoundToDecimalPlaces(value, math::DecimalPlaces{places}, mode); + if (!rounded) { + return std::nullopt; + } + // NOLINTNEXTLINE(misc-const-correctness): returned by name, which moves it; a const would be copied. + std::string text = exactText(*rounded, places); + if (!display.decimals || display.padPlaces) { + return text; + } + return roundText(*digitsOf(text), places, display.rounding, false); + }; + auto const ofText = [&display](std::string const& text) -> std::optional { + auto const digits = digitsOf(text); + if (!digits) { + return std::nullopt; + } + if (!display.decimals) { + return textOf(*digits); + } + return roundText(*digits, *display.decimals, display.rounding, display.padPlaces); + }; + if (auto const* const integer = std::get_if(&cell)) { + return ofText(std::to_string(*integer)); + } + if (auto const* const rational = std::get_if(&cell)) { + return ofRational(*rational); + } + if (auto const* const number = std::get_if(&cell)) { + auto const text = doubleText(*number); + return text ? ofText(*text) : std::nullopt; + } + if (auto const* const quantity = std::get_if(&cell)) { + auto const canonical = math::checkedMul(quantity->amount, quantity->toCanonical); + return canonical ? ofRational(*canonical) : std::nullopt; + } + return std::nullopt; +} + +std::optional> measureText(table::Measure const& measure, + DisplayUnits const& units) { + if (units.units == nullptr || !units.units->contains(measure.unit)) { + return std::nullopt; + } + table::UnitInfo const& own = units.units->info(measure.unit); + table::UnitInfo const* shown = &own; + math::Rational amount = measure.amount; + if (auto const chosen = units.byDimension.find(own.dimension); chosen != units.byDimension.end()) { + if (auto const target = units.units->find(chosen->second); target && *target != measure.unit) { + table::UnitInfo const& toUnit = units.units->info(*target); + if (toUnit.dimension == own.dimension) { + auto const base = math::checkedMul(measure.amount, own.toBase); + auto const converted = base ? math::checkedDiv(*base, toUnit.toBase) : base; + if (!converted) { + return std::nullopt; + } + amount = *converted; + shown = &toUnit; + } + } + } + std::uint32_t const places = std::min(shown->decimals, math::kMaxDecimalPlaces); + auto const rounded = + math::checkedRoundToDecimalPlaces(amount, math::DecimalPlaces{places}, math::RoundingMode::HalfEven); + if (!rounded) { + return std::nullopt; + } + return std::pair{exactText(*rounded, places), shown->symbol}; +} + +std::string dateText(std::int64_t value, table::TableColumn const& column, FormatContext const& locale) { + bool const withTime = column.info.kind == table::ColumnKind::DateTime; + // Days of 0000-01-01 and of 9999-12-31 from the epoch: the range a four-digit year spells. + constexpr std::int64_t kFirstDay = -719'528; + constexpr std::int64_t kLastDay = 2'932'896; + constexpr std::int64_t kDaySeconds = 86'400; + std::int64_t seconds = 0; + if (!withTime) { + if (value < kFirstDay || value > kLastDay) { + return std::to_string(value); + } + seconds = value * kDaySeconds; + } else { + // A zone is less than a day from UTC: a value a day past either end is out of range in every zone, and the + // shift below cannot overflow. + if (value < (kFirstDay - 1) * kDaySeconds || value >= (kLastDay + 2) * kDaySeconds) { + return std::to_string(value); + } + seconds = value + (std::int64_t{locale.utcOffsetMinutes} * 60); + if (seconds < kFirstDay * kDaySeconds || seconds >= (kLastDay + 1) * kDaySeconds) { + return std::to_string(value); + } + } + time::DateTime const local{std::chrono::sys_time{std::chrono::seconds{seconds}}}; + std::string const& sessions = withTime ? locale.dateTimePattern : locale.datePattern; + std::string_view const pattern = + !column.display.date.empty() ? std::string_view{column.display.date} : std::string_view{sessions}; + if (!pattern.empty()) { + if (std::string text = formatDate(pattern, local, locale.utcOffsetMinutes); !text.empty()) { + return text; + } + } + return formatDate(withTime ? "yyyy-MM-dd HH:mm" : "yyyy-MM-dd", local, locale.utcOffsetMinutes); +} + +bool sameOperand(std::string_view label, std::string_view operand, table::ColumnKind kind) { + if (kind == table::ColumnKind::Decimal || kind == table::ColumnKind::Number) { + auto const lhs = table::parseDecimal(label); + auto const rhs = table::parseDecimal(operand); + if (lhs && rhs) { + return *lhs == *rhs; + } + } + return label == operand; +} + +} // namespace morph::ui::detail::cells + +namespace morph::ui { + +CellLook cellLook(table::Cell const& cell, table::TableColumn const& column, DisplayUnits const& units) { + if (std::holds_alternative(cell)) { + return CellLook::Unloaded; + } + if (std::holds_alternative(cell)) { + return CellLook::Empty; + } + auto const read = detail::cells::normalized(cell, column.info.kind); + if (!read) { + return CellLook::Invalid; + } + if (auto const* const measure = std::get_if(&*read)) { + return detail::cells::measureText(*measure, units) ? CellLook::Text : CellLook::Invalid; + } + bool const number = std::holds_alternative(*read) || std::holds_alternative(*read) || + std::holds_alternative(*read) || std::holds_alternative(*read); + bool const dated = column.info.kind == table::ColumnKind::Date || column.info.kind == table::ColumnKind::DateTime; + if (number && !dated && !detail::cells::numberText(*read, column.display)) { + return CellLook::Invalid; + } + return CellLook::Text; +} + +std::optional operandOf(table::Cell const& cell, table::TableColumn const& column, + DisplayUnits const& units) { + if (CellLook const look = cellLook(cell, column, units); look != CellLook::Text) { + return std::nullopt; + } + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): a cell with a look has a normalized value. + table::Cell const read = *detail::cells::normalized(cell, column.info.kind); + return std::visit( + [&](T const& value) -> std::optional { + if constexpr (std::is_same_v || std::is_same_v) { + return std::nullopt; + } else if constexpr (std::is_same_v) { + return std::to_string(value); + } else if constexpr (std::is_same_v) { + return units::detail::formatRationalDecimal(value); + } else if constexpr (std::is_same_v) { + return detail::cells::doubleText(value); + } else if constexpr (std::is_same_v) { + return std::string{value ? "true" : "false"}; + } else if constexpr (std::is_same_v) { + return value; + } else if constexpr (std::is_same_v) { + auto const canonical = math::checkedMul(value.amount, value.toCanonical); + return canonical ? std::optional{units::detail::formatRationalDecimal(*canonical)} : std::nullopt; + } else { + static_assert(std::is_same_v); + return units::detail::formatRationalDecimal(value.amount) + " " + units.units->info(value.unit).id; + } + }, + read); +} + +table::Cell cellOfOperand(std::string_view operand, table::TableColumn const& column, DisplayUnits const& units) { + using table::ColumnKind; + std::string const text{operand}; + switch (column.info.kind) { + case ColumnKind::Integer: + case ColumnKind::Key: + case ColumnKind::Date: + case ColumnKind::DateTime: { + std::int64_t value = 0; + auto const read = std::from_chars(text.data(), std::to_address(text.end()), value); + if (read.ec == std::errc{} && read.ptr == std::to_address(text.end()) && !text.empty()) { + return table::Cell{value}; + } + return table::Cell{text}; + } + case ColumnKind::Decimal: + case ColumnKind::Quantity: + if (auto parsed = table::parseDecimal(text)) { + return table::Cell{*parsed}; + } + return table::Cell{text}; + case ColumnKind::Number: { + if (auto const value = table::detail::parseReal(text)) { + return table::Cell{*value}; + } + return table::Cell{text}; + } + case ColumnKind::Bool: + if (text == "true" || text == "false") { + return table::Cell{text == "true"}; + } + return table::Cell{text}; + case ColumnKind::Measure: { + auto const space = text.find(' '); + auto const amount = table::parseDecimal(std::string_view{text}.substr(0, space)); + std::string_view const columnId = + space == std::string::npos ? std::string_view{} : std::string_view{text}.substr(space + 1); + if (!amount) { + return table::Cell{text}; + } + std::optional const unit = + units.units != nullptr ? units.units->find(columnId) : std::nullopt; + return table::Cell{table::Measure{.amount = *amount, .unit = unit.value_or(table::kUnknownUnit)}}; + } + case ColumnKind::Text: + case ColumnKind::Custom: + default: + return table::Cell{text}; + } +} + +std::string formatCell(table::Cell const& cell, table::TableColumn const& column, FormatContext const& locale, + DisplayUnits const& units) { + CellLook const look = cellLook(cell, column, units); + if (look == CellLook::Unloaded || look == CellLook::Invalid) { + return {}; + } + if (look == CellLook::Empty) { + return column.display.empty; + } + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): a cell with a look has a normalized value. + table::Cell const read = *detail::cells::normalized(cell, column.info.kind); + if (!column.display.labels.empty()) { + if (std::optional const operand = operandOf(read, column, units)) { + for (table::ValueLabel const& label : column.display.labels) { + if (detail::cells::sameOperand(label.operand, *operand, column.info.kind)) { + return label.text; + } + } + } + } + render::NumericLocale const numbers = column.display.grouping ? locale.numeric : withoutGrouping(locale.numeric); + bool const dated = column.info.kind == table::ColumnKind::Date || column.info.kind == table::ColumnKind::DateTime; + if (auto const* const days = std::get_if(&read); days != nullptr && dated) { + return detail::cells::dateText(*days, column, locale); + } + if (auto const* const measure = std::get_if(&read)) { + if (auto const shown = detail::cells::measureText(*measure, units)) { + std::string out = render::formatCanonicalNumber(shown->first, numbers); + if (!shown->second.empty()) { + out += ' '; + out += shown->second; + } + return out; + } + } + if (auto const text = detail::cells::numberText(read, column.display)) { + return render::formatCanonicalNumber(*text, numbers); + } + return table::displayText(read); +} + +std::vector distinctTexts(std::span values, table::TableColumn const& column, + FormatContext const& locale, DisplayUnits const& units) { + std::vector out; + out.reserve(values.size()); + for (table::DistinctValue const& value : values) { + // A date bucket's operand is a range (`a..b`), which no cell holds: the server's text names it. + if (value.operand.contains("..")) { + out.push_back(value.text); + continue; + } + out.push_back(formatCell(cellOfOperand(value.operand, column, units), column, locale, units)); + } + table::TableColumn ownPlaces = column; + ownPlaces.display.decimals.reset(); + std::vector const first = out; + for (std::size_t at = 0; at < out.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `out` has one text per value. + if (std::ranges::count(first, first.at(at)) > 1 && !values[at].operand.contains("..")) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `out` has one text per value. + out.at(at) = formatCell(cellOfOperand(values[at].operand, column, units), ownPlaces, locale, units); + } + } + return out; +} + +std::string headerText(std::string_view label, std::string_view unit) { + if (unit.empty()) { + return std::string{label}; + } + return std::format("{} [{}]", label, unit); +} + +std::string headerAccessibleName(std::string_view label, std::string_view unit) { + if (unit.empty()) { + return std::string{label}; + } + return std::format("{}, {}", label, unit); +} + +} // namespace morph::ui diff --git a/src/ui/custom_screen_checks.cpp b/src/ui/custom_screen_checks.cpp index cce1cc668..7c204d91f 100644 --- a/src/ui/custom_screen_checks.cpp +++ b/src/ui/custom_screen_checks.cpp @@ -464,28 +464,53 @@ namespace detail { namespace { // NOLINTBEGIN(modernize-use-designated-initializers): the table reads as rows. -constexpr std::array kEventKeys = {{ - {"button", "onClick", EventClass::Press}, {"button", "onActivate", EventClass::Press}, - {"textInput", "onChange", EventClass::Press}, {"textInput", "onCommit", EventClass::Press}, - {"textInput", "onSubmit", EventClass::Press}, {"checkbox", "onToggle", EventClass::Press}, - {"checkbox", "onChange", EventClass::Press}, {"select", "onChoose", EventClass::Press}, - {"select", "onChange", EventClass::Press}, {"panel", "onToggle", EventClass::Press}, - {"tabs", "onChoose", EventClass::Press}, {"dialog", "onDismiss", EventClass::Press}, - {"dialog", "default", EventClass::Press}, {"dialog", "cancel", EventClass::Press}, - {"drawer", "onDismiss", EventClass::Press}, {"drawer", "default", EventClass::Press}, - {"drawer", "cancel", EventClass::Press}, {"table", "onSelectionChange", EventClass::Press}, - {"table", "onSortChange", EventClass::Press}, {"table", "onActivate", EventClass::Press}, - {"dateTimeInput", "onChange", EventClass::Press}, {"dateTimeInput", "onCommit", EventClass::Press}, - {"slider", "onChange", EventClass::Press}, {"slider", "onCommit", EventClass::Press}, - {"filePicker", "onPick", EventClass::ChosenFile}, {"banner", "onDismiss", EventClass::Press}, - {"badge", "onRemove", EventClass::Press}, {"collapsible", "onToggle", EventClass::Press}, - {"dropZone", "onDrop", EventClass::ChosenFile}, {"form", "onSubmit", EventClass::FormOutcome}, - {"form", "onSuccess", EventClass::FormOutcome}, {"form", "onError", EventClass::FormOutcome}, - {"custom", "on", EventClass::ComponentEvent}, {"menuItem", "onClick", EventClass::Press}, - {"action", "onClick", EventClass::Press}, {"drop", "onDrop", EventClass::Press}, - {"actionButton", "onClick", EventClass::Press}, {"headMenuItem", "onClick", EventClass::Press}, - {"headTool", "onChange", EventClass::Press}, {"headTool", "onSubmit", EventClass::Press}, +constexpr std::array kEventKeys = {{ + {"button", "onClick", EventClass::Press}, + {"button", "onActivate", EventClass::Press}, + {"textInput", "onChange", EventClass::Press}, + {"textInput", "onCommit", EventClass::Press}, + {"textInput", "onSubmit", EventClass::Press}, + {"checkbox", "onToggle", EventClass::Press}, + {"checkbox", "onChange", EventClass::Press}, + {"select", "onChoose", EventClass::Press}, + {"select", "onChange", EventClass::Press}, + {"panel", "onToggle", EventClass::Press}, + {"tabs", "onChoose", EventClass::Press}, + {"dialog", "onDismiss", EventClass::Press}, + {"dialog", "default", EventClass::Press}, + {"dialog", "cancel", EventClass::Press}, + {"drawer", "onDismiss", EventClass::Press}, + {"drawer", "default", EventClass::Press}, + {"drawer", "cancel", EventClass::Press}, + {"table", "onSelectionChange", EventClass::Press}, + {"table", "onSortChange", EventClass::Press}, + {"table", "onActivate", EventClass::Press}, + {"dateTimeInput", "onChange", EventClass::Press}, + {"dateTimeInput", "onCommit", EventClass::Press}, + {"slider", "onChange", EventClass::Press}, + {"slider", "onCommit", EventClass::Press}, + {"filePicker", "onPick", EventClass::ChosenFile}, + {"banner", "onDismiss", EventClass::Press}, + {"badge", "onRemove", EventClass::Press}, + {"collapsible", "onToggle", EventClass::Press}, + {"dropZone", "onDrop", EventClass::ChosenFile}, + {"form", "onSubmit", EventClass::FormOutcome}, + {"form", "onSuccess", EventClass::FormOutcome}, + {"form", "onError", EventClass::FormOutcome}, + {"custom", "on", EventClass::ComponentEvent}, + {"menuItem", "onClick", EventClass::Press}, + {"action", "onClick", EventClass::Press}, + {"drop", "onDrop", EventClass::Press}, + {"actionButton", "onClick", EventClass::Press}, + {"headMenuItem", "onClick", EventClass::Press}, + {"headTool", "onChange", EventClass::Press}, + {"headTool", "onSubmit", EventClass::Press}, {"headTool", "onChoose", EventClass::Press}, + {"table", "onFiltersChange", EventClass::Press}, + {"table", "onLayoutChange", EventClass::Press}, + {"fieldGrid", "onActivate", EventClass::Press}, + {"fieldGrid", "onFiltersChange", EventClass::Press}, + {"fieldGrid", "onLayoutChange", EventClass::Press}, }}; // NOLINTEND(modernize-use-designated-initializers) diff --git a/src/ui/document.cpp b/src/ui/document.cpp index 76b93f0c1..6f692b7fa 100644 --- a/src/ui/document.cpp +++ b/src/ui/document.cpp @@ -13,7 +13,11 @@ #include #include #include +#include #include +#include +#include +#include #include #include #include @@ -105,9 +109,11 @@ constexpr std::array kSelectValues = {"selected", "selected /// @brief The element values of a tabs node: the id of the tab shown. constexpr std::array kTabsValues = {"selected"}; /// @brief The element values of a table. -constexpr std::array kTableValues = { - "selection", "activeKey", "sort", "filters", "viewCount", "sourceCount", "selectedCount", - "pending", "error", "hoveredKey", "page", "pageCount", "pageFirst", "pageLast"}; +constexpr std::array kTableValues = { + "selection", "activeKey", "sort", "filters", "viewCount", "sourceCount", + "selectedCount", "pending", "error", "hoveredKey", "page", "pageCount", + "pageFirst", "pageLast", "layout", "visibleColumns", "hiddenCount", "selectionSet", + "selectedCountKind", "busyCount", "modifiedCount", "modifiedRows", "errorCount", "editing"}; /// @brief The element values of a dialog or drawer. constexpr std::array kDialogValues = {"open", "ready", "submitted"}; /// @brief The element values of a form, beside its fields. @@ -293,50 +299,144 @@ constexpr std::array kForEachKeys = {{{"rows", Shape::Expr, {}, kReq {"divided", Shape::Flag}, {"children", Shape::Nodes, {}, kInner}}}; /// @brief The keys of `table`. -constexpr std::array kTableKeys = {{{"rows", Shape::Expr}, - {"key", Shape::Expr, {}, kInner}, - {"model", Shape::Name}, - {"action", Shape::Text}, - {"body", Shape::Expr}, - {"mode", Shape::Expr}, - {"columns", Shape::PartsOrExpr, "column"}, - {"showHeader", Shape::Flag}, - {"virtualizeThreshold", Shape::Expr}, - {"virtualizeOverscan", Shape::Expr}, - {"selectionMode", Shape::Expr}, - {"selection", Shape::Expr}, - {"onSelectionChange", Shape::Commands}, - {"selectColumn", Shape::Flag}, - {"selectAllLabel", Shape::Expr}, - {"rowLabel", Shape::Expr, {}, kInner}, - {"sort", Shape::Expr}, - {"onSortChange", Shape::Commands}, - {"pageSize", Shape::Expr}, - {"page", Shape::Expr}, - {"group", Shape::Part, "group"}, - {"filters", Shape::Expr}, - {"rowTone", Shape::Expr, {}, kInner}, - {"rowSpans", Shape::Expr, {}, kInner}, - {"highlightKey", Shape::Expr}, - {"onActivate", Shape::Commands, {}, kInner}, - {"valign", Shape::Text}, - {"empty", Shape::Nodes}}}; -/// @brief The keys of a `table` column part. -constexpr std::array kColumnKeys = {{{"id", Shape::Name}, +constexpr auto kTableKeys = std::to_array({{"rows", Shape::Expr}, + {"form", Shape::Text}, + {"field", Shape::Text}, + {"enterMoves", Shape::Text}, + {"walk", Shape::Text}, + {"editMode", Shape::Text}, + {"appendRows", Shape::Flag}, + {"rowsFixed", Shape::Flag}, + {"key", Shape::Expr, {}, kInner}, + {"model", Shape::Name}, + {"table", Shape::Name}, + {"action", Shape::Text}, + {"status", Shape::Flag}, + {"retainChanged", Shape::Flag}, + {"persist", Shape::Expr}, + {"body", Shape::Expr}, + {"mode", Shape::Expr}, + {"columns", Shape::PartsOrExpr, "column"}, + {"showHeader", Shape::Flag}, + {"virtualizeThreshold", Shape::Expr}, + {"virtualizeOverscan", Shape::Expr}, + {"selectionMode", Shape::Expr}, + {"selection", Shape::Expr}, + {"onSelectionChange", Shape::Commands}, + {"selectColumn", Shape::Flag}, + {"selectAllLabel", Shape::Expr}, + {"rowLabel", Shape::Expr, {}, kInner}, + {"sort", Shape::Expr}, + {"onSortChange", Shape::Commands}, + {"maxSortKeys", Shape::Expr}, + {"layout", Shape::Expr}, + {"onLayoutChange", Shape::Commands}, + {"configurable", Shape::Expr}, + {"onFiltersChange", Shape::Commands}, + {"pageSize", Shape::Expr}, + {"page", Shape::Expr}, + {"group", Shape::Part, "group"}, + {"groups", Shape::Parts, "columnGroup"}, + {"filters", Shape::Expr}, + {"rowTone", Shape::Expr, {}, kInner}, + {"rowSpans", Shape::Expr, {}, kInner}, + {"highlightKey", Shape::Expr}, + {"onActivate", Shape::Commands, {}, kInner}, + {"valign", Shape::Text}, + {"empty", Shape::Nodes}, + {"cellMenu", Shape::Parts, "menuItem", kInner}, + {"headerMenu", Shape::Parts, "menuItem"}, + {"headerEnabled", Shape::Condition}, + {"bands", Shape::Parts, "band"}, + {"summaries", Shape::Parts, "summary"}, + {"layoutRows", Shape::Parts, "layoutRow"}}); +/// @brief The keys of a `table` column part; `tone` and `tooltip` are read in the row's scope. +constexpr std::array kColumnKeys = {{{"id", Shape::Name}, + {"field", Shape::Text}, + {"value", Shape::Expr, {}, kInner}, + {"kind", Shape::Text}, {"label", Shape::Expr}, {"width", Shape::Expr}, {"role", Shape::Expr}, {"align", Shape::Text}, {"valign", Shape::Text}, {"sortable", Shape::Flag}, + {"locked", Shape::Flag}, + {"filterable", Shape::Flag}, {"wrap", Shape::Flag}, {"shrink", Shape::Flag}, {"sortBy", Shape::Expr, {}, kInner}, - {"cell", Shape::Nodes, {}, kInner}}}; + {"cell", Shape::Nodes, {}, kInner}, + {"decimals", Shape::Expr}, + {"rounding", Shape::Text}, + {"padPlaces", Shape::Flag}, + {"grouping", Shape::Flag}, + {"empty", Shape::Text}, + {"unit", Shape::Text}, + {"date", Shape::Text}, + {"labels", Shape::Expr}, + {"tone", Shape::Expr, {}, kInner}, + {"tooltip", Shape::Expr, {}, kInner}, + {"readonly", Shape::Expr}, + {"options", Shape::Expr}, + {"placeholder", Shape::Expr}}}; +/// @brief The keys of a form field overlay's `grid` part: the keys a `table` over a `form` takes beyond its `form` and +/// `field`, its columns, walk and activation, its layout, menus and filters. +constexpr auto kGridPartKeys = std::to_array({{"columns", Shape::Parts, "column"}, + {"enterMoves", Shape::Text}, + {"walk", Shape::Text}, + {"appendRows", Shape::Flag}, + {"rowsFixed", Shape::Flag}, + {"onActivate", Shape::Commands}, + {"layout", Shape::Expr}, + {"onLayoutChange", Shape::Commands}, + {"configurable", Shape::Expr}, + {"onFiltersChange", Shape::Commands}, + {"cellMenu", Shape::Parts, "menuItem", kInner}, + {"headerMenu", Shape::Parts, "menuItem"}, + {"headerEnabled", Shape::Condition}, + {"testId", Shape::Text}, + {"bands", Shape::Parts, "band"}, + {"summaries", Shape::Parts, "summary"}}); +/// @brief The keys of a `table` column group part: the group's id, its label and its columns' ids, a literal list. +constexpr std::array kColumnGroupKeys = { + {{"id", Shape::Name, {}, kRequired}, {"label", Shape::Expr}, {"columns", Shape::Expr, {}, kRequired}}}; +/// @brief The keys of a fixed grid's `layoutRows` part: a row, `{key, label, cells}`, or a block, `{forEach, rows}`, +/// whose rows repeat for each row of the form's collection `forEach` names. +constexpr auto kLayoutRowKeys = std::to_array({{"key", Shape::Text}, + {"label", Shape::Expr}, + {"cells", Shape::ExprRecord, "layoutCells"}, + {"forEach", Shape::Text}, + {"rows", Shape::Parts, "layoutRow"}}); +/// @brief The keys of a fixed grid's cell part, by the column id it is given under: the form field it edits, the +/// expression or the text it shows, the rows and columns it spans, and its overlays, a grid column's. +constexpr auto kLayoutCellKeys = std::to_array({{"field", Shape::Text}, + {"value", Shape::Expr}, + {"text", Shape::Text}, + {"rows", Shape::Expr}, + {"columns", Shape::Expr}, + {"decimals", Shape::Expr}, + {"unit", Shape::Expr}, + {"readonly", Shape::Expr}, + {"options", Shape::Expr}, + {"placeholder", Shape::Expr}}); /// @brief The keys of a `table` group part: the value its rows are grouped by, and the heading drawn before each -/// group, both read in the row scope. -constexpr std::array kTableGroupKeys = { - {{"by", Shape::Expr, {}, kInner | kRequired}, {"heading", Shape::Nodes, {}, kInner | kRequired}}}; +/// group, both read in the row scope, and the summary rows drawn after each group. +constexpr auto kTableGroupKeys = std::to_array({{"by", Shape::Expr, {}, kInner | kRequired}, + {"heading", Shape::Nodes, {}, kInner | kRequired}, + {"summaries", Shape::Parts, "summary"}}); +/// @brief The keys of a header band part: its text, its unit, its columns' ids (a literal list) and the bands one +/// level down. +constexpr auto kBandKeys = std::to_array({{"label", Shape::Text}, + {"unit", Shape::Text}, + {"columns", Shape::Expr, {}, kRequired}, + {"bands", Shape::Parts, "band"}}); +/// @brief The keys of a summary row part: its key, its label, where it is drawn, and its cells' expressions by column +/// id, read in a scope with `rows` and `column`. +constexpr auto kSummaryKeys = std::to_array({{"key", Shape::Text, {}, kRequired}, + {"label", Shape::Expr}, + {"position", Shape::Text}, + {"cells", Shape::ExprRecord}}); /// @brief The keys of `dateTimeInput`. constexpr std::array kDateTimeKeys = {{{"value", Shape::Expr}, {"mode", Shape::Expr}, @@ -469,7 +569,7 @@ constexpr std::array kCustomizeKeys = {{{"point", Shape::Name, {}, k constexpr std::array kBoundaryKeys = { {{"loading", Shape::Nodes}, {"error", Shape::Nodes, {}, kBoundaryError}, {"children", Shape::Nodes}}}; /// @brief The keys of `form`. -constexpr std::array kFormKeys = {{{"model", Shape::Name, {}, kRequired}, +constexpr std::array kFormKeys = {{{"model", Shape::Name, {}, kRequired}, {"action", Shape::Text, {}, kRequired}, {"prefill", Shape::Expr}, {"key", Shape::Expr}, @@ -484,7 +584,9 @@ constexpr std::array kFormKeys = {{{"model", Shape::Name, {}, kRequ {"showStatus", Shape::Flag}, {"columns", Shape::Expr}, {"fieldLayout", Shape::Text}, - {"captionWidth", Shape::Expr}}}; + {"captionWidth", Shape::Expr}, + {"derive", Shape::Text}, + {"deriveDebounce", Shape::Expr}}}; /// @brief The keys of `collection` and `wizard`: the model and action, and the presentation keys that reach every /// form the view draws. constexpr std::array kCollectionKeys = {{{"model", Shape::Name, {}, kRequired}, @@ -506,7 +608,7 @@ constexpr std::array kDragKeys = {{{"payload", Shape::Expr, {}, kReq constexpr std::array kDropKeys = {{{"accepts", Shape::Expr}, {"onDrop", Shape::Commands}}}; /// @brief The view node kinds of `ui/1` and the part kinds inside them. -constexpr std::array kKinds = {{ +constexpr auto kKinds = std::to_array({ {"text", kTextKeys, kField}, {"button", kButtonKeys}, {"textInput", kTextInputKeys, kField | kWritable, kInputValues}, @@ -554,7 +656,14 @@ constexpr std::array kKinds = {{ {"case", kCaseKeys, kPart | kScope}, {"tab", kTabKeys, kPart}, {"column", kColumnKeys, kPart}, + {"fieldGrid", kGridPartKeys, kPart}, {"group", kTableGroupKeys, kPart}, + {"columnGroup", kColumnGroupKeys, kPart}, + {"band", kBandKeys, kPart}, + {"summary", kSummaryKeys, kPart}, + {"layoutRow", kLayoutRowKeys, kPart}, + {"layoutCells", {}, kPart}, + {"layoutCell", kLayoutCellKeys, kPart}, {"track", kTrackKeys, kPart}, {"action", kActionKeys, kPart}, {"a11y", kA11yKeys, kPart}, @@ -568,7 +677,7 @@ constexpr std::array kKinds = {{ {"fields", {}, kPart}, {"series", kSeriesKeys, kPart | kRowScope}, {"line", kLineKeys, kPart}, -}}; +}); // NOLINTEND(modernize-use-designated-initializers,readability-trailing-comma) /// @brief A literal length of a page node: an integer count of micrometres. @@ -1893,6 +2002,14 @@ class DocumentParser { made.scope = ScopeDecl{}; } } + // A fixed grid's cells: one cell part per column id, its id the column's. + if (made.kind == "layoutCells") { + for (auto const& [column, cell] : object) { + auto cellNode = std::make_shared(*part(cell, "layoutCell", pointerAppend(path, column))); + cellNode->id = column; + made.parts["cells"].push_back(std::move(cellNode)); + } + } if (made.kind == "fields") { for (auto const& [field, overlay] : object) { made.parts["fields"].push_back(fieldOverlay(field, overlay, pointerAppend(path, field))); @@ -1935,10 +2052,9 @@ class DocumentParser { return *text; } - // One field overlay of a form's `fields`: expressions by key, and the host `component` that draws the field with - // its `props`. - [[nodiscard]] static DocNodePtr fieldOverlay(std::string const& field, Json const& overlay, - std::string const& where) { + // One field overlay of a form's `fields`: expressions by key, the host `component` that draws the field with its + // `props`, and a grid widget's `grid` part. + [[nodiscard]] DocNodePtr fieldOverlay(std::string const& field, Json const& overlay, std::string const& where) { auto const& settings = objectOf(overlay, where, "a field overlay is an object"); auto part = std::make_shared(); part->kind = "field"; @@ -1961,6 +2077,8 @@ class DocumentParser { record->props.emplace(prop, expr(propValue, pointerAppend(keyPath, prop))); } part->parts["props"].push_back(std::move(record)); + } else if (key == "grid") { + part->parts["grid"].push_back(this->part(value, "fieldGrid", keyPath)); } else { part->props.emplace(key, expr(value, keyPath)); } @@ -1982,9 +2100,42 @@ class DocumentParser { return made; } + // A table's `filters` written as the literal filter, an object of `columns` and `groups` alone: kept as its + // JSON text under the node's names, checked to read as a `table::FilterSpec`. Any other value is an expression. + [[nodiscard]] static bool literalFilter(DocNode& made, Json const& value, std::string const& path) { + auto const* const object = std::get_if(&value.data); + if (object == nullptr || object->empty() || !std::ranges::all_of(*object, [](auto const& entry) { + return entry.first == "columns" || entry.first == "groups"; + })) { + return false; + } + std::string const text = glz::write_json(value).value_or(std::string{}); + table::FilterSpec filter; + if (auto const failed = glz::read_json(filter, text)) { + refuse(path, "`filters` is not a filter: " + glz::format_error(failed, text)); + } + made.names.emplace("filters", text); + return true; + } + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per shape a key takes. void entry(DocNode& made, KeySpec const& key, Json const& value, std::string const& path) { std::string const name{key.key}; + if (made.kind == "table" && name == "filters" && literalFilter(made, value, path)) { + return; + } + if (made.kind == "table" && name == "persist") { + auto const* const text = std::get_if(&value.data); + if (std::get_if(&value.data) == nullptr && (text == nullptr || text->empty())) { + refuse(path, "`persist` is a literal: true, false or a name"); + } + } + // A grid column's `field` and `unit` may be expressions in the row's scope; a string stays a name. + if (made.kind == "column" && (name == "field" || name == "unit") && + std::get_if(&value.data) == nullptr) { + made.props.emplace(name, expr(value, path)); + return; + } switch (key.shape) { case Shape::Expr: case Shape::Condition: @@ -2128,6 +2279,10 @@ struct CheckContext { bool onClose = false; /// @brief Names bound here: `as` of a sequence step or `each`, `result`, `body`, `props`. std::vector> bindings; + /// @brief The column parts of a grid, whose keys take expressions in the row's scope. + bool gridColumns = false; + /// @brief The rows of a fixed grid's block, whose cells are read with `row` the block's collection row. + bool layoutBlock = false; }; class DocumentValidator; @@ -2783,6 +2938,22 @@ class DocumentValidator { return info; } + // A model-backed table's `table`: its two actions, `Table.
` and `Table.
.describe`, are in the + // catalog and belong to the alias's model type. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the alias, then the table it names, as the node reads. + void checkModelTable(CheckContext const& context, std::string const& alias, std::string const& table, + std::string const& path) { + std::string const query = "Table." + table; + if (_options->catalog.action && + (!_options->catalog.action(query) || !_options->catalog.action(query + ".describe"))) { + static_cast( + require(context, alias, pointerAppend(path, "model"), {NameCategory::Model}, "a model alias")); + refuse(path, "the table `" + table + "` is not in the catalog"); + } + static_cast(checkModelAction(context, alias, query, path)); + static_cast(checkModelAction(context, alias, query + ".describe", path)); + } + void checkScope(ScopeDecl const& decl, CheckContext const& context) { for (ModelDecl const& model : decl.models) { if (model.key) { @@ -2957,11 +3128,11 @@ class DocumentValidator { std::set> arranged; for (auto const& [name, point] : _doc->customize) { static_cast(name); - if (point.kind == "columns" && _doc->view) { + if ((point.kind == "columns" || (point.kind == "saved" && !point.of.empty())) && _doc->view) { auto const found = _elements.find(point.of); if (found == _elements.end() || found->second->kind != "table") { refuse(pointerAppend(point.path, "of"), - "a `columns` point names a table; `" + point.of + "` is not one"); + "a `" + point.kind + "` point names a table; `" + point.of + "` is not one"); } } if (point.kind == "arrange") { @@ -3119,6 +3290,7 @@ class DocumentValidator { } } + // NOLINTNEXTLINE(readability-function-cognitive-complexity): checks one element against its kind: each branch refuses a different malformed shape and reports into the shared context void checkElement(DocNode const& node, CheckContext const& outer, bool part) { KindSpec const* const spec = findKind(node.kind, part); CheckContext const inner = innerContext(node, outer); @@ -3145,7 +3317,40 @@ class DocumentValidator { } } for (auto const& [key, parts] : node.parts) { - CheckContext const& context = isInner(spec, key) ? inner : outer; + CheckContext context = isInner(spec, key) ? inner : outer; + // A table's menu entries read the column they open on, and a cell's entries its row and its value. + if ((node.kind == "table" || node.kind == "fieldGrid") && (key == "cellMenu" || key == "headerMenu")) { + context.bindings.emplace_back("column", Type::of(TypeKind::String)); + if (key == "cellMenu") { + context.bindings.emplace_back("row", Type::any()); + context.bindings.emplace_back("value", Type::any()); + } + } + // A summary's cells read the records of the rows it summarises as `rows`, and their column's id as + // `column`. + if (key == "summaries") { + context.bindings.emplace_back("rows", Type::any()); + context.bindings.emplace_back("column", Type::of(TypeKind::String)); + } + // A grid's column reads its row's record as `row`: a display column's `value`, and an edit column's + // `field` expression and overlays. A grid's group reads its row's record as `row` in its `by`, as its + // columns do. + if (key == "group" && node.kind == "table" && !node.name("form").empty()) { + context.bindings.emplace_back("row", Type::any()); + } + // A block's rows read its collection row as `row` in their cells' `value` and overlays; a row's `label` is + // read once, for every collection row, so it reads none. + if (key == "rows" && node.kind == "layoutRow") { + context.layoutBlock = true; + } + if (key == "cells" && node.kind == "layoutRow" && context.layoutBlock) { + context.bindings.emplace_back("row", Type::any()); + } + if (key == "columns" && (node.kind == "fieldGrid" || (node.kind == "table" && !node.name("form").empty() && + node.partList("layoutRows").empty()))) { + context.bindings.emplace_back("row", Type::any()); + context.gridColumns = true; + } for (DocNodePtr const& child : parts) { checkElement(*child, context, true); } @@ -3153,7 +3358,7 @@ class DocumentValidator { checkPlacements(node); checkTabBleed(node); if (part) { - checkPartNode(node); + checkPartNode(node, outer.gridColumns); } else { checkFlags(node); checkLayoutKeys(node); @@ -3164,12 +3369,12 @@ class DocumentValidator { } } - static void checkPartNode(DocNode const& node) { + static void checkPartNode(DocNode const& node, bool gridColumn) { if (node.kind == "column" || node.kind == "track") { checkNoPercentWidth(node); } if (node.kind == "column") { - checkColumnPart(node); + checkColumnPart(node, gridColumn); } else if (node.kind == "track") { checkCellPlace(node, "align"); } else if (isMenuEntry(node.kind)) { @@ -3275,6 +3480,7 @@ class DocumentValidator { } } + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one rule per element kind, each reading the same node and reporting to the shared check context in document order void checkKindRules(DocNode const& node, CheckContext const& context) { if (node.kind == "custom") { checkCustomProps(node); @@ -3294,21 +3500,389 @@ class DocumentValidator { checkKindValues(node); checkSheet(node); std::string_view const model = node.name("model"); - if (!model.empty()) { + std::string_view const table = node.kind == "table" ? node.name("table") : std::string_view{}; + bool const fixedGrid = node.kind == "table" && !node.partList("layoutRows").empty(); + if (fixedGrid && (!model.empty() || !table.empty())) { + refuse(pointerAppend(node.path, "layoutRows"), + "a fixed grid's rows are its `layoutRows`; a model's table takes none"); + } + if (!table.empty()) { + if (model.empty()) { + refuse(node.path, "`table` names one of a model's tables; give the table its `model`"); + } + if (!node.name("action").empty()) { + refuse(node.path, "a table names a `table` or an `action`, not both"); + } + checkModelTable(context, std::string{model}, std::string{table}, node.path); + } else if (!model.empty()) { if (node.name("action").empty()) { refuse(node.path, "a `" + node.kind + "` with a `model` names its `action`"); } checkModelAction(context, std::string{model}, std::string{node.name("action")}, node.path); + if (node.kind == "form") { + checkFormDerive(context, node); + } + } else if (fixedGrid) { + checkFixedGrid(node); + } else if (node.kind == "table" && !node.name("form").empty()) { + checkFormGrid(node); } else if (node.kind == "table" && !node.prop("rows")) { refuse(node.path, "a table takes `rows`, or a `model` and `action`"); } if (node.kind == "table") { + checkCellSelection(node); checkTableSelection(node); checkSelectColumn(node); checkTableSort(node); checkTablePaging(node); + checkTableSortBound(node); + checkTableConfigurable(node); + checkBandParts(node); + checkSummaryParts(node); checkTableGroup(node); + checkEditMode(node); + checkColumnGroups(node); checkRowsTableKeys(node); + checkColumnKinds(node); + if (!model.empty() && table.empty()) { + checkActionTable(node); + } + } + } + + // A form's derive action is an action of the form's model; `deriveDebounce` is a literal count of milliseconds. + // The debounce times a round's evaluation as well as its derive call, so a form that names no `derive` takes it + // too. + void checkFormDerive(CheckContext const& context, DocNode const& node) { + if (std::string_view const derive = node.name("derive"); !derive.empty()) { + static_cast(checkModelAction(context, std::string{node.name("model")}, std::string{derive}, + pointerAppend(node.path, "derive"))); + } + if (ExprPtr const debounce = node.prop("deriveDebounce")) { + std::int64_t const* const millis = debounce->kind == ExprKind::Literal + ? debounce->literal.asInt() + : static_cast(nullptr); + if (millis == nullptr || *millis < 0) { + refuse(debounce->path, "`deriveDebounce` is a literal count of milliseconds, 0 or more"); + } + } + } + + // A grid of a form: a table over a form node's collection field, in place of `rows`. Each column's `field` names a + // member of the field's row type, read from the form action's schema when the catalog has it. + void checkFormGrid(DocNode const& node) const { + if (node.prop("rows")) { + refuse(pointerAppend(node.path, "form"), "a table takes `rows` or a `form`, not both"); + } + std::string_view const field = node.name("field"); + if (field.empty()) { + refuse(node.path, "a table over a `form` names its `field`, the form's collection"); + } + auto const form = _elements.find(node.name("form")); + if (form == _elements.end() || form->second->kind != "form") { + refuse(pointerAppend(node.path, "form"), + "`" + std::string{node.name("form")} + "` is not a form of this document"); + } + checkGridPart(node, *form->second, field, pointerAppend(node.path, "field")); + } + + // A fixed grid: a table whose rows are its `layoutRows`, in place of `rows`, each cell a field of the form `form` + // names, an expression or a text. Its rows are fixed, so it takes nothing that orders, groups, adds or summarises + // rows. Keys are unique in the grid, a block's rows included, since a block row's key joins its collection row's + // key and its own, and two collections' row keys may meet. A cell's `field` is a path of the form's fields, or in + // a block of the collection's row type, read from the form action's schema when the catalog has it. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one refusal per rule of a fixed grid's parts. + void checkFixedGrid(DocNode const& node) const { + if (node.prop("rows")) { + refuse(pointerAppend(node.path, "layoutRows"), + "a fixed grid's `layoutRows` are in place of `rows`; give it one of them"); + } + if (!node.name("field").empty()) { + refuse(pointerAppend(node.path, "field"), + "a fixed grid's cells name their own fields; a table with `layoutRows` takes no `field`"); + } + for (std::string_view const key : + {std::string_view{"sort"}, std::string_view{"group"}, std::string_view{"summaries"}, + std::string_view{"rowSpans"}, std::string_view{"appendRows"}, std::string_view{"rowsFixed"}, + std::string_view{"key"}}) { + bool const given = node.prop(key) != nullptr || !node.partList(key).empty() || + node.flag(key, false) == node.flag(key, true); + if (given) { + refuse( + pointerAppend(node.path, key), + "a fixed grid's rows are fixed, in the order of its `layoutRows`, and its spans are its cells'; " + "it takes no `" + + std::string{key} + "`"); + } + } + if (node.prop("columns") != nullptr) { + refuse(pointerAppend(node.path, "columns"), "a fixed grid's `columns` are a list of column parts"); + } + std::span const columns = node.partList("columns"); + for (DocNodePtr const& column : columns) { + if (!column->name("field").empty() || column->prop("field") != nullptr || + column->prop("value") != nullptr) { + refuse(column->path, "a fixed grid's cells name their fields and values; its columns name neither"); + } + } + std::string_view const formId = node.name("form"); + DocNode const* form = nullptr; + if (!formId.empty()) { + auto const found = _elements.find(formId); + if (found == _elements.end() || found->second->kind != "form") { + refuse(pointerAppend(node.path, "form"), + "`" + std::string{formId} + "` is not a form of this document"); + } + form = found->second; + } + std::optional const model = form != nullptr ? fixedGridModel(*form) : std::nullopt; + std::set> keys; + for (DocNodePtr const& part : node.partList("layoutRows")) { + std::string_view const forEach = part->name("forEach"); + if (forEach.empty()) { + checkLayoutRow(*part, columns, form, + model ? std::span{model->fields()} : std::span{}, + model.has_value(), keys); + continue; + } + if (!part->name("key").empty() || !part->partList("cells").empty() || part->prop("label") != nullptr) { + refuse(part->path, "a block's `forEach` repeats its `rows`; it takes no `key`, `label` or `cells`"); + } + if (form == nullptr) { + refuse(pointerAppend(part->path, "forEach"), + "a block repeats rows of a form's collection; give the table its `form`"); + } + std::span members; + if (model) { + auto const array = std::ranges::find(model->fields(), forEach, &forms::FieldSpec::name); + if (array == model->fields().end() || array->kind != forms::FieldKind::ObjectArray) { + refuse(pointerAppend(part->path, "forEach"), + "`" + std::string{forEach} + "` is not a list of records of the form"); + } + members = array->children; + } + if (part->partList("rows").empty()) { + refuse(pointerAppend(part->path, "rows"), "a block repeats its `rows`, and gives none"); + } + for (DocNodePtr const& row : part->partList("rows")) { + if (!row->name("forEach").empty()) { + refuse(pointerAppend(row->path, "forEach"), "a block's rows are rows; a block holds no block"); + } + checkLayoutRow(*row, columns, form, members, model.has_value(), keys); + } + } + if (form == nullptr) { + return; + } + for (DocNodePtr const& part : node.partList("layoutRows")) { + std::string_view const forEach = part->name("forEach"); + std::span const rows = forEach.empty() ? std::span{&part, 1} : part->partList("rows"); + for (DocNodePtr const& row : rows) { + for (DocNodePtr const& cells : row->partList("cells")) { + for (DocNodePtr const& cell : cells->partList("cells")) { + std::string_view const field = cell->name("field"); + ExprPtr const unit = cell->prop("unit"); + std::string const* const literal = + unit != nullptr && unit->kind == ExprKind::Literal ? unit->literal.asString() : nullptr; + if (!field.empty() && literal != nullptr) { + noteUnit( + *form, + forEach.empty() ? std::string{field} : std::string{forEach} + "." + std::string{field}, + *literal, unit->path); + } + } + } + } + } + } + + // A literal `unit` overlay on a field of a form: a field is entered in one unit, so two overlays in the document + // that give it different literal units are refused. A unit an expression gives is read when it is shown, and not + // compared. A field of a collection's rows is named `.`. + void noteUnit(DocNode const& form, std::string const& field, std::string const& unit, + std::string const& where) const { + if (unit.empty()) { + return; + } + auto const [given, added] = _unitsGiven.try_emplace(form.id + "\x1F" + field, unit); + if (!added && given->second != unit) { + refuse(where, "`" + field + "` is given the units `" + given->second + "` and `" + unit + + "` by two overlays; a field is entered in one unit"); + } + } + + // The form model a fixed grid's cells are checked against: its form action's schema, when the catalog has it. + [[nodiscard]] std::optional fixedGridModel(DocNode const& form) const { + if (!_options->catalog.schema) { + return std::nullopt; + } + std::string const action{form.name("action")}; + std::optional const schema = _options->catalog.schema(action); + if (!schema) { + return std::nullopt; + } + auto model = forms::FormModel::fromSchema(action, *schema); + return model ? std::optional{std::move(*model)} : std::nullopt; + } + + // One row of a fixed grid: its key, unique in the grid, and its cells, each under a column's id and naming one of + // `field`, `value` and `text`; a `field` needs the form, and names a field of @p fields when @p known. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one refusal per rule of a cell. + static void checkLayoutRow(DocNode const& row, std::span columns, DocNode const* form, + std::span fields, bool known, + std::set>& keys) { + std::string const key{row.name("key")}; + if (key.empty()) { + refuse(row.path, "a fixed grid's row names its `key`, or repeats `rows` for each row of a `forEach`"); + } + if (!row.partList("rows").empty()) { + refuse(pointerAppend(row.path, "rows"), "a row's `rows` repeat for each row of a `forEach`; give it one"); + } + if (key.contains('/')) { + refuse(pointerAppend(row.path, "key"), + "the row key `" + key + "` holds a `/`, which joins a block row's keys; give it another"); + } + if (!keys.insert(key).second) { + refuse(pointerAppend(row.path, "key"), "the row `" + key + "` is declared twice in the grid"); + } + for (DocNodePtr const& cells : row.partList("cells")) { + for (DocNodePtr const& cell : cells->partList("cells")) { + if (std::ranges::none_of(columns, + [&cell](DocNodePtr const& column) { return column->id == cell->id; })) { + refuse(cell->path, + "a fixed grid's cells are named by the table's column ids; `" + cell->id + "` is not one"); + } + std::string_view const field = cell->name("field"); + int const given = (field.empty() ? 0 : 1) + (cell->prop("value") != nullptr ? 1 : 0) + + (cell->names.contains("text") ? 1 : 0); + if (given != 1) { + refuse(cell->path, + "a fixed grid's cell edits its `field`, or shows its `value` or its `text`: " + "one of them"); + } + if (!field.empty() && form == nullptr) { + refuse(pointerAppend(cell->path, "field"), + "a cell that edits a field names the form's; give the table its `form`"); + } + if (!field.empty() && known && !fieldAt(fields, field)) { + refuse(pointerAppend(cell->path, "field"), "`" + std::string{field} + + "` is not a field of the form of `" + + std::string{form->name("action")} + "`"); + } + for (std::string_view const span : {std::string_view{"rows"}, std::string_view{"columns"}}) { + if (ExprPtr const count = cell->prop(span)) { + std::int64_t const* const literal = count->kind == ExprKind::Literal + ? count->literal.asInt() + : static_cast(nullptr); + if (literal == nullptr || *literal < 1) { + refuse(count->path, "a cell's `" + std::string{span} + "` is a literal count, 1 or more"); + } + } + } + for (std::string_view const overlay : {std::string_view{"decimals"}, std::string_view{"unit"}, + std::string_view{"options"}, std::string_view{"placeholder"}}) { + if (ExprPtr const set = cell->prop(overlay); set != nullptr && field.empty()) { + refuse(set->path, "`" + std::string{overlay} + + "` is an overlay of the field a cell edits; " + "this cell edits no field"); + } + } + } + } + } + + // Whether a dotted path names a field below @p fields. + [[nodiscard]] static bool fieldAt(std::span fields, std::string_view path) { + while (!path.empty()) { + std::size_t const dot = path.find('.'); + std::string_view const name = path.substr(0, dot); + path = dot == std::string_view::npos ? std::string_view{} : path.substr(dot + 1); + auto const member = std::ranges::find(fields, name, &forms::FieldSpec::name); + if (member == fields.end()) { + return false; + } + fields = member->children; + } + return true; + } + + // What a grid takes beyond its table, on a `table` over a form or a field overlay's `grid` part: `enterMoves` and + // `walk` by name, and columns that each edit a member, named by `field`, or show a `value`. A `field` must name a + // member of the collection's row type, read from the form action's schema when the catalog has it. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the grid's two options, each column's member or value and the field lookup in one pass over the parts, refusing in document order + void checkGridPart(DocNode const& part, DocNode const& form, std::string_view field, + std::string const& where) const { + for (std::string_view const key : {std::string_view{"enterMoves"}, std::string_view{"walk"}}) { + std::string_view const given = part.name(key); + bool const known = + given.empty() || (key == "enterMoves" ? given == "down" || given == "right" || given == "none" + : given == "rows" || given == "columns"); + if (!known) { + refuse(pointerAppend(part.path, key), key == "enterMoves" ? "`enterMoves` is `down`, `right` or `none`" + : "`walk` is `rows` or `columns`"); + } + } + if (part.flag("appendRows") && part.flag("rowsFixed")) { + refuse(pointerAppend(part.path, "appendRows"), "a grid with `rowsFixed` adds no rows; drop `appendRows`"); + } + if (part.kind == "fieldGrid") { + checkBandParts(part); + checkSummaryParts(part); + } + for (DocNodePtr const& column : part.partList("columns")) { + if (column->name("field").empty() && column->prop("field") == nullptr && + column->prop("value") == nullptr) { + refuse(column->path, "a grid's column edits the member its `field` names, or shows its `value`"); + } + if (std::string_view const member = column->name("field"); !member.empty()) { + noteUnit(form, std::string{field} + "." + std::string{member}, std::string{column->name("unit")}, + pointerAppend(column->path, "unit")); + } + } + if (!_options->catalog.schema) { + return; + } + std::string const action{form.name("action")}; + std::optional const schema = _options->catalog.schema(action); + if (!schema) { + return; + } + auto const model = forms::FormModel::fromSchema(action, *schema); + if (!model) { + return; + } + auto const array = std::ranges::find(model->fields(), field, &forms::FieldSpec::name); + if (array == model->fields().end() || array->kind != forms::FieldKind::ObjectArray) { + refuse(where, "`" + std::string{field} + "` is not a list of records of the form of `" + action + "`"); + } + for (DocNodePtr const& column : part.partList("columns")) { + std::string_view const member = column->name("field"); + if (!member.empty() && std::ranges::none_of(array->children, [member](forms::FieldSpec const& child) { + return child.name == member; + })) { + refuse(pointerAppend(column->path, "field"), + "`" + std::string{member} + "` names no member of `" + std::string{field} + "`"); + } + } + } + + // A table over a typed list action pages through the one request member marked `x-table`, and builds its + // description from its `columns` or the action's view document, since a catalog carries no reply schema. + void checkActionTable(DocNode const& node) const { + std::string const action{node.name("action")}; + if (_options->catalog.schema) { + std::optional const schema = _options->catalog.schema(action); + std::vector const members = schema ? tableQueryMembers(*schema) : std::vector{}; + if (members.empty()) { + refuse(node.path, "a table over an action needs a query member marked x-table"); + } + if (members.size() > 1) { + refuse(node.path, "a table over an action needs one query member marked x-table; `" + action + + "` marks " + std::to_string(members.size())); + } + } + if (_options->catalog.view && node.partList("columns").empty() && !_options->catalog.view(action)) { + refuse(node.path, "a table over an action needs its columns, or a view document for the action"); } } @@ -3379,7 +3953,8 @@ class DocumentValidator { // A sortable column is named by its id, which a sort key gives; `sortBy` says how a sortable column orders. A // literal `sort` names sortable columns, each once, with a direction, and `onSortChange` needs a header that - // sorts. A model-backed table's engine sorts, so none of these belongs on one. + // sorts. A model-backed table's engine sorts and its description says which columns do, so neither `sortable` + // nor `sortBy` belongs on one. static void checkTableSort(DocNode const& node) { bool const modelBacked = !node.name("model").empty(); std::set> sortable; @@ -3400,7 +3975,7 @@ class DocumentValidator { sortable.insert(column->id); } } - if (node.event("onSortChange") != nullptr && sortable.empty()) { + if (node.event("onSortChange") != nullptr && sortable.empty() && !modelBacked) { refuse(pointerAppend(node.path, "onSortChange"), "`onSortChange` runs when a header sorts the table; give a column `sortable`"); } @@ -3437,6 +4012,106 @@ class DocumentValidator { } } + // A band part as `BandInfo`: its label, unit, literal list of column ids and the bands one level down. + // NOLINTNEXTLINE(misc-no-recursion): a band's bands are bands one level down. + static table::BandInfo bandOf(DocNode const& part) { + table::BandInfo band{.label = std::string{part.name("label")}, + .unit = std::string{part.name("unit")}, + .columns = {}, + .bands = {}}; + ExprPtr const members = part.prop("columns"); + ValueList const* const list = + members != nullptr && members->kind == ExprKind::Literal ? members->literal.asList() : nullptr; + if (list == nullptr) { + refuse(pointerAppend(part.path, "columns"), "a band's `columns` is a literal list of its columns' ids"); + } + for (Value const& member : *list) { + std::string const* const columnId = member.asString(); + if (columnId == nullptr) { + refuse(pointerAppend(part.path, "columns"), + "a band's `columns` is a literal list of its columns' ids"); + } + band.columns.push_back(*columnId); + } + for (DocNodePtr const& child : part.partList("bands")) { + band.bands.push_back(bandOf(*child)); + } + return band; + } + + // Header bands: nested at most three levels, each over columns of the table, a child over its parent's columns + // and a column in one band per level (`table::bandRefusal`). A model's table names its columns in its + // description, so only a table that declares its column parts has its ids checked here. + static void checkBandParts(DocNode const& node) { + auto const parts = node.partList("bands"); + if (parts.empty()) { + return; + } + std::vector bands; + for (DocNodePtr const& part : parts) { + bands.push_back(bandOf(*part)); + } + std::vector known; + if (node.name("model").empty() && node.prop("columns") == nullptr) { + for (DocNodePtr const& column : node.partList("columns")) { + known.push_back(column->id); + } + } + if (std::optional const refused = table::bandRefusal(bands, known)) { + refuse(pointerAppend(node.path, "bands"), *refused); + } + } + + // Summary rows, on a table and on its group part: a summary is a feature of a table over held rows, so a + // model-backed table refuses both. Each has a key, unique in its list, a `position` of `bottom` or `top`, and + // cells named by the table's column ids. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): checks each summary's key, position and cells in one pass over the list; the uniqueness set is shared + static void checkSummaryParts(DocNode const& node) { + bool const modelBacked = !node.name("model").empty(); + auto const check = [&node, modelBacked](std::span summaries, std::string const& where) { + if (summaries.empty()) { + return; + } + if (modelBacked) { + refuse(where, + "a summary row summarises rows the client holds; a model-backed table refuses " + "`summaries`, as it refuses `group`"); + } + std::set> keys; + auto const columns = node.partList("columns"); + for (DocNodePtr const& summary : summaries) { + std::string const key{summary->name("key")}; + if (key.empty() || !keys.insert(key).second) { + refuse(pointerAppend(summary->path, "key"), key.empty() + ? std::string{"a summary names its `key`"} + : "the summary `" + key + "` is declared twice"); + } + std::string_view const position = summary->name("position"); + if (!position.empty() && position != "bottom" && position != "top") { + refuse(pointerAppend(summary->path, "position"), "a summary's `position` is `bottom` or `top`"); + } + if (node.prop("columns") != nullptr || columns.empty()) { + continue; + } + for (DocNodePtr const& cells : summary->partList("cells")) { + for (auto const& [column, expr] : cells->props) { + static_cast(expr); + if (std::ranges::none_of(columns, + [&column](DocNodePtr const& part) { return part->id == column; })) { + refuse( + pointerAppend(cells->path, column), + "a summary's cells are named by the table's column ids; `" + column + "` is not one"); + } + } + } + } + }; + check(node.partList("summaries"), pointerAppend(node.path, "summaries")); + for (DocNodePtr const& group : node.partList("group")) { + check(group->partList("summaries"), pointerAppend(group->path, "summaries")); + } + } + // A table over `rows` draws its own group headings; a model-backed table's engine shapes its rows. static void checkTableGroup(DocNode const& node) { if (!node.name("model").empty() && !node.partList("group").empty()) { @@ -3445,6 +4120,76 @@ class DocumentValidator { } } + // When a model's table commits its cells' edits: `cell` or `row`. Only a model's table commits through edit + // actions. + static void checkEditMode(DocNode const& node) { + std::string_view const mode = node.name("editMode"); + if (mode.empty()) { + return; + } + if (node.name("model").empty() || node.name("table").empty()) { + refuse(pointerAppend(node.path, "editMode"), + "`editMode` chooses how a model's table commits its cells; this table is not a model's table"); + } + if (mode != "cell" && mode != "row") { + refuse(pointerAppend(node.path, "editMode"), + "`editMode` is `cell` or `row`, not `" + std::string{mode} + "`"); + } + } + + // A table over `rows` declares its column groups: each 2 to 16 of its column parts, of one literal kind, and a + // column in at most one group. A model's table has its groups from its description. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): checks each group's size, kind and column membership in one pass; the "column in one group" set is shared + static void checkColumnGroups(DocNode const& node) { + auto const groups = node.partList("groups"); + if (groups.empty()) { + return; + } + if (!node.prop("rows")) { + refuse( + pointerAppend(node.path, "groups"), + "a model's table declares its column groups in its description; `groups` is for a table over `rows`"); + } + auto const columns = node.partList("columns"); + std::set> grouped; + std::set> ids; + for (DocNodePtr const& group : groups) { + std::string const where = pointerAppend(group->path, "columns"); + if (!ids.insert(group->id).second) { + refuse(pointerAppend(group->path, "id"), "the group `" + group->id + "` is declared twice"); + } + ExprPtr const members = group->prop("columns"); + ValueList const* const list = + members != nullptr && members->kind == ExprKind::Literal ? members->literal.asList() : nullptr; + if (list == nullptr) { + refuse(where, "a group's `columns` is a literal list of its columns' ids"); + } + if (list->size() < 2 || list->size() > 16) { + refuse(where, "a group has 2 to 16 columns"); + } + std::optional kind; + for (Value const& member : *list) { + std::string const* const columnId = member.asString(); + auto const part = columnId == nullptr + ? columns.end() + : std::ranges::find_if(columns, [columnId](DocNodePtr const& column) { + return column->id == *columnId; + }); + if (part == columns.end()) { + refuse(where, "a group's columns are the ids of the table's column parts"); + } + if (!grouped.insert(*columnId).second) { + refuse(where, "the column `" + *columnId + "` is in another group"); + } + std::string_view const named = (*part)->name("kind"); + if (kind && *kind != named) { + refuse(where, "a group's columns hold one kind of value"); + } + kind = named; + } + } + } + // A table over `rows` pages itself by `pageSize`, at `page`; a model-backed table's engine pages. static void checkTablePaging(DocNode const& node) { ExprPtr const size = node.prop("pageSize"); @@ -3465,18 +4210,88 @@ class DocumentValidator { } } + // A `rows` table's sort bound: a literal 1 to 32. A model's table has its bound from its description. + static void checkTableSortBound(DocNode const& node) { + ExprPtr const bound = node.prop("maxSortKeys"); + if (bound == nullptr) { + return; + } + std::string const path = pointerAppend(node.path, "maxSortKeys"); + if (!node.name("model").empty()) { + refuse(path, "`maxSortKeys` is a `rows` table's; a model's table carries its bound in its description"); + } + std::int64_t const* const keys = bound->kind == ExprKind::Literal ? bound->literal.asInt() : nullptr; + if (keys == nullptr || *keys < 1 || *keys > 32) { + refuse(path, "`maxSortKeys` is 1 to 32"); + } + } + + // What a table lets its user change about its columns: a literal `true`, `false`, or a list of the four. + static void checkTableConfigurable(DocNode const& node) { + ExprPtr const expr = node.prop("configurable"); + if (expr == nullptr) { + return; + } + std::string const path = pointerAppend(node.path, "configurable"); + std::string_view const shape = + R"(`configurable` is a literal `true`, `false`, or a list of "reorder", "hide", "pin" and "resize")"; + if (expr->kind != ExprKind::Literal) { + refuse(path, std::string{shape}); + } + if (expr->literal.asBool() != nullptr) { + return; + } + ValueList const* const names = expr->literal.asList(); + if (names == nullptr) { + refuse(path, std::string{shape}); + } + static constexpr std::array kConfigurable = {"reorder", "hide", "pin", "resize"}; + for (Value const& item : *names) { + std::string const* const name = item.asString(); + if (name == nullptr) { + refuse(path, std::string{shape}); + } + if (!listed(kConfigurable, *name)) { + refuse(path, "`configurable` names `" + *name + "`; it lists reorder, hide, pin and resize"); + } + } + } + // The keys of a model-backed table that a table over `rows` would accept and ignore. static void checkRowsTableKeys(DocNode const& node) { if (!node.prop("rows")) { return; } - if (node.prop("filters") != nullptr) { + if (node.prop("filters") != nullptr || !node.name("filters").empty()) { refuse(pointerAppend(node.path, "filters"), "`filters` belongs to a model-backed table; filter `rows` with `filter`"); } if (node.prop("highlightKey") != nullptr) { refuse(pointerAppend(node.path, "highlightKey"), "`highlightKey` links a model-backed table to a chart"); } + // Its arrangement is kept under the table's id, so a table with none persists nothing, and says so when it + // asks to. + if (ExprPtr const persist = node.prop("persist"); persist != nullptr && node.id.empty()) { + bool const* const flag = persist->kind == ExprKind::Literal ? persist->literal.asBool() : nullptr; + if (flag == nullptr || *flag) { + refuse(pointerAppend(node.path, "persist"), + "a table over `rows` needs an `id` to persist its arrangement"); + } + } + } + + // A column part's literal `kind`, on a table over `rows` or over a typed list action: one of the seven a + // document names. + static void checkColumnKinds(DocNode const& node) { + static constexpr std::array kColumnKinds = {"text", "integer", "decimal", "number", + "date", "dateTime", "bool"}; + for (DocNodePtr const& column : node.partList("columns")) { + std::string_view const kind = column->name("kind"); + if (!kind.empty() && !listed(kColumnKinds, kind)) { + refuse(pointerAppend(column->path, "kind"), + "`kind` is one of text, integer, decimal, number, date, dateTime, bool"); + } + } } // The select column draws a `multiple` table's selection, so it needs a literal `multiple`; its header's name @@ -3500,8 +4315,37 @@ class DocumentValidator { } } + // `selectionMode: "cells"` selects a rectangle of cells, which a grid of a form does by default and only; a + // model's table is in server mode and selects rows. `appendRows` and `rowsFixed` say which row operations a grid + // offers. + static void checkCellSelection(DocNode const& node) { + bool const grid = !node.name("form").empty() || !node.partList("layoutRows").empty(); + ExprPtr const mode = node.prop("selectionMode"); + std::string const* const literal = + mode != nullptr && mode->kind == ExprKind::Literal ? mode->literal.asString() : nullptr; + std::string const where = pointerAppend(node.path, "selectionMode"); + if (literal != nullptr && *literal == "cells" && !node.name("model").empty()) { + refuse(where, + "`selectionMode` `cells` selects cells of a table held on the client; a model's table " + "selects rows"); + } + if (literal != nullptr && *literal == "cells" && !grid) { + refuse(where, "`selectionMode` `cells` is a grid's; this table is not a grid of a form"); + } + if (grid && mode != nullptr && (literal == nullptr || *literal != "cells")) { + refuse(where, "a grid of a form selects cells: its `selectionMode` is `cells`"); + } + for (std::string_view const key : {std::string_view{"appendRows"}, std::string_view{"rowsFixed"}}) { + if (node.flag(key, false) == node.flag(key, true) && !grid) { + refuse(pointerAppend(node.path, key), + "`" + std::string{key} + "` is a grid's; this table is not a grid of a form"); + } + } + } + // A table's `selection` and `onSelectionChange` need rows the user can select, and rows the document holds: a - // model-backed table's engine owns its selection. + // model-backed table's engine owns its selection. A grid of a form selects cells, so it takes them without a + // `selectionMode`. static void checkTableSelection(DocNode const& node) { std::string_view key; if (node.prop("selection") != nullptr) { @@ -3516,6 +4360,9 @@ class DocumentValidator { refuse(where, "a model-backed table's engine owns its selection; `" + std::string{key} + "` is for a table over `rows`"); } + if (!node.name("form").empty() || !node.partList("layoutRows").empty()) { + return; + } ExprPtr const mode = node.prop("selectionMode"); std::string const* const literal = mode != nullptr && mode->kind == ExprKind::Literal ? mode->literal.asString() : nullptr; @@ -3713,6 +4560,18 @@ class DocumentValidator { if (!field->name("component").empty()) { checkFieldComponent(*field); } + if (std::span const grid = field->partList("grid"); !grid.empty()) { + // A literal `widget: "grid"` only: a grid part on any other control would be dropped silently. + ExprPtr const widget = field->prop("widget"); + std::string const* const named = + widget != nullptr && widget->kind == ExprKind::Literal ? widget->literal.asString() : nullptr; + if (named == nullptr || *named != "grid") { + refuse(grid.front()->path, + "a field's `grid` gives a grid widget its columns; give it `widget: \"grid\"`"); + } + checkGridPart(*grid.front(), form, field->id, field->path); + checkTableConfigurable(*grid.front()); + } } } } @@ -4310,11 +5169,57 @@ class DocumentValidator { // cell. static constexpr std::array kCellPlaces = {"start", "center", "end"}; - // A table column's closed sets: its default cell's text role, and its cells' places. - static void checkColumnPart(DocNode const& node) { + // A table column's closed sets: its default cell's text role, and its cells' places; and its display parts, + // which are literals: `decimals` 0 to 18, `rounding` one of two names, `date` a pattern, `labels` a list of + // `{operand, text}`. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the column's closed sets and display parts are each checked against their allowed values and report in document order + static void checkColumnPart(DocNode const& node, bool gridColumn) { checkTextRole(node); checkCellPlace(node, "align"); checkCellPlace(node, "valign"); + // A grid column's overlays are per row; a table over rows has none of them. + if (!gridColumn) { + for (std::string_view const key : + {std::string_view{"readonly"}, std::string_view{"options"}, std::string_view{"placeholder"}, + std::string_view{"field"}, std::string_view{"unit"}}) { + if (ExprPtr const given = node.prop(key)) { + refuse(given->path, "`" + std::string{key} + + (key == "field" || key == "unit" ? "` as an expression" : "`") + + " is a grid column's, read per row; this table is not a grid of a form"); + } + } + } + if (ExprPtr const decimals = node.prop("decimals"); + decimals && (!gridColumn || decimals->kind == ExprKind::Literal)) { + std::int64_t const* const places = decimals->kind == ExprKind::Literal + ? decimals->literal.asInt() + : static_cast(nullptr); + if (places == nullptr || *places < 0 || *places > 18) { + refuse(decimals->path, "`decimals` is a literal integer, 0 to 18"); + } + } + if (std::string_view const rounding = node.name("rounding"); + !rounding.empty() && rounding != "halfEven" && rounding != "halfUp") { + refuse(pointerAppend(node.path, "rounding"), + "`" + std::string{rounding} + "` is not one of the values of `rounding`: halfEven or halfUp"); + } + if (std::string_view const date = node.name("date"); + !date.empty() && !checkDatePattern(date, false) && !checkDatePattern(date, true)) { + refuse(pointerAppend(node.path, "date"), checkDatePattern(date, false).error()); + } + if (ExprPtr const labels = node.prop("labels")) { + ValueList const* const items = + labels->kind == ExprKind::Literal ? labels->literal.asList() : static_cast(nullptr); + bool const read = items != nullptr && std::ranges::all_of(*items, [](Value const& item) { + Value const* const operand = item.field("operand"); + Value const* const text = item.field("text"); + return operand != nullptr && operand->asString() != nullptr && text != nullptr && + text->asString() != nullptr; + }); + if (!read) { + refuse(labels->path, R"(`labels` is a literal list of `{"operand": text, "text": text}`)"); + } + } } // Only a horizontal `forEach` wraps and only a vertical one is divided; a literal `axis` that says otherwise is @@ -4907,6 +5812,8 @@ class DocumentValidator { std::map _innerOf; std::map> _queries; std::map> _elements; + // The literal unit each form field is first given by an overlay, by the form's id and the field's path. + mutable std::map> _unitsGiven; std::vector> _watches; std::vector> _mutations; std::vector> _queryScopes; @@ -5166,6 +6073,34 @@ std::expected loadTourText(std::string_view text) { } } +std::vector tableQueryMembers(std::string_view schemaJson) { + std::vector members; + auto const json = parseJson(schemaJson); + auto const* const schema = json ? std::get_if(&json->data) : nullptr; + const auto* const properties = schema != nullptr ? schema->find("properties") : Json::object_t::const_iterator{}; + if (schema == nullptr || properties == schema->end()) { + return members; + } + auto const* const entries = std::get_if(&properties->second.data); + if (entries == nullptr) { + return members; + } + for (auto const& [name, property] : *entries) { + auto const* const fields = std::get_if(&property.data); + if (fields == nullptr) { + continue; + } + const auto* const marker = fields->find(table::TableQuery::schemaMarker()); + if (marker == fields->end()) { + continue; + } + if (bool const* const flag = std::get_if(&marker->second.data); flag != nullptr && *flag) { + members.push_back(name); + } + } + return members; +} + std::vector nodeKinds() { std::vector kinds; for (detail::KindSpec const& spec : detail::kKinds) { diff --git a/src/ui/expression.cpp b/src/ui/expression.cpp index ed36c3c64..f1aa9f7c2 100644 --- a/src/ui/expression.cpp +++ b/src/ui/expression.cpp @@ -1227,6 +1227,10 @@ class EvaluatorCore { case ExprKind::Runs: return grouped(expr); case ExprKind::Get: + // A path out of the whole row is the row's own read, so the environment sees which field it is. + if (Expr const& source = *expr.args.at(0); source.kind == ExprKind::Row && source.fieldPath.empty()) { + return _env->row(expr.fieldPath); + } return walk(eval(*expr.args.at(0)), expr.fieldPath); case ExprKind::Call: default: @@ -1705,70 +1709,17 @@ class EvaluatorCore { /// Orders two values of one comparable kind: numbers exactly (quantities converted), timestamps, strings, and /// booleans with `false` before `true`. std::optional order(Value const& lhs, Value const& rhs) { - auto const lhsNumber = numeric(lhs); - auto const rhsNumber = numeric(rhs); - if (lhsNumber && rhsNumber) { - if ((lhsNumber->unit == nullptr) != (rhsNumber->unit == nullptr)) { - return std::nullopt; - } - math::Rational right = rhsNumber->value; - if (lhsNumber->unit != nullptr) { - auto converted = convertUnit(right, *rhsNumber->unit, *lhsNumber->unit, _env->formatting().units); - if (!converted) { - return std::nullopt; - } - right = *converted; - } - return lhsNumber->value <=> right; - } - if (time::DateTime const* const lhsTime = lhs.asTimestamp()) { - if (time::DateTime const* const rhsTime = rhs.asTimestamp()) { - return *lhsTime <=> *rhsTime; - } - return std::nullopt; - } - if (std::string const* const lhsText = lhs.asString()) { - if (std::string const* const rhsText = rhs.asString()) { - return *lhsText <=> *rhsText; - } - } - if (bool const* const lhsFlag = lhs.asBool()) { - if (bool const* const rhsFlag = rhs.asBool()) { - return static_cast(*lhsFlag) <=> static_cast(*rhsFlag); - } - } - return std::nullopt; + return ::morph::ui::detail::valueOrder(lhs, rhs, _env->formatting().units); } /// Equality over non-null values: numbers by value, lists and records element-wise, other kinds by identity. bool equal(Value const& lhs, Value const& rhs) { - if (numeric(lhs) && numeric(rhs)) { - auto const ordering = order(lhs, rhs); - return ordering.has_value() && *ordering == std::strong_ordering::equal; - } - if (lhs.kind() != rhs.kind()) { - return false; - } - if (ValueList const* const lhsItems = lhs.asList()) { - return std::ranges::equal(*lhsItems, *rhs.asList(), [this](Value const& left, Value const& right) { - return sameElement(left, right); - }); - } - if (ValueRecord const* const lhsFields = lhs.asRecord()) { - // Records are ordered by field name, so equal records have equal sequences of fields. - return std::ranges::equal(*lhsFields, *rhs.asRecord(), [this](auto const& left, auto const& right) { - return left.first == right.first && sameElement(left.second, right.second); - }); - } - return lhs == rhs; + return ::morph::ui::detail::valuesEqual(lhs, rhs, _env->formatting().units); } /// Equality of two elements of a list or record, where `null` equals only `null`. bool sameElement(Value const& left, Value const& right) { - if (left.isNull() || right.isNull()) { - return left.isNull() && right.isNull(); - } - return equal(left, right); + return ::morph::ui::detail::sameElement(left, right, _env->formatting().units); } /// The display text of a value, as `format` shows an argument. @@ -2509,6 +2460,75 @@ std::optional numeric(Value const& value) { return std::nullopt; } +std::optional valueOrder(Value const& lhs, Value const& rhs, UnitTable const& units) { + auto const lhsNumber = numeric(lhs); + auto const rhsNumber = numeric(rhs); + if (lhsNumber && rhsNumber) { + if ((lhsNumber->unit == nullptr) != (rhsNumber->unit == nullptr)) { + return std::nullopt; + } + math::Rational right = rhsNumber->value; + if (lhsNumber->unit != nullptr) { + auto converted = convertUnit(right, *rhsNumber->unit, *lhsNumber->unit, units); + if (!converted) { + return std::nullopt; + } + right = *converted; + } + return lhsNumber->value <=> right; + } + if (time::DateTime const* const lhsTime = lhs.asTimestamp()) { + if (time::DateTime const* const rhsTime = rhs.asTimestamp()) { + return *lhsTime <=> *rhsTime; + } + return std::nullopt; + } + if (std::string const* const lhsText = lhs.asString()) { + if (std::string const* const rhsText = rhs.asString()) { + return *lhsText <=> *rhsText; + } + } + if (bool const* const lhsFlag = lhs.asBool()) { + if (bool const* const rhsFlag = rhs.asBool()) { + return static_cast(*lhsFlag) <=> static_cast(*rhsFlag); + } + } + return std::nullopt; +} + +// NOLINTNEXTLINE(misc-no-recursion): a list or a record compares its elements, which are values. +bool valuesEqual(Value const& lhs, Value const& rhs, UnitTable const& units) { + if (numeric(lhs) && numeric(rhs)) { + auto const ordering = valueOrder(lhs, rhs, units); + return ordering.has_value() && *ordering == std::strong_ordering::equal; + } + if (lhs.kind() != rhs.kind()) { + return false; + } + if (ValueList const* const lhsItems = lhs.asList()) { + // NOLINTNEXTLINE(misc-no-recursion): equality over lists recurses into the items, one level per nesting of the document's value; the depth is the data's + return std::ranges::equal(*lhsItems, *rhs.asList(), [&units](Value const& left, Value const& right) { + return sameElement(left, right, units); + }); + } + if (ValueRecord const* const lhsFields = lhs.asRecord()) { + // Records are ordered by field name, so equal records have equal sequences of fields. + // NOLINTNEXTLINE(misc-no-recursion): equality over records recurses into the fields, one level per nesting of the document's value; the depth is the data's + return std::ranges::equal(*lhsFields, *rhs.asRecord(), [&units](auto const& left, auto const& right) { + return left.first == right.first && sameElement(left.second, right.second, units); + }); + } + return lhs == rhs; +} + +// NOLINTNEXTLINE(misc-no-recursion): see valuesEqual. +bool sameElement(Value const& left, Value const& right, UnitTable const& units) { + if (left.isNull() || right.isNull()) { + return left.isNull() && right.isNull(); + } + return valuesEqual(left, right, units); +} + std::optional convertUnit(math::Rational const& value, std::string_view from, std::string_view target, UnitTable const& units) { if (from == target) { diff --git a/src/ui/form_rows.cpp b/src/ui/form_rows.cpp new file mode 100644 index 000000000..81f4998cb --- /dev/null +++ b/src/ui/form_rows.cpp @@ -0,0 +1,388 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui::detail { + +table::ColumnKind columnKindOf(forms::FieldKind kind) noexcept { + using forms::FieldKind; + switch (kind) { + case FieldKind::Integer: + case FieldKind::Slider: + return table::ColumnKind::Integer; + case FieldKind::Decimal: + case FieldKind::Quantity: + return table::ColumnKind::Decimal; + case FieldKind::Number: + return table::ColumnKind::Number; + case FieldKind::Date: + case FieldKind::EpochDate: + return table::ColumnKind::Date; + case FieldKind::DateTime: + case FieldKind::EpochDateTime: + return table::ColumnKind::DateTime; + case FieldKind::Boolean: + return table::ColumnKind::Bool; + case FieldKind::Text: + case FieldKind::Multiline: + case FieldKind::Enum: + case FieldKind::Choice: + case FieldKind::Array: + case FieldKind::Object: + case FieldKind::ObjectArray: + default: + return table::ColumnKind::Text; + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity) +table::Cell memberCell(forms::FieldState const& field, table::ColumnKind kind) { + forms::Encoding const& encoding = field.encoded().get(); + if (!encoding.has_value()) { + return std::monostate{}; + } + if (!encoding->has_value()) { + return std::string{field.draft()}; + } + forms::WireValue const& wire = **encoding; + Value const& value = wire.value; + switch (kind) { + case table::ColumnKind::Integer: + if (std::int64_t const* const whole = value.asInt()) { + return *whole; + } + break; + case table::ColumnKind::Decimal: + if (Decimal const* const exact = value.asDecimal()) { + return exact->value; + } + if (std::int64_t const* const whole = value.asInt()) { + return math::Rational{*whole, math::DecimalPlaces{0}}; + } + break; + case table::ColumnKind::Number: { + if (Decimal const* const exact = value.asDecimal()) { + return exact->value.toDouble(); + } + if (std::int64_t const* const whole = value.asInt()) { + return static_cast(*whole); + } + break; + } + case table::ColumnKind::Bool: + if (bool const* const flag = value.asBool()) { + return *flag; + } + break; + case table::ColumnKind::Date: { + if (std::int64_t const* const days = value.asInt()) { + return *days; + } + std::string_view const text = forms::detail::engine::trim(field.draft()); + if (auto const midnight = forms::detail::engine::parseWallClock(std::string{text} + "T00:00")) { + // Assigned, not cast: the duration's count type is the library's own, and only the + // assignment is right whether or not it is `std::int64_t`. + std::int64_t const days = std::chrono::floor(*midnight).time_since_epoch().count(); + return days; + } + break; + } + case table::ColumnKind::DateTime: + if (std::int64_t const* const seconds = value.asInt()) { + return *seconds; + } + if (time::DateTime const* const instant = value.asTimestamp()) { + std::int64_t const seconds = + std::chrono::floor(instant->value).time_since_epoch().count(); + return seconds; + } + break; + case table::ColumnKind::Quantity: + case table::ColumnKind::Text: + case table::ColumnKind::Key: + case table::ColumnKind::Custom: + case table::ColumnKind::Measure: + default: + if (std::string const* const text = value.asString()) { + return *text; + } + return wire.json; + } + return std::string{field.draft()}; +} + +table::Cell perRowCell(forms::FieldState const& field) { + forms::Encoding const& encoding = field.encoded().get(); + if (encoding.has_value() && encoding->has_value()) { + if (std::string const* const text = (*encoding)->value.asString()) { + return *text; + } + } + std::string const& draft = field.draft(); + return draft.empty() ? table::Cell{} : table::Cell{draft}; +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +FormRowsSource::FormRowsSource(forms::FormSession& form, std::string arrayPath, std::vector columns, + std::vector members, + std::vector> perRow) + : _form{&form}, + _arrayPath{std::move(arrayPath)}, + _array{&form.field(_arrayPath)}, + _columns{std::move(columns)}, + _members{std::move(members)}, + _perRow{std::move(perRow)} { + if (_array->spec().kind != forms::FieldKind::ObjectArray || _array->spec().truncated) { + throw std::invalid_argument{"morph::ui::FormRowsSource: `" + _arrayPath + "` is not a collection"}; + } + if (_members.empty()) { + for (table::ColumnInfo const& column : _columns) { + _members.push_back(column.id); + } + } + if (_members.size() != _columns.size()) { + throw std::invalid_argument{"morph::ui::FormRowsSource: one member per column"}; + } + if (_perRow.empty()) { + _perRow.resize(_columns.size()); + } + if (_perRow.size() != _columns.size()) { + throw std::invalid_argument{"morph::ui::FormRowsSource: one per-row member reader per column"}; + } + for (std::size_t at = 0; at < _members.size(); ++at) { + std::string const& name = _members.at(at); + if (_perRow.at(at)) { + continue; + } + if (std::ranges::none_of(_array->spec().children, + [&name](forms::FieldSpec const& member) { return member.name == name; })) { + throw std::invalid_argument{"morph::ui::FormRowsSource: no member `" + name + "` in `" + _arrayPath + "`"}; + } + } + // Reading it is free while nothing it tracks changed, and walks every member once after a change. + _version = std::make_unique>(form.runtime(), [this] { + for (auto const& row : _array->rows()) { + for (auto const& member : row->fields()) { + static_cast(member->encoded().get()); + static_cast(member->draft()); + } + } + return ++_versions; + }); + _synced = currentVersion(); + _held = build(); + _watch = std::make_unique(form.runtime(), [this] { watch(); }); +} + +forms::RowState* FormRowsSource::row(table::RowId const& key) const { + std::int64_t const* const number = std::get_if(&key); + if (number == nullptr || *number < 0) { + return nullptr; + } + // The rows by key, taken again only after the field's rows or a draft changed. + if (std::uint64_t const now = currentVersion(); now != _indexed) { + _indexed = now; + _byKey.clear(); + _form->runtime().untracked([&] { + for (auto const& held : _array->rows()) { + _byKey.insert_or_assign(held->key(), held.get()); + } + }); + } + auto const found = _byKey.find(static_cast(*number)); + return found == _byKey.end() ? nullptr : found->second; +} + +void FormRowsSource::setGroup(std::function groupBy) { + bool const listed = _group != nullptr; + _group = std::move(groupBy); + if (_group && !listed) { + _columns.push_back(table::ColumnInfo{.id = std::string{kGroupRunColumn}, .kind = table::ColumnKind::Integer}); + _members.emplace_back(); + _perRow.emplace_back(); + } else if (!_group && listed) { + _columns.pop_back(); + _members.pop_back(); + _perRow.pop_back(); + } + _held = build(); + _listeners.notify(table::RowChange{.kind = table::ChangeKind::Reset, .rows = {}}); +} + +RecordOf FormRowsSource::recordOf() { + return [](table::RowSnapshot const& snapshot, std::size_t sourceRow) { + auto const* const rows = dynamic_cast(&snapshot); + return RowRecord{.key = snapshot.rowId(sourceRow), .row = rows == nullptr ? Value{} : rows->record(sourceRow)}; + }; +} + +bool FormRowsSource::sync() { + _posted = false; + if (std::uint64_t const now = currentVersion(); now != _synced) { + _synced = now; + } else { + return false; + } + auto next = build(); + auto const& before = *_held; + auto const& after = *next; + if (before.keys() == after.keys()) { + std::vector changed; + for (std::size_t row = 0; row < after.rowCount(); ++row) { + if (before.cells().at(row) != after.cells().at(row) || !(before.record(row) == after.record(row))) { + changed.push_back(row); + } + } + if (changed.empty()) { + return false; + } + _held = std::move(next); + _listeners.notify(table::RowChange{.kind = table::ChangeKind::Updated, .rows = std::move(changed)}); + return true; + } + std::optional const change = structural(before, after); + _held = std::move(next); + _listeners.notify(change.value_or(table::RowChange{.kind = table::ChangeKind::Reset, .rows = {}})); + return true; +} + +std::optional FormRowsSource::structural(detail::FormRowsSnapshot const& before, + detail::FormRowsSnapshot const& after) { + bool const growing = after.rowCount() > before.rowCount(); + detail::FormRowsSnapshot const& longer = growing ? after : before; + detail::FormRowsSnapshot const& shorter = growing ? before : after; + std::vector rows; + std::size_t kept = 0; + for (std::size_t at = 0; at < longer.rowCount(); ++at) { + if (kept < shorter.rowCount() && longer.keys().at(at) == shorter.keys().at(kept)) { + if (longer.cells().at(at) != shorter.cells().at(kept) || !(longer.record(at) == shorter.record(kept))) { + return std::nullopt; + } + ++kept; + } else { + rows.push_back(at); + } + } + if (kept != shorter.rowCount()) { + return std::nullopt; + } + return table::RowChange{.kind = growing ? table::ChangeKind::Inserted : table::ChangeKind::Removed, + .rows = std::move(rows)}; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one pass building the snapshot's parallel vectors. +std::shared_ptr FormRowsSource::build() const { + ++_builds; + return _form->runtime().untracked([&] { + std::vector keys; + std::vector> cells; + std::vector records; + // The run column, while grouped, is the last; its cell is filled once the runs are known. + std::size_t const own = _group ? _columns.size() - 1 : _columns.size(); + for (auto const& row : _array->rows()) { + keys.emplace_back(static_cast(row->key())); + std::vector rowCells; + rowCells.reserve(_columns.size()); + for (std::size_t at = 0; at < own; ++at) { + if (_perRow.at(at)) { + // A member per row: its kind varies, so the cell is text (`detail::perRowCell`). + forms::FieldState const* const member = row->field(_perRow.at(at)(*row)); + rowCells.push_back(member == nullptr ? table::Cell{} : detail::perRowCell(*member)); + continue; + } + forms::FieldState const* const member = row->field(_members.at(at)); + rowCells.push_back(member == nullptr ? table::Cell{} + : detail::memberCell(*member, _columns.at(at).kind)); + } + cells.push_back(std::move(rowCells)); + ValueRecord record; + for (auto const& member : row->fields()) { + forms::Encoding const& encoding = member->encoded().get(); + record.insert_or_assign(member->spec().name, + encoding.has_value() && encoding->has_value() ? (*encoding)->value : Value{}); + } + record.insert_or_assign(std::string{kGridKeyField}, Value{static_cast(row->key())}); + records.emplace_back(std::move(record)); + } + std::vector runs; + if (_group) { + runs = groupRuns(records, cells); + } + return std::make_shared(_columns.size(), std::move(keys), std::move(cells), + std::move(records), std::move(runs)); + }); +} + +std::vector FormRowsSource::groupRuns(std::vector const& records, + std::vector>& cells) const { + std::vector runs; + std::map> ordinals; + std::optional key; + ValueList items; + auto const close = [&] { + if (!key) { + return; + } + std::string const json = ui::detail::canonicalJson(*key); + Value const record = runRecord(*key, std::exchange(items, {})); + ValueRecord entry = *record.asRecord(); + entry.insert_or_assign(std::string{detail::kGroupHeadingField}, + Value{"\x1Fgroup:" + json + ":" + std::to_string(ordinals[json]++)}); + runs.emplace_back(std::move(entry)); + }; + std::size_t index = 0; + for (auto const& row : _array->rows()) { + Value groupKey = _group(*row); + if (key && !detail::sameElement(*key, groupKey, UnitTable{})) { + close(); + key.reset(); + } + if (!key) { + key = std::move(groupKey); + } + items.push_back(records.at(index)); + cells.at(index).emplace_back(static_cast(runs.size())); + ++index; + } + close(); + return runs; +} + +void FormRowsSource::watch() { + static_cast(_version->get()); + if (_watching && !_posted) { + _posted = true; + _form->runtime().owner().post(_alive.guard([this] { sync(); })); + } + _watching = true; +} + +} // namespace morph::ui diff --git a/src/ui/grid_1.cpp b/src/ui/grid_1.cpp new file mode 100644 index 000000000..be8888fb7 --- /dev/null +++ b/src/ui/grid_1.cpp @@ -0,0 +1,1488 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +std::string pasteMessage(PasteResult const& result) { + std::string text = "Pasted " + std::to_string(result.written) + " values"; + std::vector parts; + if (result.readOnly > 0) { + parts.push_back(std::to_string(result.readOnly) + " on read-only cells"); + } + if (result.pastRows > 0) { + parts.push_back(std::to_string(result.pastRows) + " past the last row"); + } + if (result.pastColumns > 0) { + parts.push_back(std::to_string(result.pastColumns) + " past the last column"); + } + if (parts.empty()) { + return text; + } + text += "; "; + for (std::size_t at = 0; at < parts.size(); ++at) { + text += (at == 0 ? "" : " and ") + parts.at(at); + } + return text + " were dropped"; +} + +bool cellReadOnly(CellFacts const& facts) { + if (facts.field == nullptr || !facts.hasEdit) { + return true; + } + return facts.field->readonly().get() || facts.overlayReadOnly || facts.companionReadOnly || facts.busy || + facts.locked || facts.unloaded || facts.foreignUnit; +} + +std::vector GridSource::spans(Key const& key) const { + static_cast(key); + return {}; +} + +Node GridSource::cellContent(std::string const& column, reactive::Signal const& row) { + reactive::Signal const* const record = &row; + Node content = ui::text(Text{.text = Prop{[this, record, column] { + std::optional const key = keyOf(record->get()); + return key ? text(*key, column) : std::string{}; + }}}); + Prop accent{[this, record, column] { + std::optional const key = keyOf(record->get()); + std::optional const failed = key ? error(*key, column) : std::nullopt; + return CellAccent{ + .tone = std::nullopt, .tooltip = failed.value_or(std::string{}), .invalid = failed.has_value()}; + }}; + return accentedCell(std::move(content), std::move(accent)); +} + +Node GridSource::cellView(std::string const& column, reactive::Signal const& row) { + reactive::Signal const* const record = &row; + Prop marked{[this, record, column] { + std::optional const key = keyOf(record->get()); + return key ? marks(*key, column) : CellMarks{}; + }}; + return markedCell(cellContent(column, row), std::move(marked)); +} + +void GridSource::revertCell(Key const& key, std::string_view column) { + static_cast(key); + static_cast(column); +} + +void GridSource::editorOpened(Key const& key, std::string_view column) { + static_cast(key); + static_cast(column); +} + +std::optional GridSource::insertRow(std::size_t position) { + static_cast(position); + return std::nullopt; +} + +bool GridSource::removeRows(std::span keys) { + static_cast(keys); + return false; +} + +std::optional GridSource::refusal(Key const& key, std::string_view column) const { + static_cast(key); + static_cast(column); + return std::nullopt; +} + +bool GridSource::resends(Key const& key, std::string_view column) const { + static_cast(key); + static_cast(column); + return false; +} + +GridRows::GridRows(std::shared_ptr source) : _source{checked(std::move(source))} { + // Subscribed before the engine, so a row added while the view is ordered is known to be added when the + // engine's change for it arrives. + _source->subscribe(*this); + table::EngineOptions options; + options.owner = &_source->form().runtime().owner(); + options.worker = nullptr; + options.services.collator = std::make_shared(); + _engine = std::make_unique(_source, FormRowsSource::recordOf(), std::move(options)); + rebuild(); + // The engine's change is the view's while both views were the engine's own; a view that kept its keys in + // order changed only in content; anything else is a reset. + _engine->onChange([this](table::ViewChange const& change) { + bool const alignedBefore = _aligned; + std::vector const before = keys(); + rebuild(); + if (!_onChange) { + return; + } + if (alignedBefore && _aligned) { + _onChange(change); + return; + } + table::ViewChange out; + if (keys() == before) { + out.ops.push_back( + table::ViewOp{.kind = table::ViewOp::Kind::Changed, .first = 0, .count = _items.size(), .to = 0}); + } else { + out.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}); + } + _onChange(out); + }); +} + +GridRows::~GridRows() { + _engine.reset(); + _source->unsubscribe(*this); +} + +void GridRows::sync() { + if (_source->sync()) { + _engine->engine().flush(); + } +} + +TableTotal GridRows::total() const { + return TableTotal{ + .rows = static_cast(_items.size()), .kind = table::TotalKind::Exact, .known = true}; +} + +std::optional GridRows::row(std::int64_t index) const { + if (index < 0 || static_cast(index) >= _items.size()) { + return std::nullopt; + } + Item const& item = _items.at(static_cast(index)); + if (item.engine) { + return _engine->row(static_cast(*item.engine)); + } + RowRecord const* const record = heldRecord(item.key); + if (record == nullptr) { + return std::nullopt; + } + return TableRowRef{.key = record->key, .row = record->row}; +} + +table::UnloadedLevels GridRows::unloadedLevels(std::int64_t index) const { + static_cast(index); + return {}; +} + +void GridRows::visible(std::int64_t first, std::int64_t count, std::span columns) { + static_cast(first); + static_cast(count); + static_cast(columns); +} + +async::Completion, table::TableError>> GridRows::keysOf(std::int64_t first, + std::int64_t count) { + using Result = std::expected, table::TableError>; + auto [completion, promise] = async::Completion::makeSettleable(&_source->form().runtime().owner()); + auto const rows = static_cast(_items.size()); + if (first < 0 || count < 0 || count > rows - first) { + promise.resolve(Result{std::unexpected(table::TableError{ + .code = table::TableErrorCode::InvalidSpec, .column = {}, .message = "a range outside the view"})}); + return std::move(completion); + } + std::vector keys; + for (std::int64_t at = first; at < first + count; ++at) { + keys.push_back(_items.at(static_cast(at)).key); + } + promise.resolve(Result{std::move(keys)}); + return std::move(completion); +} + +void GridRows::locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) { + std::optional const position = positionOf(key); + RowLocation const found{position ? std::optional{static_cast(*position)} : std::nullopt}; + _source->form().runtime().owner().post([stop = std::move(stop), done = std::move(done), found] { + if (!stop.stop_requested()) { + done(found); + } + }); +} + +std::expected GridRows::setSort(SortChain sort) { + sync(); + _sorted = !sort.empty(); + _appended.clear(); + auto result = _engine->setSort(std::move(sort)); + rebuild(); + return result; +} + +std::expected GridRows::setFilter(table::FilterSpec filter) { + sync(); + _filtered = !(filter == table::FilterSpec{}); + _appended.clear(); + auto result = _engine->setFilter(std::move(filter)); + rebuild(); + return result; +} + +TableCountsView GridRows::counts() const { + TableCountsView counts = _engine->counts(); + counts.view = total(); + return counts; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`from`, `target`): the old key first, as every `moveKey` caller and override reads it +void GridRows::moveKey(table::RowId const& from, table::RowId const& target) { + static_cast(from); + static_cast(target); +} + +void GridRows::hold(std::optional key) { + if (key == _held) { + return; + } + sync(); + std::vector const before = keys(); + _held = std::move(key); + _heldAt = _held ? positionOf(*_held).value_or(_items.size()) : 0; + rebuild(); + if (_onChange && keys() != before) { + table::ViewChange reset; + reset.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}); + _onChange(reset); + } +} + +void GridRows::setGroup(std::function groupBy) { + _source->setGroup(std::move(groupBy)); + _engine->engine().flush(); + rebuild(); +} + +std::optional GridRows::positionOf(table::RowId const& key) const { + auto const found = _positions.find(key); + return found == _positions.end() ? std::nullopt : std::optional{found->second}; +} + +std::shared_ptr GridRows::checked(std::shared_ptr source) { + if (source == nullptr) { + throw std::invalid_argument{"morph::ui::GridRows: the source must not be null"}; + } + return source; +} + +void GridRows::rowsChanged(table::RowChange const& change) { + _records.clear(); + if (change.kind != table::ChangeKind::Inserted || (!_sorted && !_filtered)) { + return; + } + auto const snapshot = _source->snapshot(); + for (std::size_t const row : change.rows) { + if (row < snapshot->rowCount()) { + _appended.push_back(snapshot->rowId(row)); + } + } +} + +std::vector GridRows::keys() const { + std::vector out; + out.reserve(_items.size()); + for (Item const& item : _items) { + out.push_back(item.key); + } + return out; +} + +void GridRows::rebuild() { + _items.clear(); + _positions.clear(); + std::unordered_set appended(_appended.begin(), _appended.end()); + if (_held && _source->row(*_held) == nullptr) { + _held.reset(); + } + if (_held) { + appended.insert(*_held); + } + TableTotal const engineTotal = _engine->total(); + std::unordered_map inEngine; + for (std::int64_t at = 0; at < engineTotal.rows; ++at) { + std::optional const ref = _engine->row(at); + if (!ref) { + continue; + } + inEngine.emplace(ref->key, static_cast(at)); + if (!appended.contains(ref->key)) { + _items.push_back(Item{.engine = static_cast(at), .key = ref->key}); + } + } + std::erase_if(_appended, [this](table::RowId const& key) { return _source->row(key) == nullptr; }); + auto const itemOf = [&inEngine](table::RowId const& key) { + auto const found = inEngine.find(key); + return Item{.engine = found == inEngine.end() ? std::nullopt : std::optional{found->second}, .key = key}; + }; + for (table::RowId const& key : _appended) { + if (key != _held) { + _items.push_back(itemOf(key)); + } + } + if (_held) { + auto const place = static_cast(std::min(_heldAt, _items.size())); + _items.insert(_items.begin() + place, itemOf(*_held)); + } + _aligned = _items.size() == static_cast(std::max(engineTotal.rows, 0)); + for (std::size_t at = 0; at < _items.size(); ++at) { + _positions.emplace(_items.at(at).key, at); + _aligned = _aligned && _items.at(at).engine == at; + } +} + +RowRecord const* GridRows::heldRecord(table::RowId const& key) const { + if (auto const found = _records.find(key); found != _records.end()) { + return &found->second; + } + auto const snapshot = _source->snapshot(); + for (std::size_t row = 0; row < snapshot->rowCount(); ++row) { + if (snapshot->rowId(row) == key) { + return &_records.insert_or_assign(key, FormRowsSource::recordOf()(*snapshot, row)).first->second; + } + } + return nullptr; +} + +ValueList summaryScopeRows(TableRows const& rows, std::int64_t first, std::int64_t count) { + ValueList out; + std::int64_t const last = std::min(first + std::max(count, 0), rows.total().rows); + for (std::int64_t at = std::max(first, 0); at < last; ++at) { + if (std::optional const ref = rows.row(at)) { + out.push_back(ref->row); + } + } + return out; +} + +SummaryRows::SummaryRows(std::shared_ptr data, std::vector table, + std::vector perRun, Runs runs) + : _data{checked(std::move(data))}, _table{std::move(table)}, _perRun{std::move(perRun)}, _runs{std::move(runs)} { + rebuild(); + _data->onChange([this](table::ViewChange const& change) { heard(change); }); +} + +void SummaryRows::setHeadings(std::function heading) { + _heading = std::move(heading); + relayout(); +} + +void SummaryRows::relayout() { + ++_version; + rebuild(); + if (_onChange) { + table::ViewChange reset; + reset.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}); + _onChange(reset); + } +} + +TableTotal SummaryRows::mountedTotal() const { + TableTotal out = _data->total(); + out.rows = static_cast(_entries.size()); + return out; +} + +std::optional SummaryRows::row(std::int64_t index) const { + if (index < 0 || static_cast(index) >= _entries.size()) { + return std::nullopt; + } + Entry const& entry = _entries.at(static_cast(index)); + if (entry.kind == Entry::Kind::Data) { + return _data->row(entry.data); + } + return TableRowRef{.key = entry.key, .row = entry.record}; +} + +std::optional SummaryRows::mounted(std::int64_t dataRow) const { + if (dataRow < 0 || static_cast(dataRow) >= _mounted.size()) { + return std::nullopt; + } + return _mounted.at(static_cast(dataRow)); +} + +std::optional SummaryRows::data(std::int64_t mountedRow) const { + if (mountedRow < 0 || static_cast(mountedRow) >= _entries.size()) { + return std::nullopt; + } + auto const index = static_cast(mountedRow); + for (std::size_t distance = 0; distance < _entries.size(); ++distance) { + if (distance <= index && _entries.at(index - distance).kind == Entry::Kind::Data) { + return _entries.at(index - distance).data; + } + if (index + distance < _entries.size() && _entries.at(index + distance).kind == Entry::Kind::Data) { + return _entries.at(index + distance).data; + } + } + return std::nullopt; +} + +bool SummaryRows::summary(std::int64_t mountedRow) const { + return mountedRow >= 0 && static_cast(mountedRow) < _entries.size() && + _entries.at(static_cast(mountedRow)).kind == Entry::Kind::Summary; +} + +table::UnloadedLevels SummaryRows::unloadedLevels(std::int64_t index) const { + std::optional const position = exact(index); + return position ? _data->unloadedLevels(*position) : table::UnloadedLevels{}; +} + +void SummaryRows::visible(std::int64_t first, std::int64_t count, std::span columns) { + auto const [from, rows] = dataRange(first, count); + _data->visible(from, rows, columns); +} + +async::Completion, table::TableError>> SummaryRows::keysOf( + std::int64_t first, std::int64_t count) { + auto const [from, rows] = dataRange(first, count); + return _data->keysOf(from, rows); +} + +void SummaryRows::locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) { + _data->locateRow(std::move(key), std::move(stop), [this, done = std::move(done)](RowLocation const& found) { + if (found && *found) { + done(RowLocation{mounted(**found)}); + return; + } + done(found); + }); +} + +async::Completion, table::TableError>> SummaryRows::rowsOf( + std::int64_t first, std::int64_t count, std::span columns) { + auto const [from, rows] = dataRange(first, count); + return _data->rowsOf(from, rows, columns); +} + +std::shared_ptr SummaryRows::checked(std::shared_ptr data) { + if (data == nullptr) { + throw std::invalid_argument{"morph::ui::SummaryRows: the data rows must not be null"}; + } + return data; +} + +std::optional SummaryRows::exact(std::int64_t index) const { + if (index < 0 || static_cast(index) >= _entries.size()) { + return std::nullopt; + } + Entry const& entry = _entries.at(static_cast(index)); + return entry.kind == Entry::Kind::Data ? std::optional{entry.data} : std::nullopt; +} + +std::pair SummaryRows::dataRange(std::int64_t first, std::int64_t count) const { + std::optional low; + std::int64_t high = -1; + auto const size = static_cast(_entries.size()); + std::int64_t const begin = std::clamp(first, 0, size); + std::int64_t const end = std::clamp(first + std::max(count, 0), begin, size); + for (std::int64_t at = begin; at < end; ++at) { + if (std::optional const data = exact(at)) { + low = low.value_or(*data); + high = *data; + } + } + if (low) { + return {*low, high - *low + 1}; + } + std::int64_t before = 0; + for (std::int64_t at = 0; at < begin; ++at) { + before += exact(at) ? 1 : 0; + } + return {before, 0}; +} + +SummaryRows::Entry SummaryRows::summaryEntry(SummarySpec const& spec, std::optional run, + std::int64_t first, std::int64_t count) const { + ValueRecord record; + record.insert_or_assign(std::string{kSummaryField}, Value{spec.key}); + record.insert_or_assign(std::string{kSummaryFirstField}, Value{first}); + record.insert_or_assign(std::string{kSummaryCountField}, Value{count}); + record.insert_or_assign(std::string{kSummaryVersionField}, Value{static_cast(_version)}); + std::string key = "\x1Fsummary:"; + if (run) { + record.insert_or_assign(std::string{kSummaryRunField}, Value{static_cast(*run)}); + key += std::to_string(*run) + "/"; + } + key += spec.key; + return Entry{.kind = Entry::Kind::Summary, + .data = 0, + .perRun = run.has_value(), + .key = Key{std::move(key)}, + .record = Value{std::move(record)}}; +} + +void SummaryRows::rebuild() { + std::int64_t const total = std::max(_data->total().rows, 0); + std::vector> const runs = + _runs ? _runs() : std::vector>{}; + _entries.clear(); + auto const data = [this](std::int64_t index) { + _entries.push_back(Entry{.kind = Entry::Kind::Data, .data = index, .perRun = false, .key = {}, .record = {}}); + }; + auto const summaries = [this](std::vector const& specs, bool top, std::optional run, + std::int64_t first, std::int64_t count) { + for (SummarySpec const& spec : specs) { + if (spec.top == top) { + _entries.push_back(summaryEntry(spec, run, first, count)); + } + } + }; + summaries(_table, true, std::nullopt, 0, total); + std::int64_t next = 0; + for (std::size_t run = 0; run < runs.size(); ++run) { + std::int64_t const first = std::clamp(runs.at(run).first, next, total); + std::int64_t const last = std::clamp(first + runs.at(run).second, first, total); + for (; next < first; ++next) { + data(next); + } + if (_heading) { + RowRecord heading = _heading(run); + _entries.push_back(Entry{.kind = Entry::Kind::Heading, + .data = 0, + .perRun = true, + .key = std::move(heading.key), + .record = std::move(heading.row)}); + } + summaries(_perRun, true, run, first, last - first); + for (; next < last; ++next) { + data(next); + } + summaries(_perRun, false, run, first, last - first); + } + for (; next < total; ++next) { + data(next); + } + summaries(_table, false, std::nullopt, 0, total); + _mounted.assign(static_cast(total), std::int64_t{0}); + for (std::size_t at = 0; at < _entries.size(); ++at) { + if (_entries.at(at).kind == Entry::Kind::Data) { + _mounted.at(static_cast(_entries.at(at).data)) = static_cast(at); + } + } +} + +void SummaryRows::heard(table::ViewChange const& change) { + std::vector const before = std::move(_entries); + auto const lead = + static_cast(std::ranges::count_if(_table, [](SummarySpec const& spec) { return spec.top; })); + ++_version; + rebuild(); + if (!_onChange) { + return; + } + bool const reset = + std::ranges::any_of(change.ops, [](table::ViewOp const& op) { return op.kind == table::ViewOp::Kind::Reset; }); + table::ViewChange out; + if (!reset && !perRun(before) && !perRun(_entries)) { + // Ungrouped: every data row sits `lead` rows down, before and after. + for (table::ViewOp op : change.ops) { + op.first += lead; + if (op.kind == table::ViewOp::Kind::Moved) { + op.to += lead; + } + out.ops.push_back(op); + } + } else { + bool const sameShape = + !reset && before.size() == _entries.size() && + std::ranges::equal(before, _entries, + [](Entry const& left, Entry const& right) { + return left.kind == right.kind && left.data == right.data && left.key == right.key; + }) && + std::ranges::all_of(change.ops, + [](table::ViewOp const& op) { return op.kind == table::ViewOp::Kind::Changed; }); + if (!sameShape) { + out.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}); + _onChange(out); + return; + } + for (table::ViewOp const& op : change.ops) { + for (std::size_t at = op.first; at < op.first + op.count; ++at) { + if (std::optional const now = mounted(static_cast(at))) { + out.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Changed, + .first = static_cast(*now), + .count = 1, + .to = 0}); + } + } + } + } + for (std::size_t at = 0; at < _entries.size(); ++at) { + if (_entries.at(at).kind != Entry::Kind::Data) { + out.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Changed, .first = at, .count = 1, .to = 0}); + } + } + _onChange(out); +} + +FormatContext formatOf(forms::FormSession const& form) { + forms::FormSessionOptions const& options = form.options(); + FormatContext format; + format.locale = options.bcp47; + format.numeric = options.locale; + format.datePattern = options.datePattern; + format.dateTimePattern = options.dateTimePattern; + return format; +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +void applyUnitOverlay(std::unordered_map>& applied, forms::FieldState& state, + std::optional const& unit, + std::vector>& asLoaded) { + auto const last = applied.find(state.path()); + bool const first = last == applied.end() || !last->second.has_value(); + bool const changed = first ? unit.has_value() : last->second != unit; + applied.insert_or_assign(state.path(), unit); + if (!changed) { + return; + } + std::vector const& units = state.spec().units; + auto const found = unit ? std::ranges::find(units, *unit, &forms::UnitOption::id) : units.end(); + std::size_t const index = + found != units.end() ? static_cast(found - units.begin()) : state.spec().entryUnit; + if (state.unit().peek() == index) { + return; + } + if (first) { + asLoaded.emplace_back(&state, index); + } else { + state.switchUnit(index); + } +} + +std::string fieldText(forms::FieldState& state, std::string_view column, FormatContext const& format) { + forms::Encoding const& encoding = state.encoded().get(); + if (!encoding.has_value() || !encoding->has_value()) { + return state.draft(); + } + forms::FieldSpec const& spec = state.spec(); + table::TableColumn shown; + shown.info = table::ColumnInfo{.id = std::string{column}, .kind = columnKindOf(spec.kind)}; + if (std::optional const places = state.places().get()) { + shown.display.decimals = places; + } else if (spec.decimalPlaces) { + shown.display.decimals = spec.decimalPlaces; + } else if (spec.displayDecimals) { + shown.display.decimals = spec.displayDecimals; + } else if (spec.kind == forms::FieldKind::Integer) { + shown.display.decimals = 0; + } + return formatCell(memberCell(state, shown.info.kind), shown, format); +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +FormGridSource::FormGridSource(forms::FormSession& form, std::string arrayPath, std::vector columns, + FormatContext format) + : _form{&form}, + _formAlive{form.alive()}, + _arrayPath{std::move(arrayPath)}, + _columns{std::move(columns)}, + _format{std::move(format)}, + _formatVersion{form.runtime(), std::uint64_t{0}}, + _layoutVersion{form.runtime(), std::uint64_t{0}} { + forms::FieldState const& array = form.field(_arrayPath); + if (array.spec().kind != forms::FieldKind::ObjectArray || array.spec().truncated) { + throw std::invalid_argument{"morph::ui::FormGridSource: `" + _arrayPath + "` is not a collection"}; + } + for (GridColumn const& column : _columns) { + if (!column.fieldOf && !column.field.empty() && + std::ranges::none_of(array.spec().children, + [&column](forms::FieldSpec const& member) { return member.name == column.field; })) { + throw std::invalid_argument{"morph::ui::FormGridSource: no member `" + column.field + "` in `" + + _arrayPath + "`"}; + } + _layout.push_back(column.id); + } + // The rows' columns are the edit columns, by their own ids, so a sort or a filter names a column as the + // table does; a display column has no cell there and neither sorts nor filters. + std::vector infos; + std::vector members; + std::vector> perRow; + for (GridColumn const& column : _columns) { + if (column.fieldOf) { + // A member per row: the kind varies, so the column sorts and filters the drafts as text. + infos.push_back(table::ColumnInfo{.id = column.id, .kind = table::ColumnKind::Text}); + members.emplace_back(); + perRow.push_back(column.fieldOf); + continue; + } + auto const member = std::ranges::find(array.spec().children, column.field, &forms::FieldSpec::name); + if (!column.field.empty() && member != array.spec().children.end()) { + infos.push_back(table::ColumnInfo{.id = column.id, .kind = detail::columnKindOf(member->kind)}); + members.push_back(column.field); + perRow.emplace_back(); + } + } + _rowsSource = + std::make_shared(form, _arrayPath, std::move(infos), std::move(members), std::move(perRow)); + _rows = std::make_unique(_rowsSource); + if (std::ranges::any_of(_columns, [](GridColumn const& column) { + return column.decimals || column.unit || column.options || column.placeholder; + })) { + _overlays = std::make_unique(form.runtime(), [this] { applyOverlays(); }); + } +} + +FormGridSource::~FormGridSource() { + if (_hook && !_formAlive.expired()) { + _form->removeBeforeSubmit(*_hook); + } +} + +std::size_t FormGridSource::rowCount() const { + _rows->sync(); + return static_cast(_rows->total().rows); +} + +std::optional FormGridSource::keyAt(std::size_t viewRow) const { + _rows->sync(); + std::optional const ref = _rows->row(static_cast(viewRow)); + return ref ? std::optional{ref->key} : std::nullopt; +} + +std::optional FormGridSource::positionOf(Key const& key) const { + _rows->sync(); + return _rows->positionOf(key); +} + +void FormGridSource::setFormat(FormatContext format) { + _format = std::move(format); + _formatVersion.set(_formatVersion.peek() + 1); +} + +void FormGridSource::setLayout(std::vector visible) { + if (visible != _layout) { + _layout = std::move(visible); + _layoutVersion.set(_layoutVersion.peek() + 1); + } +} + +forms::FieldState* FormGridSource::field(Key const& row, std::string_view column) const { + GridColumn const* const declared = columnOf(column); + if (declared == nullptr || !edits(*declared)) { + return nullptr; + } + forms::RowState const* const held = _rowsSource->row(row); + return held == nullptr ? nullptr : memberOf(*declared, *held); +} + +Node FormGridSource::editor(Key const& key, std::string_view column) { + forms::FieldState* const state = field(key, column); + if (state == nullptr) { + return ui::text(Text{.text = std::string{}, .role = TextRole::Muted}); + } + return forms::detail::engine::scalarControl(*_form, *state); +} + +bool FormGridSource::toggles(Key const& key, std::string_view column) const { + forms::FieldState const* const state = field(key, column); + return state != nullptr && state->spec().kind == forms::FieldKind::Boolean; +} + +bool FormGridSource::readOnly(Key const& key, std::string_view column) const { + GridColumn const* const declared = columnOf(column); + bool overlay = false; + if (declared != nullptr && declared->readonly) { + forms::RowState const* const held = _rowsSource->row(key); + overlay = held != nullptr && declared->readonly(*held); + } + return cellReadOnly(CellFacts{ + .field = field(key, column), .hasEdit = declared != nullptr && edits(*declared), .overlayReadOnly = overlay}); +} + +bool FormGridSource::covered(Key const& key, std::string_view column) const { + if (!_spansOf) { + return false; + } + Coverage const& coverage = coverageNow(); + auto const found = coverage.covered.find(key); + return found != coverage.covered.end() && std::ranges::contains(found->second, column); +} + +std::vector FormGridSource::spans(Key const& key) const { + if (!_spansOf) { + return {}; + } + static_cast(_layoutVersion.get()); + Coverage const& coverage = coverageNow(); + auto const found = coverage.given.find(key); + return found == coverage.given.end() ? std::vector{} : found->second; +} + +void FormGridSource::setSpans(std::function(forms::RowState const&)> spansOf) { + _spansOf = std::move(spansOf); + _coverage.reset(); +} + +std::string FormGridSource::draft(Key const& key, std::string_view column) const { + forms::FieldState const* const state = field(key, column); + return state == nullptr ? std::string{} : _form->runtime().untracked([&] { return state->draft(); }); +} + +std::string FormGridSource::text(Key const& key, std::string_view column) const { + GridColumn const* const declared = columnOf(column); + if (declared == nullptr) { + return {}; + } + if (!edits(*declared)) { + forms::RowState const* const held = _rowsSource->row(key); + return held != nullptr && declared->value ? declared->value(*held) : std::string{}; + } + forms::FieldState* const state = field(key, column); + if (state == nullptr) { + return {}; + } + static_cast(_formatVersion.get()); + return detail::fieldText(*state, column, _format); +} + +std::optional FormGridSource::error(Key const& key, std::string_view column) const { + forms::FieldState const* const state = field(key, column); + if (state == nullptr) { + return std::nullopt; + } + std::optional const& failed = state->error().get(); + return failed ? std::optional{failed->message} : _form->refusal(state->path()); +} + +void FormGridSource::write(Key const& key, std::string_view column, std::string draft) { + if (forms::FieldState* const state = field(key, column)) { + state->text().set(std::move(draft)); + } +} + +void FormGridSource::committed() { + _form->noteCommit(); + if (_committed) { + _committed(); + } +} + +void FormGridSource::editorOpened(Key const& key, std::string_view column) { + if (forms::FieldState* const state = field(key, column)) { + state->openOptions(); + } +} + +std::pair> FormGridSource::bounds() const { + forms::FieldSpec const& spec = _rowsSource->array().spec(); + return {spec.minItems.value_or(0), spec.maxItems}; +} + +std::optional FormGridSource::appendRow() { + if (atMost()) { + return std::nullopt; + } + std::uint64_t const key = _rowsSource->array().addRow(); + _rows->sync(); + return key == 0 ? std::nullopt : std::optional{Key{static_cast(key)}}; +} + +std::optional FormGridSource::insertRow(std::size_t position) { + if (atMost()) { + return std::nullopt; + } + forms::FieldState& array = _rowsSource->array(); + std::size_t place = _form->runtime().untracked([&] { return array.rows().size(); }); + if (std::optional const before = keyAt(position)) { + std::int64_t const* const number = std::get_if(&*before); + std::vector> const& rows = + _form->runtime().untracked([&] -> auto const& { return array.rows(); }); + auto const found = std::ranges::find_if( + rows, [number](auto const& row) { return number != nullptr && std::cmp_equal(row->key(), *number); }); + place = static_cast(found - rows.begin()); + } + std::uint64_t const key = array.insertRow(place); + _rows->sync(); + return key == 0 ? std::nullopt : std::optional{Key{static_cast(key)}}; +} + +bool FormGridSource::removeRows(std::span keys) { + std::vector numbers; + for (Key const& key : keys) { + if (std::int64_t const* const number = std::get_if(&key); number != nullptr && *number > 0) { + numbers.push_back(static_cast(*number)); + } + } + forms::FieldState& array = _rowsSource->array(); + _removed = array.removeRows(numbers); + _rows->sync(); + _afterRemove = array.snapshot(); + return _form->runtime().untracked( + [&] { return std::ranges::any_of(_removed, [](forms::RemovedRow const& row) { return !row.row->blank(); }); }); +} + +void FormGridSource::undoRemove() { + forms::FieldState& array = _rowsSource->array(); + std::vector rows = std::exchange(_removed, {}); + if (rows.empty() || array.snapshot() != _afterRemove) { + return; + } + array.restoreRows(std::move(rows)); + _rows->sync(); +} + +CellMarks FormGridSource::marks(Key const& key, std::string_view column) const { + forms::FieldState const* const state = field(key, column); + bool const derived = state != nullptr && (state->spec().computed || state->spec().derived); + return CellMarks{.readOnly = readOnly(key, column), + .modified = state != nullptr && _form->modified(state->path()), + .error = error(key, column).has_value(), + .stale = derived && _form->deriveFailing(), + .muted = derived && _form->deriveState() == forms::DeriveState::Running}; +} + +std::optional FormGridSource::keyOf(Value const& record) const { + Value const* const key = record.field(kGridKeyField); + std::int64_t const* const number = key == nullptr ? nullptr : key->asInt(); + return number == nullptr ? std::nullopt : std::optional{Key{*number}}; +} + +bool FormGridSource::rowModified(Key const& key) const { + std::int64_t const* const number = std::get_if(&key); + return number != nullptr && *number >= 0 && _form->rowModified(_arrayPath, static_cast(*number)); +} + +void FormGridSource::revertCell(Key const& key, std::string_view column) { + if (forms::FieldState const* const state = field(key, column)) { + _form->revert(state->path()); + } +} + +void FormGridSource::revertRow(Key const& key) { + if (std::int64_t const* const number = std::get_if(&key)) { + _form->revert(_arrayPath + "#" + std::to_string(*number)); + } +} + +void FormGridSource::onBeforeSubmit(std::function commit) { + if (_hook) { + _form->removeBeforeSubmit(*_hook); + } + _hook = _form->addBeforeSubmit(std::move(commit)); +} + +std::size_t FormGridSource::modifiedRows() const { + std::size_t rows = 0; + for (auto const& row : _rowsSource->array().rows()) { + rows += _form->rowModified(_arrayPath, row->key()) ? 1U : 0U; + } + return rows; +} + +std::size_t FormGridSource::errorCount() const { + return countCells([this](forms::FieldState const& state) { + return state.error().get().has_value() || _form->refusal(state.path()).has_value(); + }); +} + +std::optional> FormGridSource::filterCell(Key const& key, + std::string_view column) const { + forms::FieldState const* const state = field(key, column); + if (state == nullptr) { + return std::nullopt; + } + table::TableColumn shown; + GridColumn const* const declared = columnOf(column); + if (declared != nullptr && declared->fieldOf) { + // The rows' column holds text, whatever the row's member is. + shown.info = table::ColumnInfo{.id = std::string{column}, .kind = table::ColumnKind::Text}; + return std::pair{detail::perRowCell(*state), shown}; + } + shown.info = table::ColumnInfo{.id = std::string{column}, .kind = detail::columnKindOf(state->spec().kind)}; + return std::pair{detail::memberCell(*state, shown.info.kind), shown}; +} + +bool FormGridSource::atMost() const { + std::optional const most = bounds().second; + return most && _form->runtime().untracked([&] { return heldRows(); }) >= *most; +} + +GridColumn const* FormGridSource::columnOf(std::string_view columnId) const { + auto const found = std::ranges::find(_columns, columnId, &GridColumn::id); + return found == _columns.end() ? nullptr : &*found; +} + +forms::FieldState* FormGridSource::memberOf(GridColumn const& column, forms::RowState const& row) { + if (column.fieldOf) { + return row.field(column.fieldOf(row)); + } + return column.field.empty() ? nullptr : row.field(column.field); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): applies each column's overlay to each row's member in one pass over the rows; the places, entry unit, options and placeholder steps read the same row state +void FormGridSource::applyOverlays() { + // Forget the units applied to members of rows that are gone: a reload builds every row anew. + if (!_unitApplied.empty()) { + std::unordered_set present; + for (auto const& row : _rowsSource->array().rows()) { + for (auto const& member : row->fields()) { + present.insert(member->path()); + } + } + std::erase_if(_unitApplied, [&present](auto const& entry) { return !present.contains(entry.first); }); + } + // The first units a load's rows take, switched together after the walk (one batch, one pass over the form). + std::vector> asLoaded; + for (auto const& row : _rowsSource->array().rows()) { + for (GridColumn const& column : _columns) { + forms::FieldState* const state = memberOf(column, *row); + if (state == nullptr) { + continue; + } + std::optional const places = column.decimals ? column.decimals(*row) : std::nullopt; + std::optional const unit = column.unit ? column.unit(*row) : std::nullopt; + std::optional> options = column.options ? column.options(*row) : std::nullopt; + std::string placeholder = column.placeholder ? column.placeholder(*row) : std::string{}; + _form->runtime().untracked([&] { + if (column.decimals && state->places().peek() != places) { + state->places().set(places); + } + if (column.unit) { + applyUnit(*state, unit, asLoaded); + } + if (column.options) { + state->narrowOptions(std::move(options)); + } + if (column.placeholder) { + state->overridePlaceholder(std::move(placeholder)); + } + }); + } + } + _form->runtime().untracked([&] { _form->switchUnitsAsLoaded(asLoaded); }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): rows, their spans, and the cells each covers. +FormGridSource::Coverage const& FormGridSource::coverageNow() const { + _rows->sync(); + std::shared_ptr const snapshot = _rowsSource->snapshot(); + bool const sorted = _rows->sorted(); + if (_coverage && _coverage->snapshot == snapshot && _coverage->layout == _layout && _coverage->sorted == sorted) { + return *_coverage; + } + Coverage next{.snapshot = snapshot, .layout = _layout, .sorted = sorted, .covered = {}, .given = {}}; + Virtualization const limits{}; + auto const rows = static_cast(std::max(_rows->total().rows, 0)); + bool const applies = !sorted && rows < limits.threshold && _layout.size() < limits.columnThreshold && + rows * _layout.size() < limits.cellThreshold; + if (applies) { + std::vector declared; + declared.reserve(_columns.size()); + for (GridColumn const& column : _columns) { + declared.push_back(column.id); + } + // NOLINTNEXTLINE(readability-function-cognitive-complexity): one untracked read of the form: the overlay steps share the locals the reads fill, so they stay in one lambda + _form->runtime().untracked([&] { + for (std::size_t row = 0; row < rows; ++row) { + std::optional const ref = _rows->row(static_cast(row)); + forms::RowState const* const held = ref ? _rowsSource->row(ref->key) : nullptr; + if (held == nullptr) { + continue; + } + for (CellSpan span : _spansOf(*held)) { + span.columns = cutColumns(span, declared, _layout); + auto const place = std::ranges::find(_layout, span.column); + // A span past the last row is refused by the mount and drawn as nothing, so it covers + // nothing here either. + if (span.columns == 0 || span.rows == 0 || place == _layout.end() || span.rows > rows - row) { + continue; + } + auto const first = static_cast(place - _layout.begin()); + for (std::size_t down = 0; down < span.rows; ++down) { + std::optional const below = _rows->row(static_cast(row + down)); + if (!below) { + continue; + } + for (std::size_t right = 0; right < span.columns; ++right) { + if (down != 0 || right != 0) { + next.covered[below->key].push_back(_layout.at(first + right)); + } + } + } + next.given[ref->key].push_back(std::move(span)); + } + } + }); + } + _coverage = std::move(next); + return *_coverage; +} + +FixedGridSource::FixedGridSource(reactive::Runtime& runtime, forms::FormSession* form, std::vector rows, + std::vector columns, FormatContext format) + : _rt{&runtime}, + _form{form}, + _formAlive{form != nullptr ? form->alive() : std::weak_ptr{}}, + _parts{std::move(rows)}, + _columns{std::move(columns)}, + _format{std::move(format)}, + _formatVersion{runtime, std::uint64_t{0}}, + _layoutVersion{runtime, std::uint64_t{0}}, + _data{std::make_shared(std::vector{ + table::ColumnInfo{.id = std::string{kGridKeyField}, .kind = table::ColumnKind::Text}})} { + for (GridColumn const& column : _columns) { + _layout.push_back(column.id); + } + checkParts(); + expand(); + table::EngineOptions options; + options.owner = &runtime.owner(); + _rows = std::make_unique( + _data, + [](table::RowSnapshot const& snapshot, std::size_t row) { + table::RowId key = snapshot.rowId(row); + ValueRecord record; + record.insert_or_assign(std::string{kGridKeyField}, Value{std::get(key)}); + return RowRecord{.key = std::move(key), .row = Value{std::move(record)}}; + }, + std::move(options)); + _rows->engine().flush(); + if (std::ranges::any_of(_parts, [](Part const& part) { return std::holds_alternative(part); })) { + _watch = std::make_unique(runtime, [this] { watch(); }); + } + if (std::ranges::any_of(_parts, [](Part const& part) { + return std::ranges::any_of(rowsOf(part), [](FixedRow const& row) { + return std::ranges::any_of(row.cells, [](auto const& cell) { + FixedCell const& given = cell.second; + return !given.field.empty() && + (given.decimals || given.unit || given.options || given.placeholder); + }); + }); + })) { + _overlays = std::make_unique(runtime, [this] { applyOverlays(); }); + } +} + +FixedGridSource::~FixedGridSource() { + _overlays.reset(); + _watch.reset(); + if (_hook && _form != nullptr && !_formAlive.expired()) { + _form->removeBeforeSubmit(*_hook); + } +} + +std::size_t FixedGridSource::rowCount() const { + sync(); + return _expanded.size(); +} + +std::optional FixedGridSource::keyAt(std::size_t viewRow) const { + sync(); + return viewRow < _expanded.size() ? std::optional{_expanded.at(viewRow).key} : std::nullopt; +} + +std::optional FixedGridSource::positionOf(Key const& key) const { + sync(); + auto const found = _index.find(key); + return found == _index.end() ? std::nullopt : std::optional{found->second}; +} + +void FixedGridSource::setFormat(FormatContext format) { + _format = std::move(format); + _formatVersion.set(_formatVersion.peek() + 1); +} + +void FixedGridSource::setLayout(std::vector visible) { + if (visible != _layout) { + _layout = std::move(visible); + _layoutVersion.set(_layoutVersion.peek() + 1); + } +} + +forms::FieldState* FixedGridSource::field(Key const& key, std::string_view column) const { + Expanded const* const row = expandedOf(key); + if (row == nullptr) { + return nullptr; + } + auto const found = row->fields.find(column); + return found == row->fields.end() ? nullptr : found->second; +} + +std::string FixedGridSource::label(Key const& key) const { + Expanded const* const row = expandedOf(key); + return row == nullptr ? std::string{} : row->row->label; +} + +Node FixedGridSource::editor(Key const& key, std::string_view column) { + forms::FieldState* const state = field(key, column); + if (state == nullptr || _form == nullptr) { + return ui::text(Text{.text = std::string{}, .role = TextRole::Muted}); + } + return forms::detail::engine::scalarControl(*_form, *state); +} + +bool FixedGridSource::toggles(Key const& key, std::string_view column) const { + forms::FieldState const* const state = field(key, column); + return state != nullptr && state->spec().kind == forms::FieldKind::Boolean; +} + +bool FixedGridSource::readOnly(Key const& key, std::string_view column) const { + auto const [cell, specimen] = cellOf(key, column); + bool const overlay = cell != nullptr && cell->readonly && cell->readonly(specimen); + return cellReadOnly(CellFacts{ + .field = field(key, column), .hasEdit = cell != nullptr && !cell->field.empty(), .overlayReadOnly = overlay}); +} + +bool FixedGridSource::covered(Key const& key, std::string_view column) const { + Coverage const& coverage = coverageNow(); + auto const found = coverage.covered.find(key); + return found != coverage.covered.end() && std::ranges::contains(found->second, column); +} + +std::vector FixedGridSource::spans(Key const& key) const { + static_cast(_layoutVersion.get()); + Coverage const& coverage = coverageNow(); + auto const found = coverage.given.find(key); + return found == coverage.given.end() ? std::vector{} : found->second; +} + +bool FixedGridSource::spanning() const { + return std::ranges::any_of(_parts, [](Part const& part) { + return std::ranges::any_of(rowsOf(part), [](FixedRow const& row) { + return std::ranges::any_of( + row.cells, [](auto const& cell) { return cell.second.rows > 1 || cell.second.columns > 1; }); + }); + }); +} + +std::string FixedGridSource::draft(Key const& key, std::string_view column) const { + forms::FieldState const* const state = field(key, column); + return state == nullptr ? std::string{} : _rt->untracked([&] { return state->draft(); }); +} + +std::string FixedGridSource::text(Key const& key, std::string_view column) const { + auto const [cell, specimen] = cellOf(key, column); + if (cell == nullptr) { + return {}; + } + if (cell->field.empty()) { + return cell->value ? cell->value(specimen) : cell->text; + } + forms::FieldState* const state = field(key, column); + if (state == nullptr) { + return {}; + } + static_cast(_formatVersion.get()); + return detail::fieldText(*state, column, _format); +} + +std::optional FixedGridSource::error(Key const& key, std::string_view column) const { + forms::FieldState const* const state = field(key, column); + if (state == nullptr) { + return std::nullopt; + } + std::optional const& failed = state->error().get(); + return failed ? std::optional{failed->message} : _form->refusal(state->path()); +} + +void FixedGridSource::write(Key const& key, std::string_view column, std::string draft) { + if (forms::FieldState* const state = field(key, column)) { + state->text().set(std::move(draft)); + } +} + +void FixedGridSource::committed() { + if (_form != nullptr) { + _form->noteCommit(); + } +} + +void FixedGridSource::editorOpened(Key const& key, std::string_view column) { + if (forms::FieldState* const state = field(key, column)) { + state->openOptions(); + } +} + +void FixedGridSource::recalculate() { + if (_form != nullptr) { + _form->recalculate(); + } +} + +CellMarks FixedGridSource::marks(Key const& key, std::string_view column) const { + forms::FieldState const* const state = field(key, column); + bool const derived = state != nullptr && (state->spec().computed || state->spec().derived); + return CellMarks{.readOnly = readOnly(key, column), + .modified = state != nullptr && _form->modified(state->path()), + .error = error(key, column).has_value(), + .stale = derived && _form->deriveFailing(), + .muted = derived && _form->deriveState() == forms::DeriveState::Running}; +} + +std::optional FixedGridSource::keyOf(Value const& record) const { + Value const* const key = record.field(kGridKeyField); + std::string const* const text = key == nullptr ? nullptr : key->asString(); + return text == nullptr ? std::nullopt : std::optional{Key{*text}}; +} + +bool FixedGridSource::rowModified(Key const& key) const { + Expanded const* const row = expandedOf(key); + return row != nullptr && std::ranges::any_of(row->fields, [this](auto const& entry) { + return entry.second != nullptr && _form->modified(entry.second->path()); + }); +} + +EngineRows& FixedGridSource::view() { + sync(); + return *_rows; +} + +void FixedGridSource::revertCell(Key const& key, std::string_view column) { + if (forms::FieldState const* const state = field(key, column)) { + _form->revert(state->path()); + } +} + +void FixedGridSource::revertRow(Key const& key) { + Expanded const* const row = expandedOf(key); + if (row == nullptr) { + return; + } + std::vector paths; + for (auto const& [column, state] : row->fields) { + if (state != nullptr) { + paths.push_back(state->path()); + } + } + for (std::string const& path : paths) { + _form->revert(path); + } +} + +void FixedGridSource::onBeforeSubmit(std::function commit) { + if (_form == nullptr) { + return; + } + if (_hook) { + _form->removeBeforeSubmit(*_hook); + } + _hook = _form->addBeforeSubmit(std::move(commit)); +} + +std::size_t FixedGridSource::modifiedRows() const { + sync(); + return static_cast( + std::ranges::count_if(_expanded, [this](Expanded const& row) { return rowModified(row.key); })); +} + +std::size_t FixedGridSource::errorCount() const { + return countCells([this](forms::FieldState const& state) { + return state.error().get().has_value() || _form->refusal(state.path()).has_value(); + }); +} + +std::span FixedGridSource::rowsOf(Part const& part) { + if (FixedRow const* const row = std::get_if(&part)) { + return {row, 1}; + } + return std::get(part).rows; +} + +forms::FieldSpec const* FixedGridSource::specAt(std::span fields, std::string_view path) { + forms::FieldSpec const* found = nullptr; + while (!path.empty()) { + std::size_t const dot = path.find('.'); + std::string_view const name = path.substr(0, dot); + path = dot == std::string_view::npos ? std::string_view{} : path.substr(dot + 1); + auto const member = std::ranges::find(fields, name, &forms::FieldSpec::name); + if (member == fields.end()) { + return nullptr; + } + found = &*member; + fields = member->children; + } + return found; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one refusal per rule of a part. +void FixedGridSource::checkParts() const { + std::unordered_set keys; + for (Part const& part : _parts) { + FixedBlock const* const block = std::get_if(&part); + std::span members; + if (block != nullptr) { + if (_form == nullptr) { + refuse("a block repeats rows of a form's collection, and there is no form"); + } + forms::FieldState const* array = nullptr; + try { + array = &_form->field(block->forEach); + } catch (std::out_of_range const&) { + refuse("`" + block->forEach + "` is not a field of the form"); + } + if (array->spec().kind != forms::FieldKind::ObjectArray || array->spec().truncated) { + refuse("`" + block->forEach + "` is not a collection"); + } + members = array->spec().children; + } + for (FixedRow const& row : rowsOf(part)) { + if (row.key.contains('/')) { + refuse("the key `" + row.key + "` holds a `/`, which joins a block row's keys"); + } + if (row.key.empty() || !keys.insert(row.key).second) { + refuse(row.key.empty() ? std::string{"a row has no key"} : "the key `" + row.key + "` is given twice"); + } + for (auto const& [column, cell] : row.cells) { + if (cell.field.empty()) { + continue; + } + if (_form == nullptr) { + refuse("the cell `" + row.key + "`, `" + column + "` edits a field, and there is no form"); + } + bool const known = block != nullptr ? specAt(members, cell.field) != nullptr : [&] { + try { + static_cast(_form->field(cell.field)); + return true; + } catch (std::out_of_range const&) { + return false; + } + }(); + if (!known) { + refuse("`" + cell.field + "` is not a field of the form"); + } + } + } + } +} + +} // namespace morph::ui diff --git a/src/ui/grid_2.cpp b/src/ui/grid_2.cpp new file mode 100644 index 000000000..a25b85ace --- /dev/null +++ b/src/ui/grid_2.cpp @@ -0,0 +1,1419 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +FixedGridSource::BlockRows FixedGridSource::blockRows() const { + BlockRows out; + for (Part const& part : _parts) { + if (FixedBlock const* const block = std::get_if(&part)) { + std::vector> rows; + for (auto const& row : _form->field(block->forEach).rows()) { + rows.emplace_back(row->key(), row.get()); + } + out.push_back(std::move(rows)); + } + } + return out; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): rebuilds the rows from the parts and the collections in one pass, each part kind appending in the order the document lists them +void FixedGridSource::expand() const { + std::vector next; + _blockRows = _rt->untracked([&] { return blockRows(); }); + std::size_t block = 0; + for (Part const& part : _parts) { + if (FixedRow const* const row = std::get_if(&part)) { + Expanded made{.key = Key{row->key}, .row = row, .specimen = nullptr, .fields = {}}; + for (auto const& [column, cell] : row->cells) { + if (!cell.field.empty()) { + made.fields.insert_or_assign(column, &_form->field(cell.field)); + } + } + next.push_back(std::move(made)); + continue; + } + auto const& repeated = std::get(part); + for (auto const& [rowKey, specimen] : _blockRows.at(block)) { + for (FixedRow const& row : repeated.rows) { + Expanded made{.key = Key{std::to_string(rowKey) + "/" + row.key}, + .row = &row, + .specimen = specimen, + .fields = {}}; + for (auto const& [column, cell] : row.cells) { + if (cell.field.empty()) { + continue; + } + std::string const path = repeated.forEach + "#" + std::to_string(rowKey) + "." + cell.field; + try { + made.fields.insert_or_assign(column, &_form->field(path)); + } catch (std::out_of_range const&) { + made.fields.insert_or_assign(column, nullptr); + } + } + next.push_back(std::move(made)); + } + } + ++block; + } + _expanded = std::move(next); + _index.clear(); + std::vector ids; + std::vector> cells; + for (std::size_t at = 0; at < _expanded.size(); ++at) { + Key const& key = _expanded.at(at).key; + _index.emplace(key, at); + ids.push_back(key); + cells.push_back({table::Cell{std::get(key)}}); + } + ++_expansion; + _data->setRows(std::move(ids), std::move(cells)); +} + +void FixedGridSource::sync() const { + if (_blockRows.empty() || blockRows() == _blockRows) { + return; + } + _rt->untracked([&] { expand(); }); + _rows->engine().flush(); +} + +void FixedGridSource::watch() { + static_cast(blockRows()); + if (_watching && !_posted) { + _posted = true; + _rt->owner().post(_alive.guard([this] { + _posted = false; + sync(); + })); + } + _watching = true; +} + +FixedGridSource::Expanded const* FixedGridSource::expandedOf(Key const& key) const { + sync(); + auto const found = _index.find(key); + return found == _index.end() ? nullptr : &_expanded.at(found->second); +} + +std::pair FixedGridSource::cellOf(Key const& key, + std::string_view column) const { + Expanded const* const row = expandedOf(key); + if (row == nullptr) { + return {nullptr, nullptr}; + } + auto const found = row->row->cells.find(column); + return {found == row->row->cells.end() ? nullptr : &found->second, row->specimen}; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per overlay. +void FixedGridSource::applyOverlays() { + sync(); + if (std::uint64_t const generation = _form->loadGeneration(); generation != _unitGeneration) { + // A field the user changed keeps the unit they left it in. + _rt->untracked( + [&] { std::erase_if(_unitApplied, [this](auto const& entry) { return !_form->modified(entry.first); }); }); + _unitGeneration = generation; + } + std::vector> asLoaded; + for (Expanded const& row : _expanded) { + for (auto const& [column, state] : row.fields) { + auto const found = row.row->cells.find(column); + if (state == nullptr || found == row.row->cells.end()) { + continue; + } + FixedCell const& cell = found->second; + std::optional const places = cell.decimals ? cell.decimals(row.specimen) : std::nullopt; + std::optional const unit = cell.unit ? cell.unit(row.specimen) : std::nullopt; + std::optional> options = cell.options ? cell.options(row.specimen) : std::nullopt; + std::string placeholder = cell.placeholder ? cell.placeholder(row.specimen) : std::string{}; + _rt->untracked([&] { + if (cell.decimals && state->places().peek() != places) { + state->places().set(places); + } + if (cell.unit) { + detail::applyUnitOverlay(_unitApplied, *state, unit, asLoaded); + } + if (cell.options) { + state->narrowOptions(std::move(options)); + } + if (cell.placeholder) { + state->overridePlaceholder(std::move(placeholder)); + } + }); + } + } + if (!asLoaded.empty()) { + _rt->untracked([&] { _form->switchUnitsAsLoaded(asLoaded); }); + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): recomputes the coverage once from the rows and the layout; the span walk and the cache check share the running coverage +FixedGridSource::Coverage const& FixedGridSource::coverageNow() const { + sync(); + if (_coverage && _coverage->expansion == _expansion && _coverage->layout == _layout) { + return *_coverage; + } + Coverage next{.expansion = _expansion, .layout = _layout, .covered = {}, .given = {}}; + std::vector declared; + declared.reserve(_columns.size()); + for (GridColumn const& column : _columns) { + declared.push_back(column.id); + } + for (std::size_t at = 0; at < _expanded.size(); ++at) { + Expanded const& row = _expanded.at(at); + for (auto const& [column, cell] : row.row->cells) { + if (cell.rows <= 1 && cell.columns <= 1) { + continue; + } + CellSpan span{.column = column, .rows = cell.rows, .columns = cell.columns}; + span.columns = cutColumns(span, declared, _layout); + auto const place = std::ranges::find(_layout, span.column); + // A span past the last row is refused by the mount and drawn as nothing, so it covers nothing here + // either. + if (span.columns == 0 || span.rows == 0 || place == _layout.end() || span.rows > _expanded.size() - at) { + continue; + } + auto const first = static_cast(place - _layout.begin()); + for (std::size_t down = 0; down < span.rows; ++down) { + for (std::size_t right = 0; right < span.columns; ++right) { + if (down != 0 || right != 0) { + next.covered[_expanded.at(at + down).key].push_back(_layout.at(first + right)); + } + } + } + next.given[row.key].push_back(std::move(span)); + } + } + _coverage = std::move(next); + return *_coverage; +} + +ModelGridSource::ModelGridSource(std::shared_ptr rows, table::CellEdits& edits, + std::vector columns, EditMode mode, ModelGridContext context) + : _rows{std::move(rows)}, + _edits{&edits}, + _columns{std::move(columns)}, + _mode{mode}, + _context{std::move(context)}, + _rt{_context.runtime}, + _version{*_context.runtime, std::uint64_t{0}}, + _open{*_context.runtime, std::optional{}} { + for (ModelColumn const& column : _columns) { + _layout.push_back(column.id); + if (column.edit && column.model != nullptr && !column.path.empty()) { + // The submitter is never called: an edit is sent as a row commit, by the table's own `CellEdits`. + exec::IExecutor* const owner = &_rt->owner(); + auto session = std::make_unique( + *_rt, *column.model, + [owner](std::string_view, std::string const&) { + return async::Completion::makeSettleable(owner).first; + }, + _context.choices, _context.session); + _sessions.insert_or_assign(column.id, Session{.form = std::move(session), .loadedFor = {}, .base = {}}); + } + } + _view = std::make_unique(*this); + _edits->onRowSettled(_alive.guard([this](table::RowId const& row, bool refused) { rowSettled(row, refused); })); +} + +void ModelGridSource::setDescription(table::TableDescription const& description) { + _description = description; + auto units = table::registryOf(description); + _units = units ? *std::move(units) : nullptr; + std::vector ids; + ids.reserve(description.columns.size()); + for (table::TableColumn const& column : description.columns) { + ids.push_back(column.info.id); + } + _edits->keepColumns(ids); + for (auto& [row, cells] : _held) { + std::erase_if(cells, [&ids](table::EditCell const& cell) { return !std::ranges::contains(ids, cell.column); }); + } + std::erase_if(_resend, [&ids](CellRef const& cell) { return !std::ranges::contains(ids, cell.column); }); + _positionsVersion.reset(); + bump(); +} + +void ModelGridSource::setLayout(std::vector visible) { + if (visible != _layout) { + _layout = std::move(visible); + bump(); + } +} + +void ModelGridSource::setFormat(FormatContext format) { + _context.format = std::move(format); + bump(); +} + +void ModelGridSource::rowsAbsent(std::span keys) { + for (table::RowId const& key : keys) { + _edits->rowAbsent(key); + _held.erase(key); + std::erase_if(_resend, [&key](CellRef const& cell) { return cell.key == key; }); + } + bump(); +} + +void ModelGridSource::moveKey(Key const& from, Key const& destination) { + if (from == destination) { + return; + } + _rows->moveKey(from, destination); + _edits->moveRow(from, destination); + if (auto const held = _held.extract(from); !held.empty()) { + std::vector& target = _held[destination]; + for (table::EditCell& cell : held.mapped()) { + if (!std::ranges::contains(target, cell.column, &table::EditCell::column)) { + target.push_back(std::move(cell)); + } + } + } + for (CellRef& cell : _resend) { + if (cell.key == from) { + cell.key = destination; + } + } + _positionsVersion.reset(); + bump(); + if (_focus.moved) { + std::function const moved = _focus.moved; + moved(from, destination); + } +} + +std::optional ModelGridSource::heldDraft(Key const& key, std::string_view column) const { + static_cast(_version.get()); + if (std::optional const open = _open.get(); open && open->key == key && open->column == column) { + if (Session const* const session = sessionOf(column); session != nullptr && session->loadedFor == key) { + return fieldOf(column)->text().get(); + } + } + return _edits->draft(key, column); +} + +std::optional ModelGridSource::heldText(Key const& key, std::string_view column) const { + std::optional held = heldDraft(key, column); + table::TableColumn const* const shown = describedColumn(column); + forms::FieldState const* const field = fieldOf(column); + if (held && !held->empty() && shown != nullptr && shown->info.kind == table::ColumnKind::Measure && + field != nullptr && !field->spec().unit.empty()) { + *held += " " + field->spec().unit; + } + return held; +} + +std::size_t ModelGridSource::rowCount() const { + static_cast(_version.get()); + return static_cast(std::max(_rows->total().rows, 0)); +} + +std::optional ModelGridSource::keyAt(std::size_t viewRow) const { + static_cast(_version.get()); + std::optional const row = _rows->row(static_cast(viewRow)); + return row ? std::optional{row->key} : std::nullopt; +} + +std::optional ModelGridSource::positionOf(Key const& key) const { + if (_positionsVersion != _rowsVersion) { + _positions.clear(); + for (auto const& [first, count] : _rows->heldRanges()) { + for (std::int64_t at = first; at < first + count; ++at) { + if (std::optional const row = _rows->row(at)) { + _positions.insert_or_assign(row->key, static_cast(at)); + } + } + } + _positionsVersion = _rowsVersion; + } + auto const found = _positions.find(key); + return found == _positions.end() ? std::nullopt : std::optional{found->second}; +} + +Node ModelGridSource::editor(Key const& key, std::string_view column) { + Session* const session = loaded(key, column); + if (session == nullptr) { + return ui::text(Text{.text = std::string{}, .role = TextRole::Muted}); + } + return forms::detail::engine::scalarControl(*session->form, *fieldOf(column)); +} + +bool ModelGridSource::toggles(Key const& key, std::string_view column) const { + static_cast(key); + forms::FieldState const* const field = fieldOf(column); + return field != nullptr && field->spec().kind == forms::FieldKind::Boolean; +} + +bool ModelGridSource::covered(Key const& key, std::string_view column) const { + static_cast(key); + static_cast(column); + return false; +} + +std::string ModelGridSource::draft(Key const& key, std::string_view column) const { + return _rt->untracked([&] { + if (std::optional held = heldDraft(key, column)) { + return std::move(*held); + } + // The column's one session holds an open editor's cell: another cell of the column is read as it shows. + if (std::optional const open = _open.peek(); open && open->column == column && open->key != key) { + return text(key, column); + } + // With no draft held the cell is the row's value now: a session still holding an earlier edit of the + // cell, whose draft a fetch since ended, is loaded again. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast): the method is const for readers but refreshes the lazily loaded sessions, which are cache state this object owns + auto* const self = const_cast(this); + if (auto const found = self->_sessions.find(column); found != self->_sessions.end()) { + found->second.loadedFor.reset(); + } + Session const* const session = self->loaded(key, column); + return session == nullptr ? std::string{} : fieldOf(column)->draft(); + }); +} + +std::string ModelGridSource::text(Key const& key, std::string_view column) const { + if (std::optional held = heldText(key, column)) { + return std::move(*held); + } + table::TableColumn const* const described = describedColumn(column); + std::optional const row = locate(key); + if (described == nullptr || !row) { + return {}; + } + return formatCell(cellOf(row->record.field(column)), *described, _context.format); +} + +std::optional ModelGridSource::error(Key const& key, std::string_view column) const { + static_cast(_version.get()); + return _edits->error(key, column); +} + +void ModelGridSource::write(Key const& key, std::string_view column, std::string draft) { + Session const* const session = loaded(key, column); + if (session == nullptr) { + return; + } + _open.set(CellRef{.key = key, .column = std::string{column}}); + fieldOf(column)->text().set(std::move(draft)); + CellRef const cell{.key = key, .column = std::string{column}}; + if (!std::ranges::contains(_dirty, cell)) { + _dirty.push_back(cell); + } + hold(key, column); +} + +void ModelGridSource::committed() { + std::vector cells = std::exchange(_dirty, {}); + // An editor's input writes its field without `write`: the open cell is committed too. + if (std::optional const open = _open.peek(); open && !std::ranges::contains(cells, *open)) { + cells.push_back(*open); + } + for (CellRef const& cell : cells) { + std::optional const made = encode(cell.key, cell.column); + if (!made) { + continue; + } + if (_mode == EditMode::Cell) { + _edits->commitRow(table::RowEditRequest{.row = cell.key, .cells = {*made}}); + continue; + } + std::vector& held = _held[cell.key]; + std::erase_if(held, [&](table::EditCell const& other) { return other.column == made->column; }); + held.push_back(*made); + } + _open.set(std::nullopt); + bump(); +} + +void ModelGridSource::editorOpened(Key const& key, std::string_view column) { + if (loaded(key, column) == nullptr) { + return; + } + _open.set(CellRef{.key = key, .column = std::string{column}}); + fieldOf(column)->openOptions(); +} + +CellMarks ModelGridSource::marks(Key const& key, std::string_view column) const { + static_cast(_version.get()); + return CellMarks{.readOnly = readOnly(key, column), + .modified = _edits->modified(key, column), + .error = _edits->error(key, column).has_value(), + .stale = _edits->stale(key, column)}; +} + +std::optional ModelGridSource::keyOf(Value const& record) const { + if (!_description) { + return std::nullopt; + } + Value const* const key = record.field(_description->key); + if (key == nullptr) { + return std::nullopt; + } + if (std::int64_t const* const number = key->asInt()) { + return Key{*number}; + } + if (std::string const* const text = key->asString()) { + return Key{*text}; + } + return std::nullopt; +} + +bool ModelGridSource::rowModified(Key const& key) const { + static_cast(_version.get()); + return _edits->rowEdited(key); +} + +std::optional ModelGridSource::refusal(Key const& key, std::string_view column) const { + CellFacts const facts = factsOf(key, column); + if (facts.unloaded) { + return std::string{kUnloadedText}; + } + if (facts.foreignUnit) { + return std::string{kForeignUnitText}; + } + if (facts.busy) { + return std::string{kBusyText}; + } + if (facts.locked) { + std::optional const row = locate(key); + if (row && _description) { + return lockText(TableRowRef{.key = key, .row = row->record}, *_description); + } + } + return std::nullopt; +} + +void ModelGridSource::focusRow(std::optional const& key) { + if (_mode != EditMode::Row) { + return; + } + std::vector leaving; + for (auto const& [row, cells] : _held) { + if (!key || row != *key) { + leaving.push_back(row); + } + } + for (Key const& row : leaving) { + send(row); + } +} + +void ModelGridSource::commitHeld() { + std::vector rows; + rows.reserve(_held.size()); + for (auto const& [row, cells] : _held) { + rows.push_back(row); + } + for (Key const& row : rows) { + send(row); + } +} + +bool ModelGridSource::resends(Key const& key, std::string_view column) const { + return std::ranges::any_of(_resend, [&](CellRef const& cell) { return cell.key == key && cell.column == column; }); +} + +void ModelGridSource::Rows::changed(table::ViewChange const& change) { + for (std::size_t const index : broughtRows(change)) { + if (std::optional const row = _inner->row(static_cast(index))) { + _source->_edits->rowFetched(row->key); + } + } + ++_source->_rowsVersion; + _source->bump(); + // Last: the mount's handler may end the mount that owns this source. + if (_handler) { + std::function const handler = _handler; + handler(change); + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): walks the change's operations once, shifting the collected indices as each insert or removal passes; the shift depends on the operation kind +std::vector ModelGridSource::broughtRows(table::ViewChange const& change) { + std::vector out; + for (table::ViewOp const& op : change.ops) { + switch (op.kind) { + case table::ViewOp::Kind::Reset: + out.clear(); + break; + case table::ViewOp::Kind::Removed: + std::erase_if(out, + [&op](std::size_t index) { return index >= op.first && index < op.first + op.count; }); + for (std::size_t& index : out) { + index -= index >= op.first + op.count ? op.count : 0; + } + break; + case table::ViewOp::Kind::Inserted: + for (std::size_t& index : out) { + index += index >= op.first ? op.count : 0; + } + for (std::size_t at = op.first; at < op.first + op.count; ++at) { + out.push_back(at); + } + break; + case table::ViewOp::Kind::Changed: + for (std::size_t at = op.first; at < op.first + op.count; ++at) { + if (!std::ranges::contains(out, at)) { + out.push_back(at); + } + } + break; + case table::ViewOp::Kind::Moved: + for (std::size_t& index : out) { + if (index == op.first) { + index = op.to; + continue; + } + std::size_t const removed = index > op.first ? index - 1 : index; + index = removed >= op.to ? removed + 1 : removed; + } + break; + default: + break; + } + } + return out; +} + +ModelColumn const* ModelGridSource::columnOf(std::string_view columnId) const { + auto const found = std::ranges::find(_columns, columnId, &ModelColumn::id); + return found == _columns.end() ? nullptr : &*found; +} + +table::TableColumn const* ModelGridSource::describedColumn(std::string_view columnId) const { + if (!_description) { + return nullptr; + } + auto const found = std::ranges::find_if( + _description->columns, [columnId](table::TableColumn const& column) { return column.info.id == columnId; }); + return found == _description->columns.end() ? nullptr : &*found; +} + +ModelGridSource::Session const* ModelGridSource::sessionOf(std::string_view column) const { + auto const found = _sessions.find(column); + return found == _sessions.end() ? nullptr : &found->second; +} + +forms::FieldState* ModelGridSource::fieldOf(std::string_view column) const { + Session const* const session = sessionOf(column); + ModelColumn const* const described = columnOf(column); + return session == nullptr || described == nullptr ? nullptr : &session->form->field(described->path); +} + +std::optional ModelGridSource::locate(Key const& key) const { + static_cast(_version.get()); + std::optional const index = positionOf(key); + if (!index) { + return std::nullopt; + } + std::optional const row = _rows->row(static_cast(*index)); + if (!row || row->key != key) { + return std::nullopt; + } + return Located{.index = static_cast(*index), .record = row->row}; +} + +CellFacts ModelGridSource::factsOf(Key const& key, std::string_view column) const { + static_cast(_version.get()); + ModelColumn const* const described = columnOf(column); + CellFacts facts; + facts.field = fieldOf(column); + facts.hasEdit = + described != nullptr && described->edit && (!_context.may || _context.may(described->edit->action)); + std::optional const row = locate(key); + if (!row) { + facts.unloaded = true; + return facts; + } + if (described != nullptr && described->edit && !described->edit->readonly.empty()) { + Value const* const companion = row->record.field(described->edit->readonly); + bool const* const frozen = companion == nullptr ? nullptr : companion->asBool(); + facts.companionReadOnly = frozen != nullptr && *frozen; + } + facts.busy = _rows->states().isBusy(key); + facts.locked = _description && lockText(TableRowRef{.key = key, .row = row->record}, *_description).has_value(); + table::TableColumn const* const shown = describedColumn(column); + table::UnloadedLevels const levels = _rows->unloadedLevels(row->index); + Value const* const value = row->record.field(column); + facts.unloaded = value == nullptr || (shown != nullptr && !shown->info.level.empty() && + std::ranges::contains(levels.levels, shown->info.level)); + if (Quantity const* const measure = value == nullptr ? nullptr : value->asQuantity(); + measure != nullptr && facts.field != nullptr && facts.field->spec().kind == forms::FieldKind::Quantity) { + facts.foreignUnit = !inFieldUnit(*measure, facts.field->spec()); + } + return facts; +} + +ModelGridSource::Session* ModelGridSource::loaded(Key const& key, std::string_view column) { + auto const found = _sessions.find(column); + ModelColumn const* const described = columnOf(column); + if (found == _sessions.end() || described == nullptr) { + return nullptr; + } + Session& session = found->second; + if (session.loadedFor == key) { + return &session; + } + _rt->untracked([&] { + std::optional const row = locate(key); + Value const* const value = row ? row->record.field(column) : nullptr; + std::string const json = value == nullptr ? std::string{"null"} : wireOf(*value, fieldOf(column)->spec()); + std::string const body = described->edit->member.empty() + ? R"({"value":)" + json + "}" + : R"({"values":{")" + described->edit->member + R"(":)" + json + "}}"; + _rt->batch([&] { + session.form->prefill(body); + forms::FieldState& field = *fieldOf(column); + session.base = field.draft(); + if (std::optional held = _edits->draft(key, column)) { + field.text().set(std::move(*held)); + } + }); + }); + session.loadedFor = key; + return &session; +} + +void ModelGridSource::hold(Key const& key, std::string_view column) { + Session const* const session = sessionOf(column); + forms::FieldState const* const field = fieldOf(column); + if (session == nullptr || field == nullptr) { + return; + } + _rt->untracked([&] { + std::string const text = field->draft(); + if (text == session->base && !_edits->stale(key, column) && !_edits->modified(key, column)) { + _edits->clearDraft(key, column); + return; + } + std::optional const& failed = field->error().get(); + _edits->setDraft(key, column, text, failed ? std::optional{failed->message} : std::nullopt); + }); + bump(); +} + +std::optional ModelGridSource::encode(Key const& key, std::string const& column) { + if (loaded(key, column) == nullptr) { + return std::nullopt; + } + std::erase_if(_resend, [&](CellRef const& cell) { return cell.key == key && cell.column == column; }); + hold(key, column); + auto const draft = _edits->draft(key, column); + if (!draft || _edits->error(key, column)) { + return std::nullopt; + } + if (_rt->untracked([&] { return readOnly(key, column); })) { + // Refused at the cell, as a held cell is: the draft keeps why, and its next commit sends it. + std::optional const why = _rt->untracked([&] { return refusal(key, column); }); + _edits->setDraft(key, column, *draft, why.value_or(std::string{kReadOnlyText})); + _resend.push_back(CellRef{.key = key, .column = column}); + return std::nullopt; + } + forms::Encoding const encoding = _rt->untracked([&] { return fieldOf(column)->encoded().get(); }); + ModelColumn const* const described = columnOf(column); + std::string member = described != nullptr && described->edit && !described->edit->member.empty() + ? described->edit->member + : std::string{"value"}; + return table::EditCell{.column = column, + .json = encoding && encoding->has_value() ? (*encoding)->json : std::string{"null"}, + .member = std::move(member)}; +} + +void ModelGridSource::send(Key const& row) { + auto const found = _held.find(row); + if (found == _held.end()) { + return; + } + std::vector cells = std::move(found->second); + _held.erase(found); + std::vector refused; + std::erase_if(cells, [this, &row, &refused](table::EditCell const& cell) { + bool const readOnlyNow = _rt->untracked([&] { return readOnly(row, cell.column); }); + if (readOnlyNow) { + refused.push_back(cell.column); + } + return readOnlyNow; + }); + // Refused at the cell: the draft stays, with why as its error, until a commit of the cell sends it. + for (std::string const& column : refused) { + std::optional const why = _rt->untracked([&] { return refusal(row, column); }); + _edits->setDraft(row, column, _edits->draft(row, column).value_or(std::string{}), + why.value_or(std::string{kReadOnlyText})); + CellRef cell{.key = row, .column = column}; + if (!std::ranges::contains(_resend, cell)) { + _resend.push_back(std::move(cell)); + } + } + if (!cells.empty()) { + _edits->commitRow(table::RowEditRequest{.row = row, .cells = std::move(cells)}); + } + bump(); +} + +void ModelGridSource::rowSettled(table::RowId const& row, bool refused) { + bump(); + if (_mode != EditMode::Row || !refused || !_refocus) { + return; + } + for (std::string const& column : _layout) { + if (_edits->error(row, column)) { + std::function const refocus = _refocus; + refocus(CellRef{.key = row, .column = column}); + return; + } + } +} + +std::string ModelGridSource::wireOf(Value const& value, forms::FieldSpec const& spec) const { + forms::FieldKind const kind = spec.kind; + if (Quantity const* const measure = value.asQuantity(); measure != nullptr && kind == forms::FieldKind::Quantity) { + std::optional const amount = inFieldUnit(*measure, spec); + return amount ? glz::write_json(valueToJson(Value{Decimal{*amount}})).value_or("null") : std::string{"null"}; + } + if (kind == forms::FieldKind::EpochDate) { + std::string const* const text = value.asString(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `text->size() == 10` is the previous operand of this condition, so indices 4 and 7 are in range + if (text != nullptr && text->size() == 10 && (*text)[4] == '-' && (*text)[7] == '-') { + unsigned year = 0; + unsigned month = 0; + unsigned day = 0; + // Each part is all digits: a part read only in its leading digits ("20xx") is not a date. + auto const whole = [](char const* first, char const* last, unsigned& out) { + auto const [end, error] = std::from_chars(first, last, out); + return error == std::errc{} && end == last; + }; + char const* const cursor = text->data(); + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic): from_chars takes a pointer range; the ranges are fixed offsets into the 10-character `YYYY-MM-DD` text the size and separator checks above validated + bool const read = whole(cursor, cursor + 4, year) && whole(cursor + 5, cursor + 7, month) && + whole(cursor + 8, cursor + 10, day); + // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic) + std::chrono::year_month_day const date{std::chrono::year{static_cast(year)}, + std::chrono::month{month}, std::chrono::day{day}}; + if (read && date.ok()) { + return std::to_string(std::chrono::sys_days{date}.time_since_epoch().count()); + } + } + } + if (kind == forms::FieldKind::EpochDateTime) { + if (time::DateTime const* const instant = value.asTimestamp()) { + return std::to_string( + std::chrono::duration_cast(instant->value.time_since_epoch()).count()); + } + } + return glz::write_json(valueToJson(value)).value_or("null"); +} + +std::optional ModelGridSource::inFieldUnit(Quantity const& measure, + forms::FieldSpec const& spec) const { + std::optional const from = _units ? _units->find(measure.unit) : std::nullopt; + std::optional const toUnit = _units ? _units->find(spec.unitAscii) : std::nullopt; + if (!from || !toUnit || _units->info(*from).dimension != _units->info(*toUnit).dimension) { + return std::nullopt; + } + auto const factor = math::checkedDiv(_units->info(*from).toBase, _units->info(*toUnit).toBase); + auto const amount = factor ? math::checkedMul(measure.value, *factor) : std::unexpected(factor.error()); + return amount ? std::optional{*amount} : std::nullopt; +} + +table::Cell ModelGridSource::cellOf(Value const* value) { + if (value == nullptr || value->isNull()) { + return std::monostate{}; + } + if (std::int64_t const* const integer = value->asInt()) { + return *integer; + } + if (Decimal const* const decimal = value->asDecimal()) { + return decimal->value; + } + if (bool const* const flag = value->asBool()) { + return *flag; + } + if (Quantity const* const quantity = value->asQuantity()) { + return quantity->value; + } + if (std::string const* const text = value->asString()) { + return *text; + } + return std::monostate{}; +} + +GridController::GridController(reactive::Runtime& runtime, GridSource& source, GridOptions options) + : _rt{&runtime}, + _source{&source}, + _options{std::move(options)}, + _place{runtime, std::optional{}}, + _editing{runtime, std::optional{}}, + _message{runtime, std::string{}}, + _notices{runtime, std::uint64_t{0}}, + _messageEntries{runtime, std::vector{}}, + _standing{runtime, std::string{}}, + _standingEntries{runtime, std::vector{}}, + _selection{runtime, std::optional{}} { + _source->refocusWith([this](CellRef const& cell) { + if (_hasFocus) { + focusCell(cell); + } + }); + _source->followFocusWith( + FocusLink{.moved = [this](Key const& from, Key const& target) { keyMoved(from, target); }}); +} + +GridController::~GridController() { + _source->refocusWith({}); + _source->followFocusWith({}); +} + +std::optional GridController::focus() const { + std::optional const shown = place(); + if (!shown || !shown->key) { + return std::nullopt; + } + return CellRef{.key = *shown->key, .column = shown->column}; +} + +std::optional GridController::place() const { + std::optional shown = _place.get(); + if (shown && !shown->key) { + // Tracked: a binding over the place runs again when the row arrives, and names its key. + shown->key = _source->keyAt(shown->viewRow); + } + return shown; +} + +void GridController::focusPlace(GridFocus target) { + _hasFocus = true; + if (target.key) { + focusCell(CellRef{.key = *target.key, .column = target.column}); + return; + } + commit(); + letGo(); + setPlace(std::move(target)); + setSelection(std::nullopt); + clearNotice(); +} + +void GridController::focusCell(CellRef cell) { + _hasFocus = true; + if (_source->covered(cell.key, cell.column)) { + return; + } + if (std::optional const open = _editing.peek(); open && *open != cell) { + commit(); + letGo(); + } + std::optional const position = _source->positionOf(cell.key); + if (!position) { + return; + } + setPlace(GridFocus{.key = cell.key, .viewRow = *position, .column = cell.column}); + if (_selection.peek() && !inBlock(cell)) { + setSelection(std::nullopt); + } + clearNotice(); +} + +void GridController::activate(CellRef cell) { + focusCell(cell); + if (_rt->untracked([&] { return _source->readOnly(cell.key, cell.column); })) { + if (_options.onActivate) { + _options.onActivate(cell.key); + } + return; + } + // A Boolean opens no editor: a click or `Space` flips it, and the second click of a double click, which + // activates, flips nothing more. + if (_source->toggles(cell.key, cell.column)) { + return; + } + _kept = _source->draft(cell.key, cell.column); + _source->holdRow(cell.key); + _editing.set(cell); + _source->editorOpened(cell.key, cell.column); +} + +std::vector GridController::keyChords() const { + if (_editing.get()) { + return {"Enter", "Tab", "Shift+Tab", "Escape", "Ctrl+Enter"}; + } + if (!_source->selectsCells()) { + return {"Tab", "Shift+Tab", "Enter", "F2", "Space", + "Delete", "Escape", "Ctrl+Enter", "Ctrl+Shift+=", "Ctrl+-"}; + } + return {"Tab", "Shift+Tab", "Enter", "F2", "Space", "Delete", + "Escape", "Ctrl+Enter", "Shift+Up", "Shift+Down", "Shift+Left", "Shift+Right", + "Ctrl+A", "Ctrl+V", "Ctrl+D", "Ctrl+Shift+=", "Ctrl+-"}; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): dispatches one chord across the focus, editing, selection and clipboard states; each branch checks the state the one before left +KeyOutcome GridController::press(std::string_view chord) { + // The row an editor was open on is let go once the key is handled: the walk moves by view position at the + // moment of the commit, so the edited row stays where it was while focus moves on. + struct LetGo { + GridController* grid; + explicit LetGo(GridController* held) : grid{held} {} + LetGo(LetGo const&) = delete; + LetGo& operator=(LetGo const&) = delete; + LetGo(LetGo&&) = delete; + LetGo& operator=(LetGo&&) = delete; + ~LetGo() { grid->letGo(); } + } const letting{this}; + _hasFocus = true; + std::optional const open = _editing.peek(); + if (chord == "Tab" || chord == "Shift+Tab") { + commit(); + return walkFrom(chord == "Tab"); + } + if (chord == "Escape") { + if (open) { + _source->write(open->key, open->column, _kept); + _editing.set(std::nullopt); + } + return KeyOutcome::Handled; + } + if (chord == "Ctrl+Enter") { + commit(); + _source->commitHeld(); + return KeyOutcome::Handled; + } + if (chord == "Enter" && open) { + commit(); + enterMove(*open); + return KeyOutcome::Handled; + } + std::optional const focused = _rt->untracked([&] { return focus(); }); + if (chord == "Enter" || chord == "F2") { + if (focused) { + activate(*focused); + } + return KeyOutcome::Handled; + } + if (chord == "Space") { + if (focused && _source->toggles(focused->key, focused->column)) { + toggle(*focused); + } + return KeyOutcome::Handled; + } + if (chord == "Delete") { + clear(); + return KeyOutcome::Handled; + } + if (chord == "Shift+Up" || chord == "Shift+Down" || chord == "Shift+Left" || chord == "Shift+Right") { + int rows = 0; + int columns = 0; + if (chord == "Shift+Up") { + rows = -1; + } else if (chord == "Shift+Down") { + rows = 1; + } else if (chord == "Shift+Left") { + columns = -1; + } else { + columns = 1; + } + extend(rows, columns); + return KeyOutcome::Handled; + } + if (chord == "Ctrl+A") { + selectAll(); + return KeyOutcome::Handled; + } + if (chord == "Ctrl+V") { + if (_readClipboard) { + if (std::optional const text = _readClipboard()) { + static_cast(paste(*text)); + } + } + return KeyOutcome::Handled; + } + if (chord == "Ctrl+D") { + fillDown(); + return KeyOutcome::Handled; + } + if (chord == "Ctrl+Shift+=") { + insertRow(true); + return KeyOutcome::Handled; + } + if (chord == "Ctrl+-") { + deleteRows(); + return KeyOutcome::Handled; + } + return KeyOutcome::Ignored; +} + +void GridController::type(std::string_view text) { + _hasFocus = true; + if (std::optional const open = _editing.peek()) { + _source->write(open->key, open->column, std::string{text}); + return; + } + std::optional const focused = _rt->untracked([&] { return focus(); }); + if (!focused || _source->covered(focused->key, focused->column)) { + return; + } + if (_rt->untracked([&] { return _source->readOnly(focused->key, focused->column); })) { + notice(_rt->untracked([&] { return _source->refusal(focused->key, focused->column); }) + .value_or(std::string{kReadOnlyText})); + return; + } + if (_source->toggles(focused->key, focused->column)) { + return; + } + _kept = _source->draft(focused->key, focused->column); + _source->holdRow(focused->key); + _source->write(focused->key, focused->column, std::string{text}); + _editing.set(focused); + _source->editorOpened(focused->key, focused->column); +} + +void GridController::leave() { + commit(); + letGo(); + _hasFocus = false; + _focusedRow.reset(); + _source->focusRow(std::nullopt); +} + +std::string GridController::message() const { + if (std::string const& notice = _message.get(); !notice.empty()) { + return notice; + } + std::optional const focused = focus(); + return focused ? _source->error(focused->key, focused->column).value_or(std::string{}) : std::string{}; +} + +void GridController::click(CellRef const& cell) { + focusCell(cell); + if (_rt->untracked([&] { return focus(); }) == cell && _source->toggles(cell.key, cell.column)) { + toggle(cell); + } +} + +std::string GridController::standing() const { + if (_source->deriveFailed()) { + return std::string{kDeriveFailedText}; + } + return _standing.get(); +} + +std::vector GridController::standingEntries() const { + if (_source->deriveFailed()) { + return {StatusEntry{.id = "recalculate", .label = "Recalculate"}}; + } + return _standingEntries.get(); +} + +void GridController::chooseEntry(std::string_view entryId) { + if (entryId == "recalculate") { + _source->recalculate(); + } else if (entryId == "undo") { + undo(); + } +} + +std::vector GridController::cellEntries(Key const& row, std::string_view column) { + GridController* const self = this; + GridSource* const source = _source; + std::string const columnId{column}; + MenuItem cell; + cell.label = std::string{"Revert cell"}; + cell.enabled = Prop{[source, row, columnId] { return source->marks(row, columnId).modified; }}; + cell.onSelect = [self, source, row, columnId] { + self->noteChange(); + source->revertCell(row, columnId); + source->committed(); + }; + MenuItem whole; + whole.label = std::string{"Revert row"}; + whole.enabled = Prop{[source, row] { return source->rowModified(row); }}; + whole.onSelect = [self, source, row] { + self->noteChange(); + source->revertRow(row); + source->committed(); + }; + std::vector entries; + entries.push_back(std::move(cell)); + entries.push_back(std::move(whole)); + std::vector rows = rowEntries(row); + if (!rows.empty()) { + MenuItem separator; + separator.separator = true; + entries.push_back(std::move(separator)); + std::ranges::move(rows, std::back_inserter(entries)); + } + return entries; +} + +std::vector GridController::rowEntries(Key const& row) { + if (fixedRows()) { + return {}; + } + GridController* const self = this; + std::vector doomed = _rt->untracked([&] { return selectedRows(); }); + if (doomed.size() < 2 || !std::ranges::contains(doomed, row)) { + doomed = {row}; + } + std::size_t const count = doomed.size(); + auto const insertEntry = [self, row](std::string label, bool below) { + MenuItem item; + item.label = std::move(label); + item.enabled = Prop{[self] { return self->rowOps().insert; }}; + item.description = Prop{[self] { return self->insertRefusal(); }}; + item.onSelect = [self, row, below] { self->insertAt(row, below); }; + return item; + }; + MenuItem removal; + removal.label = std::string{count > 1 ? "Delete rows" : "Delete row"}; + removal.enabled = Prop{[self, count] { return self->removeRefusal(count).empty(); }}; + removal.description = Prop{[self, count] { return self->removeRefusal(count); }}; + removal.onSelect = [self, doomed = std::move(doomed)] { self->removeKeys(doomed); }; + std::vector entries; + entries.push_back(insertEntry("Insert row above", false)); + entries.push_back(insertEntry("Insert row below", true)); + entries.push_back(std::move(removal)); + return entries; +} + +void GridController::copySummaries(std::shared_ptr rows, + std::function text) { + _summaries = std::move(rows); + _summaryText = std::move(text); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): builds the clipboard text for the selection or the focus in one walk over the rows and the columns in layout order +std::string GridController::copy() const { + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the untracked body of `copy`: its row and column walk shares the running text, so it is one lambda + return _rt->untracked([&] { + std::optional const cells = block(); + if (!cells) { + return std::string{}; + } + std::vector>> rows; + if (_summaries != nullptr && _summaryText && !cells->keys.empty()) { + std::optional const first = _source->positionOf(cells->keys.front()); + std::optional const last = _source->positionOf(cells->keys.back()); + std::optional const from = + first ? _summaries->mounted(static_cast(*first)) : std::nullopt; + std::optional const target = + last ? _summaries->mounted(static_cast(*last)) : std::nullopt; + if (from && target) { + // The rectangle's rows as the table draws them: a summary row between its corners is copied with + // its cells' text, a heading row is not a row of cells. + for (std::int64_t at = *from; at <= *target; ++at) { + std::optional const ref = _summaries->row(at); + if (!ref) { + continue; + } + std::vector> line; + if (_summaries->summary(at)) { + for (std::string const& column : cells->columns) { + line.emplace_back(_summaryText(ref->row, column)); + } + } else if (_source->positionOf(ref->key)) { + for (std::string const& column : cells->columns) { + line.emplace_back(_source->text(ref->key, column)); + } + } else { + continue; + } + rows.push_back(std::move(line)); + } + return copyText({}, rows).text; + } + } + for (Key const& key : cells->keys) { + std::vector> line; + for (std::string const& column : cells->columns) { + line.emplace_back(_source->text(key, column)); + } + rows.push_back(std::move(line)); + } + return copyText({}, rows).text; + }); +} + +std::optional GridController::copyRefusal(std::string_view separator) const { + std::optional const cells = _rt->untracked([&] { return block(); }); + if (cells && cells->keys.size() > _options.maxCopyRows) { + return tableText::copyBound(_options.maxCopyRows, separator); + } + return std::nullopt; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): parses the block, writes each value and counts the written and the dropped in one pass; both tallies depend on each cell's outcome +PasteResult GridController::paste(std::string_view text) { + commit(); + letGo(); + if (!_source->selectsCells()) { + return {}; + } + std::vector> const lines = pasteLines(text); + std::size_t values = 0; + for (std::vector const& line : lines) { + values += line.size(); + } + if (values > _options.maxPasteCells) { + notice("A paste holds at most " + groupedCount(static_cast(_options.maxPasteCells)) + " values"); + return {}; + } + PasteResult result; + std::vector const columns = _source->columns(); + std::size_t const rows = _source->rowCount(); + std::size_t firstRow = 0; + std::size_t firstColumn = 0; + // The focused cell, else the selection's top left corner. + std::optional start = _rt->untracked([&] { return focus(); }); + if (!start) { + if (std::optional const cells = _rt->untracked([&] { return block(); }); + cells && !cells->keys.empty() && !cells->columns.empty()) { + start = CellRef{.key = cells->keys.front(), .column = cells->columns.front()}; + } + } + if (start) { + firstRow = _source->positionOf(start->key).value_or(0); + auto const found = std::ranges::find(columns, start->column); + firstColumn = found == columns.end() ? 0 : static_cast(found - columns.begin()); + } + // The keys each line lands on: the rows there, then the rows appended for the lines past the last. + std::vector> keys; + bool appended = false; + for (std::size_t line = 0; line < lines.size(); ++line) { + std::size_t const viewRow = firstRow + line; + if (viewRow < rows) { + keys.push_back(_source->keyAt(viewRow)); + continue; + } + std::optional added; + if (_options.appendRows && !fixedRows() && _rt->untracked([&] { return insertRefusal(); }).empty()) { + added = _source->appendRow(); + } + appended = appended || added.has_value(); + keys.push_back(std::move(added)); + } + _rt->batch([&] { + for (std::size_t line = 0; line < lines.size(); ++line) { + std::vector const& cells = lines.at(line); + if (!keys.at(line)) { + result.pastRows += cells.size(); + continue; + } + for (std::size_t at = 0; at < cells.size(); ++at) { + std::size_t const column = firstColumn + at; + if (column >= columns.size()) { + ++result.pastColumns; + continue; + } + CellRef const cell{.key = *keys.at(line), .column = columns.at(column)}; + if (!editable(cell)) { + ++result.readOnly; + continue; + } + _source->write(cell.key, cell.column, cells.at(at)); + ++result.written; + } + } + }); + if (result.written > 0 || appended) { + noteChange(); + _source->committed(); + } + notice(pasteMessage(result)); + return result; +} + +void GridController::fillDown() { + commit(); + letGo(); + if (!_source->selectsCells()) { + return; + } + std::optional const cells = _rt->untracked([&] { return block(); }); + if (!cells || cells->keys.size() < 2) { + return; + } + bool changed = false; + _rt->batch([&] { + for (std::string const& column : cells->columns) { + std::string const first = _source->draft(cells->keys.front(), column); + for (std::size_t row = 1; row < cells->keys.size(); ++row) { + CellRef const cell{.key = cells->keys.at(row), .column = column}; + if (editable(cell) && _source->draft(cell.key, column) != first) { + _source->write(cell.key, column, first); + changed = true; + } + } + } + }); + if (changed) { + noteChange(); + _source->committed(); + } +} + +void GridController::clear() { + commit(); + letGo(); + std::optional const cells = _rt->untracked([&] { return block(); }); + if (!cells) { + return; + } + bool changed = false; + _rt->batch([&] { + for (Key const& key : cells->keys) { + for (std::string const& column : cells->columns) { + CellRef const cell{.key = key, .column = column}; + if (editable(cell) && !_source->draft(key, column).empty()) { + _source->write(key, column, std::string{}); + changed = true; + } + } + } + }); + if (changed) { + noteChange(); + _source->committed(); + } +} + +void GridController::insertRow(bool below) { + if (std::optional const focused = _rt->untracked([&] { return focus(); })) { + insertAt(focused->key, below); + } +} + +} // namespace morph::ui diff --git a/src/ui/grid_3.cpp b/src/ui/grid_3.cpp new file mode 100644 index 000000000..e173a4659 --- /dev/null +++ b/src/ui/grid_3.cpp @@ -0,0 +1,719 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +void GridController::deleteRows() { + std::vector doomed = _rt->untracked([&] { return selectedRows(); }); + if (doomed.empty()) { + if (std::optional const focused = _rt->untracked([&] { return focus(); })) { + doomed.push_back(focused->key); + } + } + removeKeys(doomed); +} + +void GridController::undo() { + commit(); + letGo(); + if (!_undoOffered) { + return; + } + std::size_t const before = _rt->untracked([&] { return _source->heldRows(); }); + _source->undoRemove(); + clearUndo(); + if (_rt->untracked([&] { return _source->heldRows(); }) != before) { + _source->committed(); + } +} + +RowOps GridController::rowOps() const { + if (fixedRows()) { + return {}; + } + std::string const insert = insertRefusal(); + std::string const remove = removeRefusal(1); + bool const anyRow = _source->heldRows() > 0; + return RowOps{ + .insert = insert.empty(), .remove = remove.empty() && anyRow, .why = !insert.empty() ? insert : remove}; +} + +void GridController::addRow() { + commit(); + letGo(); + if (fixedRows()) { + return; + } + if (std::optional const key = _source->appendRow()) { + noteChange(); + _source->committed(); + focusFirstEditable(*key); + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one wire per seam of the table. +Node GridController::node(std::vector columns, TableOptions options, std::optional base) { + std::shared_ptr const keep = weak_from_this().lock(); + GridController* const self = this; + GridSource* const source = _source; + auto const ids = std::make_shared>(); + for (TableColumn const& column : columns) { + ids->push_back(column.id); + } + auto const idOf = [ids](std::size_t column) { return column < ids->size() ? ids->at(column) : std::string{}; }; + auto const marksOf = [source](reactive::Signal const* row, std::string const& columnId) { + return Prop{[source, row, columnId] { + std::optional const key = source->keyOf(row->get()); + return key ? source->marks(*key, columnId) : CellMarks{}; + }}; + }; + TableSource made; + if (base && base->cellView) { + made = *base; + made.cellView = [inner = base->cellView, idOf, marksOf](std::size_t column, + reactive::Signal const& row) { + return markedCell(inner(column, row), marksOf(&row, idOf(column))); + }; + } else { + if (base) { + made = *base; + } else { + made.rows = std::shared_ptr(keep, &source->view()); + made.rowView = {}; + made.alwaysFetched = {}; + made.levels = {}; + } + made.cellView = [source, idOf](std::size_t column, reactive::Signal const& row) { + return source->cellView(idOf(column), row); + }; + } + if (source->spanning()) { + // A grid's rows are all on the client: under the threshold every row is realized, and the spans drawn. + made.alwaysWindowed = false; + } + made.rowView = [inner = made.rowView, source, ids](reactive::Signal const& row) { + TableRowLook look = inner ? inner(row) : TableRowLook{}; + reactive::Signal const* const record = &row; + look.modified = Prop{[source, record] { + std::optional const key = source->keyOf(record->get()); + return key.has_value() && source->rowModified(*key); + }}; + if (source->spanning() && !look.spans) { + look.spans = Prop>{[source, record, ids] { + std::vector out; + std::optional const key = source->keyOf(record->get()); + if (!key) { + return out; + } + for (CellSpan const& span : source->spans(*key)) { + auto const found = std::ranges::find(*ids, span.column); + if (found != ids->end()) { + out.push_back(RowSpan{.column = static_cast(found - ids->begin()), + .rows = span.rows, + .columns = span.columns}); + } + } + return out; + }}; + } + return look; + }; + // Over summary rows the mount counts mounted rows and the grid data rows: a focus's view row is mapped + // between the two, and a click, a move or a rectangle's corner that lands on a summary or heading row goes to + // the nearest data row. + auto const summaries = std::dynamic_pointer_cast(made.rows); + options.gridFocus = Prop>{[self, summaries] { + std::optional shown = self->place(); + if (shown && summaries != nullptr) { + if (std::optional const mounted = + summaries->mounted(static_cast(shown->viewRow))) { + shown->viewRow = static_cast(*mounted); + } + } + return shown; + }}; + auto const toData = [source, summaries](Key const& key) -> std::optional { + if (summaries == nullptr || source->positionOf(key)) { + return key; + } + std::int64_t const count = summaries->mountedTotal().rows; + for (std::int64_t at = 0; at < count; ++at) { + std::optional const ref = summaries->row(at); + if (ref && ref->key == key) { + std::optional const data = summaries->data(at); + return data ? source->keyAt(static_cast(*data)) : std::nullopt; + } + } + return std::nullopt; + }; + // The table's `onFocusCell` hears where a click or a move put the grid's focus, as a table's does. + options.onGridFocus = [self, keep, source, summaries, toData, + heard = std::move(options.onFocusCell)](GridFocus target) { + if (summaries != nullptr) { + if (target.key) { + target.key = toData(*target.key); + if (!target.key) { + return; + } + } + std::optional const data = summaries->data(static_cast(target.viewRow)); + target.viewRow = data ? static_cast(*data) : target.viewRow; + if (target.key) { + target.viewRow = source->positionOf(*target.key).value_or(target.viewRow); + } + } + self->focusPlace(std::move(target)); + if (heard) { + heard(self->_rt->untracked([&] { return self->focus(); })); + } + }; + options.onKey = [self](std::string const& chord) { return self->press(chord); }; + options.keyChords = Prop>{[self] { return self->keyChords(); }}; + options.onText = [self](std::string const& text) { self->type(text); }; + options.onActivateCell = [self](CellRef cell) { self->activate(std::move(cell)); }; + options.onClickCell = [self, toData](CellRef cell) { + if (std::optional const key = toData(cell.key)) { + self->click(CellRef{.key = *key, .column = std::move(cell.column)}); + } + }; + options.onFocusOut = [self] { self->leave(); }; + options.editing = Prop>{[self] { return self->editing(); }}; + options.editor = [source](CellRef const& cell) { return source->editor(cell.key, cell.column); }; + // A model's table selects rows: its selection gestures stay the table's own. + if (source->selectsCells()) { + options.cellSelection = Prop>{[self] { return self->selection(); }}; + options.onCellSelect = [self, toData](std::optional range) { + if (range) { + std::optional const anchor = toData(range->anchor.key); + std::optional const focus = toData(range->focus.key); + if (!anchor || !focus) { + return; + } + range->anchor.key = *anchor; + range->focus.key = *focus; + } + self->select(std::move(range)); + }; + } + options.cellMenu = [self, idOf, outer = std::move(options.cellMenu)](Key const& row, std::size_t column) { + std::vector own = self->cellEntries(row, idOf(column)); + if (!outer) { + return own; + } + std::vector items = outer(row, column); + auto const separator = std::ranges::find_if(items, [](MenuItem const& item) { return item.separator; }); + items.insert(separator, std::make_move_iterator(own.begin()), std::make_move_iterator(own.end())); + return items; + }; + if (!options.status.isBound() && options.status.constant() == TableStatus{}) { + options.status = Prop{[self] { + TableStatus status{.message = self->message(), + .entries = self->messageEntries(), + .standing = self->standing(), + .standingEntries = self->standingEntries()}; + status.shown = !status.message.empty() || !status.entries.empty() || !status.standing.empty() || + !status.standingEntries.empty(); + return status; + }}; + if (!options.onStatusEntry) { + options.onStatusEntry = [self](std::string const& entryId) { self->chooseEntry(entryId); }; + } + } + if (!_options.appendRows || fixedRows()) { + return ui::table(std::move(columns), std::move(made), std::move(options)); + } + // "Add row" under the grid, disabled at `maxItems` with the bound as its tooltip. + Button add; + add.label = std::string{"Add row"}; + add.onClick = [self, keep] { self->addRow(); }; + add.common.testId = options.common.testId.empty() ? std::string{} : options.common.testId + "_addRow"; + add.common.enabled = Prop{[self] { return self->rowOps().insert; }}; + add.common.tooltip = Prop{[self] { return self->insertRefusal(); }}; + std::vector under; + under.push_back(ui::button(std::move(add))); + return besideTable(options.common, std::move(under), + [&] { return ui::table(std::move(columns), std::move(made), std::move(options)); }); +} + +std::optional GridController::block() const { + std::optional range = _selection.peek(); + if (!range) { + std::optional const focused = focus(); + if (!focused) { + return std::nullopt; + } + range = CellRange{.anchor = *focused, .focus = *focused}; + } + std::vector const columns = _source->columns(); + std::optional const anchorRow = _source->positionOf(range->anchor.key); + std::optional const focusRow = _source->positionOf(range->focus.key); + auto const anchorColumn = std::ranges::find(columns, range->anchor.column); + auto const focusColumn = std::ranges::find(columns, range->focus.column); + if (!anchorRow || !focusRow || anchorColumn == columns.end() || focusColumn == columns.end()) { + return std::nullopt; + } + Block out; + for (std::size_t row = std::min(*anchorRow, *focusRow); row <= std::max(*anchorRow, *focusRow); ++row) { + if (std::optional const key = _source->keyAt(row)) { + out.keys.push_back(*key); + } + } + out.columns.assign(std::min(anchorColumn, focusColumn), std::max(anchorColumn, focusColumn) + 1); + return out; +} + +bool GridController::inBlock(CellRef const& cell) const { + std::optional const cells = _rt->untracked([&] { return block(); }); + return cells && std::ranges::contains(cells->keys, cell.key) && std::ranges::contains(cells->columns, cell.column); +} + +std::vector GridController::selectedRows() const { + if (!_selection.peek()) { + return {}; + } + std::optional const cells = block(); + return cells ? cells->keys : std::vector{}; +} + +void GridController::extend(int rows, int columns) { + if (!_source->selectsCells()) { + return; + } + std::optional const focused = _rt->untracked([&] { return focus(); }); + if (!focused) { + return; + } + CellRange range = _selection.peek().value_or(CellRange{.anchor = *focused, .focus = *focused}); + std::vector const ids = _source->columns(); + std::optional const row = _source->positionOf(range.focus.key); + auto const column = std::ranges::find(ids, range.focus.column); + std::size_t const count = _source->rowCount(); + if (!row || column == ids.end() || count == 0) { + return; + } + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`index`, `delta`, `size`): the lambda is called for the row axis and the column axis, each time with the position, the signed step and the extent in that order + auto const clamp = [](std::size_t index, int delta, std::size_t size) { + auto const moved = static_cast(index) + delta; + return static_cast(std::clamp(moved, 0, static_cast(size) - 1)); + }; + std::optional const key = _source->keyAt(clamp(*row, rows, count)); + if (!key) { + return; + } + range.focus = CellRef{ + .key = *key, .column = ids.at(clamp(static_cast(column - ids.begin()), columns, ids.size()))}; + setSelection(std::move(range)); +} + +void GridController::selectAll() { + if (!_source->selectsCells()) { + return; + } + std::vector const ids = _source->columns(); + std::size_t const count = _source->rowCount(); + if (ids.empty() || count == 0) { + return; + } + std::optional const first = _source->keyAt(0); + std::optional const last = _source->keyAt(count - 1); + if (first && last) { + setSelection(CellRange{.anchor = CellRef{.key = *first, .column = ids.front()}, + .focus = CellRef{.key = *last, .column = ids.back()}}); + } +} + +std::vector> GridController::pasteLines(std::string_view text) { + std::vector lines; + for (std::size_t start = 0;;) { + std::size_t const end = text.find('\n', start); + lines.push_back(text.substr(start, end == std::string_view::npos ? std::string_view::npos : end - start)); + if (end == std::string_view::npos) { + break; + } + start = end + 1; + } + for (std::string_view& line : lines) { + if (line.ends_with('\r')) { + line.remove_suffix(1); + } + } + if (!lines.empty() && lines.back().empty()) { + lines.pop_back(); + } + std::vector> out; + for (std::string_view const line : lines) { + std::vector values; + for (std::size_t start = 0;;) { + std::size_t const end = line.find('\t', start); + std::string_view value = + line.substr(start, end == std::string_view::npos ? std::string_view::npos : end - start); + value.remove_prefix(std::min(value.find_first_not_of(' '), value.size())); + std::size_t const last = value.find_last_not_of(' '); + value = last == std::string_view::npos ? std::string_view{} : value.substr(0, last + 1); + values.emplace_back(value); + if (end == std::string_view::npos) { + break; + } + start = end + 1; + } + out.push_back(std::move(values)); + } + return out; +} + +std::string GridController::insertRefusal() const { + std::optional const most = _source->bounds().second; + if (most && _source->heldRows() >= *most) { + return "A grid holds at most " + std::to_string(*most) + " rows"; + } + return {}; +} + +std::string GridController::removeRefusal(std::size_t count) const { + std::size_t const fewest = _source->bounds().first; + if (_source->heldRows() < count + fewest) { + return "A grid holds at least " + std::to_string(fewest) + " rows"; + } + return {}; +} + +void GridController::insertAt(Key const& row, bool below) { + commit(); + letGo(); + if (fixedRows() || !_rt->untracked([&] { return insertRefusal(); }).empty()) { + return; + } + std::optional const position = _source->positionOf(row); + if (!position) { + return; + } + if (_source->insertRow(below ? *position + 1 : *position)) { + noteChange(); + _source->committed(); + } +} + +void GridController::removeKeys(std::vector const& keys) { + commit(); + letGo(); + if (fixedRows() || keys.empty() || !_rt->untracked([&] { return removeRefusal(keys.size()); }).empty()) { + return; + } + std::optional const shown = _rt->untracked([&] { return place(); }); + std::optional const position = shown && shown->key ? _source->positionOf(*shown->key) : std::nullopt; + noteChange(); + bool const held = _source->removeRows(keys); + _source->committed(); + if (std::optional const range = _selection.peek(); + range && (!_source->positionOf(range->anchor.key) || !_source->positionOf(range->focus.key))) { + setSelection(std::nullopt); + } + if (shown && shown->key && !_source->positionOf(*shown->key)) { + std::size_t const rows = _source->rowCount(); + std::optional const next = + rows == 0 ? std::nullopt : _source->keyAt(std::min(position.value_or(0), rows - 1)); + if (next) { + focusCell(CellRef{.key = *next, .column = shown->column}); + } else { + setPlace(std::nullopt); + } + } + if (held) { + std::size_t const count = keys.size(); + notice("Deleted " + std::to_string(count) + (count == 1 ? " row" : " rows"), + {StatusEntry{.id = "undo", .label = "Undo"}}); + _undoOffered = true; + if (_options.scheduler != nullptr) { + _undoTimer = _options.scheduler->after(_options.undoHold, [this] { clearUndo(); }); + } + } +} + +void GridController::focusFirstEditable(Key const& key) { + for (std::string const& column : _source->columns()) { + if (editable(CellRef{.key = key, .column = column})) { + focusCell(CellRef{.key = key, .column = column}); + return; + } + } +} + +void GridController::setSelection(std::optional range) { + if (_selection.peek() == range) { + return; + } + _selection.set(std::move(range)); + if (_selectionObserver) { + std::function const&)> const observer = _selectionObserver; + observer(_selection.peek()); + } +} + +void GridController::notice(std::string text, std::vector entries) { + if (entries.empty() && _undoOffered) { + entries.push_back(StatusEntry{.id = "undo", .label = "Undo"}); + } + _message.set(std::move(text)); + _messageEntries.set(std::move(entries)); + _notices.set(_notices.peek() + 1); +} + +void GridController::clearNotice() { + if (_messageEntries.peek().empty()) { + _message.set({}); + } +} + +void GridController::clearUndo() { + _undoOffered = false; + _undoTimer.cancel(); + if (!_messageEntries.peek().empty()) { + _messageEntries.set({}); + _message.set({}); + } +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`from`, `target`): the old key first, which the one call site (the source's move callback) spells out +void GridController::keyMoved(Key const& from, Key const& target) { + if (std::optional const open = _editing.peek(); open && open->key == from) { + _editing.set(CellRef{.key = target, .column = open->column}); + } + std::optional const shown = _place.peek(); + if (!shown || shown->key != from) { + return; + } + _focusedRow = target; + _place.set(GridFocus{ + .key = target, .viewRow = _source->positionOf(target).value_or(shown->viewRow), .column = shown->column}); +} + +void GridController::setPlace(std::optional place) { + std::optional const row = place ? place->key : std::nullopt; + _place.set(std::move(place)); + if (row != _focusedRow) { + _focusedRow = row; + _source->focusRow(row); + } +} + +void GridController::letGo() { + if (!_editing.peek()) { + _source->holdRow(std::nullopt); + } +} + +bool GridController::editable(CellRef const& cell) const { + return _rt->untracked( + [&] { return !_source->readOnly(cell.key, cell.column) && !_source->covered(cell.key, cell.column); }); +} + +void GridController::commit() { + std::optional const open = _editing.peek(); + if (!open) { + return; + } + bool const changed = _source->draft(open->key, open->column) != _kept || _source->resends(open->key, open->column); + _editing.set(std::nullopt); + if (changed) { + noteChange(); + _source->committed(); + } +} + +void GridController::toggle(CellRef const& cell) { + if (!editable(cell)) { + return; + } + std::string const now = _source->draft(cell.key, cell.column); + _source->write(cell.key, cell.column, + forms::detail::engine::trim(now) == "true" ? std::string{"false"} : std::string{"true"}); + noteChange(); + _source->committed(); +} + +GridController::Step GridController::next(std::optional const& from, bool forward) const { + std::vector const columns = _source->columns(); + std::size_t const rows = _source->rowCount(); + if (columns.empty() || rows == 0) { + return {}; + } + std::size_t const width = columns.size(); + std::size_t const total = rows * width; + bool const byRows = _options.walk == Walk::Rows; + auto const linear = [&](std::size_t row, std::size_t column) { + return byRows ? (row * width) + column : (column * rows) + row; + }; + std::int64_t position = forward ? -1 : static_cast(total); + if (from) { + std::optional const row = _source->positionOf(from->key); + auto const column = std::ranges::find(columns, from->column); + if (row && column != columns.end()) { + position = static_cast(linear(*row, static_cast(column - columns.begin()))); + } + } + for (position += forward ? 1 : -1; position >= 0 && std::cmp_less(position, total); position += forward ? 1 : -1) { + auto const index = static_cast(position); + std::size_t const row = byRows ? index / width : index % rows; + std::size_t const column = byRows ? index % width : index / rows; + std::optional const key = _source->keyAt(row); + if (!key) { + return Step{.kind = Step::Kind::Stop, .row = row, .column = columns.at(column), .key = std::nullopt}; + } + if (editable(CellRef{.key = *key, .column = columns.at(column)})) { + return Step{.kind = Step::Kind::Found, .row = row, .column = columns.at(column), .key = key}; + } + } + return {}; +} + +void GridController::land(Step const& step) { + if (step.kind == Step::Kind::Found) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): a `Found` step is built only with its key set (see `Step`), so the optional holds a value here + focusCell(CellRef{.key = *step.key, .column = step.column}); + } else if (step.kind == Step::Kind::Stop) { + setPlace(GridFocus{.key = std::nullopt, .viewRow = step.row, .column = step.column}); + _message.set({}); + } +} + +KeyOutcome GridController::walkFrom(bool forward) { + std::optional const shown = _rt->untracked([&] { return place(); }); + if (shown && !shown->key) { + return KeyOutcome::Handled; + } + std::optional const from = + shown ? std::optional{CellRef{.key = *shown->key, .column = shown->column}} : std::nullopt; + Step const step = next(from, forward); + if (step.kind == Step::Kind::None && forward && from && appendOnWalk()) { + return KeyOutcome::Handled; + } + if (step.kind == Step::Kind::None) { + return forward ? KeyOutcome::FocusNext : KeyOutcome::FocusPrevious; + } + land(step); + return KeyOutcome::Handled; +} + +bool GridController::appendOnWalk() { + if (!_options.appendRows || fixedRows() || !_rt->untracked([&] { return insertRefusal(); }).empty()) { + return false; + } + std::optional const key = _source->appendRow(); + if (!key) { + return false; + } + noteChange(); + _source->committed(); + focusFirstEditable(*key); + return true; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): the three Enter modes each walk a different axis and share the focus and the editable-cell test +void GridController::enterMove(CellRef const& from) { + if (_options.enterMoves == EnterMoves::None) { + return; + } + std::optional const row = _source->positionOf(from.key); + if (!row) { + return; + } + if (_options.enterMoves == EnterMoves::Down) { + std::size_t const rows = _source->rowCount(); + for (std::size_t below = *row + 1; below < rows; ++below) { + std::optional const key = _source->keyAt(below); + if (!key) { + land(Step{.kind = Step::Kind::Stop, .row = below, .column = from.column, .key = std::nullopt}); + return; + } + if (editable(CellRef{.key = *key, .column = from.column})) { + focusCell(CellRef{.key = *key, .column = from.column}); + return; + } + } + // Enter down from the last row adds a row with `appendRows`, focused in the same column when it is + // editable. + if (*row + 1 >= rows && _options.appendRows && !fixedRows() && + _rt->untracked([&] { return insertRefusal(); }).empty()) { + if (std::optional const key = _source->appendRow()) { + noteChange(); + _source->committed(); + if (editable(CellRef{.key = *key, .column = from.column})) { + focusCell(CellRef{.key = *key, .column = from.column}); + } else { + focusFirstEditable(*key); + } + } + } + return; + } + std::vector const columns = _source->columns(); + auto const found = std::ranges::find(columns, from.column); + if (found == columns.end()) { + return; + } + for (auto column = std::next(found); column != columns.end(); ++column) { + if (editable(CellRef{.key = from.key, .column = *column})) { + focusCell(CellRef{.key = from.key, .column = *column}); + return; + } + } +} + +FormGrid makeFormGrid(forms::FormSession& form, forms::FieldState const& array, std::vector columns, + GridOptions options, FormatContext format, TableOptions table, std::vector shown) { + if (shown.empty()) { + for (GridColumn const& column : columns) { + shown.push_back(TableColumn{.id = column.id, .label = column.label}); + } + } + if (shown.size() != columns.size()) { + throw std::invalid_argument{"morph::ui::makeFormGrid: one table column per grid column"}; + } + auto source = std::make_shared(form, array.path(), std::move(columns), std::move(format)); + auto grid = std::make_shared(form.runtime(), *source, std::move(options)); + grid->keepAlive(source); + source->onBeforeSubmit([weak = std::weak_ptr{grid}] { + if (auto const live = weak.lock()) { + live->leave(); + } + }); + Node node = grid->node(std::move(shown), std::move(table)); + return FormGrid{.source = std::move(source), .grid = std::move(grid), .node = std::move(node)}; +} + +} // namespace morph::ui diff --git a/src/ui/interpreter.cpp b/src/ui/interpreter.cpp index 154e9eede..d66b01d82 100644 --- a/src/ui/interpreter.cpp +++ b/src/ui/interpreter.cpp @@ -1,56 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +// The interpreter's core: sessions, scopes, queries and mutations, and mounting. + +#include "interpreter_detail.hpp" namespace morph::ui { @@ -81,21 +33,118 @@ class BridgeDispatcher::Channel final : public ModelChannel { namespace detail { -ElementState::ElementState(reactive::Runtime& runtime) - : draft{runtime}, - committed{runtime}, - edited{runtime, false}, - touched{runtime, false}, - focused{runtime, false}, - open{runtime, false}, - submitted{runtime, false}, - selection{runtime, Value{ValueList{}}}, - sort{runtime, Value{ValueList{}}}, - activeKey{runtime}, - checksVersion{runtime, 0}, - inner{runtime, nullptr} {} - -ElementState::~ElementState() = default; +/// @brief The watches a session made without entries, shared with each registration so that a holder that outlives +/// its session finds nothing to release. +struct WatchRegistry { + /// @brief One watch's record and handler. + struct Watch { + std::string record; + std::function handler; + }; + /// @brief A `watchRecord` whose watch is not answered yet. + struct Waiter { + std::string record; + async::Completion::Promise promise; + WatchHolder holder; + }; + + /// @brief The session; null once it is being destroyed. + Session* session = nullptr; + /// @brief The last watch id given. + std::uint64_t next = 0; + /// @brief The watches, by id. + std::map watches; + /// @brief The records whose `watch` is sent and not answered. + std::set> inFlight; + /// @brief The `watchRecord` calls waiting for an answer. + std::vector waiters; + + /// @brief A `watch` naming @p records was answered: each waiting `watchRecord` for one of them resolves. + /// @param records The records. + void answered(std::vector const& records) { + for (std::string const& record : records) { + inFlight.erase(record); + } + // Moved out first: resolving may release a registration, which reaches back into this registry. + std::vector ready; + std::erase_if(waiters, [&](Waiter& waiter) { + if (std::ranges::find(records, waiter.record) == records.end()) { + return false; + } + ready.push_back(std::move(waiter)); + return true; + }); + for (Waiter& waiter : ready) { + waiter.promise.resolve(waiter.holder); + } + } +}; + +/// @brief One watch of `Session::watchRecord`, released when the last `WatchHolder` copy dies. +struct WatchRegistration { + WatchRegistration() = default; + WatchRegistration(WatchRegistration const&) = delete; + WatchRegistration& operator=(WatchRegistration const&) = delete; + WatchRegistration(WatchRegistration&&) = delete; + WatchRegistration& operator=(WatchRegistration&&) = delete; + + ~WatchRegistration() { + auto const held = registry.lock(); + if (!held) { + return; + } + held->watches.erase(id); + if (held->session == nullptr) { + return; + } + try { + held->session->countRecord(record, -1); + held->session->flushWatches(); + } catch (...) { // NOLINT(bugprone-empty-catch): a destructor has no one to report a failed unwatch to. + } + } + + /// @brief The session's registry. + std::weak_ptr registry; + /// @brief The watch's id there. + std::uint64_t id = 0; + /// @brief The record. + std::string record; +}; + +namespace { + +// The shortest text that reads back as @p number, in fixed notation: `0.0001`, never `1e-04`, so that every value +// a decimal can hold is read as one. The buffer holds the longest fixed form of a double (about 330 characters). +Value decimalOrText(double number) { + std::array buffer{}; + auto const [end, error] = + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): `buffer.data() + buffer.size()` is the end pointer `to_chars` takes + std::to_chars(buffer.data(), buffer.data() + buffer.size(), number, std::chars_format::fixed); + if (error == std::errc{}) { + if (auto const decimal = ::morph::table::parseDecimal(std::string_view{buffer.data(), end})) { + return Value{Decimal{*decimal}}; + } + } + return Value{std::format("{}", number)}; +} + +} // namespace + +std::expected tableValueFromJson(Json const& json) { + return structuralFromJson(json, &decimalOrText); +} + +} // namespace detail + +Session::~Session() { + if (_watchRegistry) { + _watchRegistry->session = nullptr; + _watchRegistry->waiters.clear(); + } +} + +namespace detail { [[nodiscard]] Value evalIn(RtScope const& scope, Bindings const* bindings, ExprPtr const& expr) { if (!expr) { @@ -142,11 +191,6 @@ ElementState::~ElementState() = default; return canonicalJson(value); } -namespace { - -/// @brief A value as a view key: an `int` or a string as itself, anything else as its JSON text. -/// @param value The value. -/// @return The key. [[nodiscard]] Key keyOf(Value const& value) { if (std::int64_t const* const number = value.asInt()) { return Key{*number}; @@ -157,8 +201,6 @@ namespace { return Key{canonicalJson(value)}; } -} // namespace - [[nodiscard]] Value valueOfKey(Key const& key) { if (std::int64_t const* const number = std::get_if(&key)) { return Value{*number}; @@ -166,11 +208,34 @@ namespace { return Value{std::get(key)}; } -namespace { +[[nodiscard]] Value cellRangeValue(std::optional const& range) { + if (!range) { + return Value{}; + } + auto const corner = [](CellRef const& cell) { + return Value{ValueRecord{{"key", valueOfKey(cell.key)}, {"column", Value{cell.column}}}}; + }; + return Value{ValueRecord{{"anchor", corner(range->anchor)}, {"focus", corner(range->focus)}}}; +} + +[[nodiscard]] std::optional cellRangeOf(Value const& value) { + auto const corner = [&value](std::string_view name) -> std::optional { + Value const* const part = value.field(name); + Value const* const key = part == nullptr ? nullptr : part->field("key"); + Value const* const column = part == nullptr ? nullptr : part->field("column"); + if (key == nullptr || key->isNull() || column == nullptr || column->asString() == nullptr) { + return std::nullopt; + } + return CellRef{.key = keyOf(*key), .column = *column->asString()}; + }; + std::optional anchor = corner("anchor"); + std::optional focus = corner("focus"); + if (!anchor || !focus) { + return std::nullopt; + } + return CellRange{.anchor = std::move(*anchor), .focus = std::move(*focus)}; +} -/// @brief A list of strings out of a value: a string, a list of strings, or nothing. -/// @param value The value. -/// @return The strings. [[nodiscard]] std::vector stringsOf(Value const& value) { std::vector out; if (std::string const* const text = value.asString()) { @@ -185,9 +250,6 @@ namespace { return out; } -/// @brief A list of strings as a value. -/// @param texts The strings. -/// @return The list. [[nodiscard]] Value listOfStrings(std::vector const& texts) { ValueList items; items.reserve(texts.size()); @@ -197,16 +259,14 @@ namespace { return Value{std::move(items)}; } -/// @brief A command context without its scope: what a callback the host keeps may hold, so that the host never -/// keeps a scope alive past its screen. The callback holds the scope weakly and puts it back. -/// @param ctx The context. -/// @return The context, its scope dropped. [[nodiscard]] CommandCtx detached(CommandCtx const& ctx) { CommandCtx kept = ctx; kept.scope = nullptr; return kept; } +namespace { + /// @brief Collects the `onClick` lists of menu entries, submenus included. /// @param entries The entries. /// @param lists Where they go, in document order. @@ -220,9 +280,8 @@ void menuCommandLists(std::span entries, std::vector& lists) { for (DocNodePtr const& action : doc.actions) { if (Commands const* const commands = action->event("onClick")) { @@ -239,10 +298,6 @@ void headCommandLists(Document const& doc, std::vector& lists) } } -/// @brief A kind's key spec, from the kind table. -/// @param kind The kind spec. -/// @param key The key. -/// @return The spec, or `nullptr` when the kind has no such key of its own. [[nodiscard]] KeySpec const* keySpec(KindSpec const& kind, std::string_view key) { for (KeySpec const& spec : kind.keys) { if (spec.key == key) { @@ -252,10 +307,6 @@ void headCommandLists(Document const& doc, std::vector& lists) return nullptr; } -/// @brief Whether a node kind keeps per-element state even without an id: the inputs, dialogs, tables and the forms -/// engine's screens. -/// @param kind The kind. -/// @return It. [[nodiscard]] bool statefulKind(std::string_view kind) { static constexpr std::array kStateful = { "textInput", "checkbox", "select", "dateTimeInput", "slider", "filePicker", @@ -264,8 +315,6 @@ void headCommandLists(Document const& doc, std::vector& lists) return listed(kStateful, kind); } -} // namespace - // NOLINTNEXTLINE(modernize-use-string-view): callers keep the key as an owned string, in the log and in tests. [[nodiscard]] std::string commandKey(CommandKind kind) { switch (kind) { @@ -322,10 +371,6 @@ void headCommandLists(Document const& doc, std::vector& lists) } } -} // namespace detail - -namespace detail { - [[nodiscard]] std::string failureText(std::exception_ptr const& error) { try { std::rethrow_exception(error); @@ -387,14 +432,6 @@ namespace { return glz::write_json(valueToJson(value)).value_or(std::string{}); } -namespace { - -/// @brief A value with the field at @p path replaced, creating records along the way. -/// @param base The value written into. -/// @param path The field path. -/// @param value The new value at the path. -/// @return The new value. -// NOLINTNEXTLINE(misc-no-recursion): one level per path segment [[nodiscard]] Value withPath(Value const& base, std::span path, Value value) { if (path.empty()) { return value; @@ -408,16 +445,11 @@ namespace { return Value{std::move(fields)}; } -/// @brief A row's identity for `patch` and `optimistic`: its `id` field. -/// @param row The row. -/// @return The `id` field, or `null`. [[nodiscard]] Value rowId(Value const& row) { Value const* const found = row.field("id"); return found == nullptr ? Value{} : *found; } -} // namespace - [[nodiscard]] Value mergeRow(Value const& row, Value const& with) { ValueRecord const* const fields = row.asRecord(); ValueRecord const* const over = with.asRecord(); @@ -615,6 +647,52 @@ void keyedRowsAt(Value const& value, std::span path, std::str return changed ? std::optional{Value{std::move(out)}} : std::nullopt; } +/// @brief Whether a member at a path is set: a non-empty list, a record, `true`, or a number other than zero. +/// +/// A list on the way is looked through: the member is set when it is set in any element. +/// @param value The value. +/// @param path The members still to follow. +/// @return `true` when set. +// NOLINTNEXTLINE(misc-no-recursion): one level per path member or nested list. +[[nodiscard]] bool memberSetAt(Value const& value, std::span path) { + if (!path.empty()) { + if (ValueList const* const items = value.asList()) { + // NOLINTNEXTLINE(misc-no-recursion): recurses into the nested items of a value, one level per nesting; the depth is the data's + return std::ranges::any_of(*items, [&](Value const& item) { return memberSetAt(item, path); }); + } + ValueRecord const* const record = value.asRecord(); + if (record == nullptr) { + return false; + } + auto const found = record->find(path.front()); + return found != record->end() && memberSetAt(found->second, path.subspan(1)); + } + if (ValueList const* const items = value.asList()) { + return !items->empty(); + } + if (value.asRecord() != nullptr) { + return true; + } + if (bool const* const flag = value.asBool()) { + return *flag; + } + if (std::int64_t const* const number = value.asInt()) { + return *number != 0; + } + if (Decimal const* const decimal = value.asDecimal()) { + return !decimal->value.isZero(); + } + return false; +} + +/// @brief Whether any member at @p paths is set in @p value. +/// @param value The value. +/// @param paths The members' paths. +/// @return `true` when one is. +[[nodiscard]] bool anyMemberSet(Value const& value, std::vector const& paths) { + return std::ranges::any_of(paths, [&](std::string const& path) { return memberSetAt(value, pathMembers(path)); }); +} + } // namespace [[nodiscard]] std::vector keyedRowsOf(Value const& value, std::vector const& paths, @@ -658,12 +736,16 @@ async::Completion BridgeDispatcher::Channel::execute(std::string co promise.reject(std::make_exception_ptr(std::runtime_error{"evaluate needs the UI service"})); return std::move(refused); } + if (options.stop.stop_possible()) { + return _handler.execute(actionId, bodyJson, std::move(options.stop)); + } return _handler.execute(actionId, bodyJson); } ChannelFacts BridgeDispatcher::Channel::facts() const { return ChannelFacts{.instanceId = _handler.instanceId(), .primary = _handler.primary()}; } + // NOLINTBEGIN(performance-unnecessary-value-param,bugprone-easily-swappable-parameters): every default below ignores // its arguments, so each keeps the parameter types of the interface it implements. bool InterpreterHost::navigate(NavigateRequest const& request, std::function onResult, @@ -758,6 +840,7 @@ void InterpreterHost::preferenceChanged(std::string const& screen, std::string c static_cast(point); static_cast(value); } + // NOLINTEND(performance-unnecessary-value-param,bugprone-easily-swappable-parameters) bool Session::can(std::string_view action) const { @@ -1012,8 +1095,13 @@ SessionOptions Session::checkedOptions(SessionOptions options) { } void Session::settleReply(detail::CacheEntry& entry, std::string const& reply) { + // A table's page holds its record opaquely, and its Number cells are numbers with fractions, which the strict + // rule refuses; every other reply keeps the strict rule. + bool const opaque = std::ranges::any_of(entry.records, &ActionRecordInfo::opaque); auto json = parseJson(reply); - auto value = json ? valueFromJson(*json) : std::unexpected(json.error()); + auto value = + // NOLINTNEXTLINE(readability-avoid-nested-conditional-operator): a three-way pick: the opaque rule, the strict rule or the parse error + json ? (opaque ? detail::tableValueFromJson(*json) : valueFromJson(*json)) : std::unexpected(json.error()); if (!value) { settleFailure(entry, "the reply is not a document value: " + value.error(), "error"); return; @@ -1057,31 +1145,6 @@ void Session::applyFacts(std::string locale) { setFormatting(std::move(next)); } -Screen::Screen() = default; - -Screen::~Screen() { - try { - if (Commands const* const commands = lifecycleList("onUnmount")) { - runCommands(*commands); - } - } catch (...) { // NOLINT(bugprone-empty-catch): a destructor has no one to report to. - } - _core->focusElement = {}; - _mounted.reset(); - _headActions.clear(); - _headStatus.clear(); - _headMenu.clear(); - _headTools.clear(); - _scope.reset(); -} - -Widget& Screen::root() const { - if (!_mounted) { - throw std::logic_error{"the screen is not mounted"}; - } - return _mounted->root(); -} - Value Screen::read(Json const& expression) const { auto parsed = parseExpression(expression); if (!parsed) { @@ -1255,6 +1318,12 @@ bool Screen::setPreference(std::string const& point, Value value) { if (found == _core->doc().customize.end() || !fits(found->second, value)) { return false; } + // A point that names a model-backed table edits the table's state, which then says what the point reads. + if (std::optional const taken = _core->tablePoint(found->second, value)) { + if (!*taken) { + return false; + } + } ValueRecord prefs = _core->prefs.peek(); prefs.insert_or_assign(point, std::move(value)); _core->prefs.set(std::move(prefs)); @@ -1319,6 +1388,7 @@ detail::HeadToolModel const* Screen::usableTool(std::string_view toolId) const { } return &*found; } + // NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. auto Screen::findHeadEntry(std::vector const& level, std::string_view entryId, FoundEntry const& outer) -> FoundEntry { @@ -1337,6 +1407,7 @@ auto Screen::findHeadEntry(std::vector const& level, std: } return FoundEntry{}; } + // NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. std::vector Screen::shownHeadMenu(std::vector const& level) { std::vector shown; @@ -1515,8 +1586,20 @@ Value ScopeEnv::row(std::span path) const { if (_row != nullptr) { return walk(*_row, path); } - reactive::Signal const* const current = _scope->innermostRow(); - return current == nullptr ? Value{} : walk(current->get(), path); + RtScope const* owner = _scope; + while (owner != nullptr && owner->row == nullptr) { + owner = owner->parent.get(); + } + if (owner == nullptr) { + return Value{}; + } + Value const& current = owner->row->get(); + // A server-mode row holds the columns fetched: a field it lacks is named, to be fetched after this binding. + if (owner->onMissingRowField != nullptr && !path.empty() && current.asRecord() != nullptr && + current.field(path.front()) == nullptr) { + (*owner->onMissingRowField)(path.front()); + } + return walk(current, path); } void QueryRuntime::invalidate() { @@ -1536,28 +1619,6 @@ bool QueryRuntime::Target::operator==(Target const& other) const { return idle == other.idle && token == other.token && bodyText == other.bodyText; } -ScreenCore::ScreenCore(std::shared_ptr doc, Session& owner, Dispatcher& calls, - InterpreterOptions const& options, MountOptions const& mount) - : session{owner}, - dispatcher{calls}, - host{options.host}, - onDiagnostic{options.diagnostics}, - borrowed{mount.borrowed}, - depth{mount.depth}, - prefs{session.runtime()}, - submitted{session.runtime(), false}, - pendingWork{session.runtime(), 0}, - recording{owner.options().developmentTools == DevelopmentTools::On}, - _doc{std::move(doc)} { - ValueRecord defaults; - for (auto const& [name, point] : _doc->customize) { - defaults.insert_or_assign(name, point.defaultValue); - } - prefDefaults = defaults; - prefs.set(std::move(defaults)); - session.attachScreen(*this); -} - void ScreenCore::runLifecycleOf(std::string_view key) { auto const found = _doc->lifecycle.find(key); auto const scope = rootScope.lock(); @@ -1730,7 +1791,11 @@ void Session::applyRecordEffect(ActionEffect const& effect, std::string const& r if (held == nullptr) { continue; } - if (!ownKey || !held->keyField) { + // A merge replaces rows by key: it cannot find an opaque entry's rows, nor update what an open or partial + // member says about them by position, so such an entry is marked and fetched again. + bool const unmergeable = held->opaque || detail::anyMemberSet(entry->confirmed, held->open) || + detail::anyMemberSet(entry->confirmed, held->partial); + if (!ownKey || !held->keyField || unmergeable) { marks.add(*entry); continue; } @@ -1772,7 +1837,7 @@ void Session::countTopics(detail::CacheEntry const& entry, int delta) { }; if (!entry.records.empty()) { for (ActionRecordInfo const& record : entry.records) { - count(_recordRefs, record.record, _watchRecords, _unwatchRecords); + countRecord(record.record, delta); } return; } @@ -1783,6 +1848,19 @@ void Session::countTopics(detail::CacheEntry const& entry, int delta) { } } +void Session::countRecord(std::string const& record, int delta) { + int& refs = _recordRefs[record]; + refs += delta; + if (delta > 0 && refs == 1 && _unwatchRecords.erase(record) == 0) { + _watchRecords.insert(record); + } else if (refs <= 0) { + _recordRefs.erase(record); + if (_watchRecords.erase(record) == 0) { + _unwatchRecords.insert(record); + } + } +} + void Session::sendWatch(std::string_view kind, wire::WatchBody const& body) const { // The cache's own topics need no answer: a refused one simply sends no events. An extra watch belongs to a // client that cannot work without it, so a refusal of one is reported. @@ -1792,8 +1870,22 @@ void Session::sendWatch(std::string_view kind, wire::WatchBody const& body) cons [this](std::string const& record) { return _extraWatch.contains(record); }); } auto completion = _options.watcher(std::string{kind}, glz::write_json(body).value_or(std::string{})); + // A watch's records are in flight until its answer: a `watchRecord` for one of them resolves then. + std::weak_ptr const weak = _watchRegistry; + std::vector records; + if (kind == wire::kWatchKind) { + records = body.records; + if (_watchRegistry) { + _watchRegistry->inFlight.insert(records.begin(), records.end()); + } + } + auto const answered = [weak, records = std::move(records)] { + if (auto const registry = weak.lock(); registry && !records.empty()) { + registry->answered(records); + } + }; completion - .then([extras](std::string const& reply) { + .then([extras, answered](std::string const& reply) { auto const read = wire::readWatchReply(reply); for (std::string const& record : extras) { if (!read || std::ranges::find(read->refusedRecords, record) != read->refusedRecords.end()) { @@ -1801,11 +1893,13 @@ void Session::sendWatch(std::string_view kind, wire::WatchBody const& body) cons record); } } + answered(); }) - .onError([extras](std::exception_ptr const& error) { + .onError([extras, answered](std::exception_ptr const& error) { for (std::string const& record : extras) { ::morph::log::logWarn("the watch on `{}` failed: {}", record, detail::failureText(error)); } + answered(); }); } @@ -1828,6 +1922,7 @@ void Session::flushWatches() { return body; }; if (!_watchRecords.empty() || !_watchInstances.empty()) { + static_cast(watchRegistry()); sendWatch(wire::kWatchKind, take(_watchRecords, _watchInstances)); } // An extra watch outlives the cache's last entry on the record. @@ -1892,6 +1987,33 @@ void Session::reconnected() { sendWatch(wire::kWatchKind, body); } markAllStale(); + if (_watchRegistry) { + std::set> records; + for (auto const& [watchId, watch] : _watchRegistry->watches) { + static_cast(watchId); + records.insert(watch.record); + } + for (std::string const& record : records) { + notifyWatchers(effects::RecordChange{.record = record, .keys = std::nullopt}); + } + } + std::erase_if(_reconnectListeners, [](auto const& listener) { return listener.expired(); }); + std::vector>> listeners; + for (auto const& listener : _reconnectListeners) { + if (auto held = listener.lock()) { + listeners.push_back(std::move(held)); + } + } + for (auto const& listener : listeners) { + (*listener)(); + } +} + +std::shared_ptr Session::onReconnected(std::function handler) { + auto held = std::make_shared>(std::move(handler)); + std::erase_if(_reconnectListeners, [](auto const& listener) { return listener.expired(); }); + _reconnectListeners.push_back(held); + return held; } void Session::deliverEvent(wire::EventBody const& event) { @@ -1918,6 +2040,93 @@ void Session::applyChanges(wire::ChangesBody const& changes) { } markAndRefetch(marks); }); + for (effects::RecordChange const& change : changes.records) { + notifyWatchers(change); + } +} + +void Session::notifyWatchers(effects::RecordChange const& change) { + if (!_watchRegistry) { + return; + } + // A handler may drop its own watch, or another, so the handlers are copied out first. + std::vector> handlers; + for (auto const& [watchId, watch] : _watchRegistry->watches) { + static_cast(watchId); + if (watch.record == change.record) { + handlers.push_back(watch.handler); + } + } + for (auto const& handler : handlers) { + handler(change); + } +} + +detail::WatchRegistry& Session::watchRegistry() { + if (!_watchRegistry) { + _watchRegistry = std::make_shared(); + _watchRegistry->session = this; + } + return *_watchRegistry; +} + +async::Completion Session::watchRecord(std::string const& record, + std::function handler) { + auto& registry = watchRegistry(); + auto const watchId = ++registry.next; + registry.watches.emplace(watchId, detail::WatchRegistry::Watch{.record = record, .handler = std::move(handler)}); + auto registration = std::make_shared(); + registration->registry = _watchRegistry; + registration->id = watchId; + registration->record = record; + WatchHolder holder{std::move(registration)}; + countRecord(record, +1); + flushWatches(); + auto [completion, promise] = async::Completion::makeSettleable(&_runtime->owner()); + if (registry.inFlight.contains(record)) { + registry.waiters.push_back(detail::WatchRegistry::Waiter{ + .record = record, .promise = std::move(promise), .holder = std::move(holder)}); + } else { + promise.resolve(std::move(holder)); + } + return std::move(completion); +} + +async::Completion Session::read(std::shared_ptr const& channel, std::string const& actionId, + Value const& body, ::core::async::StopToken const& stop) { + using Promise = async::Completion::Promise; + auto [completion, promise] = async::Completion::makeSettleable(&_runtime->owner()); + auto const settle = std::make_shared(std::move(promise)); + if (channel == nullptr) { + settle->reject(std::make_exception_ptr(std::runtime_error{"the model alias has no instance"})); + return std::move(completion); + } + if (stop.stop_requested()) { + settle->reject(std::make_exception_ptr(::core::async::OperationCancelled{})); + return std::move(completion); + } + // A stop settles the read at once; the reply that may still come is dropped, since the first settlement wins. + using OnStop = ::core::async::StopCallback>; + std::shared_ptr onStop; + if (stop.stop_possible()) { + onStop = + std::make_shared(stop, std::function{[settle] { + settle->reject(std::make_exception_ptr(::core::async::OperationCancelled{})); + }}); + } + try { + auto sent = channel->execute(actionId, detail::canonicalJson(body), + CallOptions{.evaluate = false, .queueOffline = false, .stop = stop}); + sent.then([settle, onStop, stop](std::string const& reply) { + if (!stop.stop_requested()) { + settle->resolve(reply); + } + }) + .onError([settle, onStop](std::exception_ptr const& error) { settle->reject(error); }); + } catch (...) { + settle->reject(std::current_exception()); + } + return std::move(completion); } void Session::markRecordChange(effects::RecordChange const& change, detail::Marks& marks) { @@ -1936,8 +2145,11 @@ void Session::markRecordChange(effects::RecordChange const& change, detail::Mark if (held == nullptr) { continue; } - // An entry still waiting for its first value may come to hold a key; keyless rows cannot be told apart. - if (!change.keys || !held->keyField || !entry->hasValue.peek()) { + // An entry still waiting for its first value may come to hold a key; keyless rows cannot be told apart. An + // opaque entry's rows cannot be found by key, and while an open member is set a row the entry does not hold + // may come to belong to it. + if (!change.keys || !held->keyField || !entry->hasValue.peek() || held->opaque || + detail::anyMemberSet(entry->confirmed, held->open)) { marks.add(*entry); continue; } @@ -1989,12 +2201,6 @@ namespace detail { return canonicalJson(key); } -namespace { - -/// @brief The channel an alias is bound to for its current token, binding it when the token changed. -/// @param alias The alias. -/// @param core The screen. -/// @return The channel, or `nullptr` while the alias is unbound. [[nodiscard]] std::shared_ptr channelOf(ModelAlias& alias, ScreenCore& core) { std::string const token = core.runtime().untracked([&] { return alias.token->get(); }); if (token.empty()) { @@ -2027,7 +2233,6 @@ namespace { alias.boundToken = token; return alias.channel; } -} // namespace RtScope::RtScope(ScreenCore& screen, std::shared_ptr enclosing, reactive::Signal const* current, std::size_t depth) @@ -2037,18 +2242,6 @@ RtScope::RtScope(ScreenCore& screen, std::shared_ptr enclosing, reactiv } } -RtScope::~RtScope() { - if (core.recording) { - std::erase(core.scopes, this); - } - if (owner != nullptr) { - core.addPending(-1); - if (owner->inner.peek() == this) { - owner->inner.set(nullptr); - } - } -} - // NOLINTNEXTLINE(misc-no-recursion): an element's value can read a nested scope's readiness, one level per nesting. bool RtScope::ready() const { for (auto const& element : elements) { @@ -2411,6 +2604,47 @@ bool QueryRuntime::settled() const { return !current || current->hasValue.get() || !current->error.get().empty(); } +} // namespace detail + +// --- Rows an action works on ---------------------------------------------------------------------------------- + +std::vector tableInputsOf(std::string_view schemaJson) { + std::vector out; + glz::generic_u64 schema; + if (glz::read_json(schema, schemaJson) || !schema.is_object()) { + return out; + } + auto const& members = schema.get_object(); + // An edit action is itself the marked type: its keyword sits at the root, and its row is its `key`. + for (std::string_view const keyword : {std::string_view{"x-cellEditOf"}, std::string_view{"x-rowEditOf"}}) { + const auto* const found = members.find(std::string{keyword}); + if (found != members.end() && found->second.is_string()) { + out.push_back( + TableInput{.member = "key", .record = found->second.get_string(), .kind = TableInputKind::CellEdit}); + } + } + const auto* const properties = members.find("properties"); + if (properties == members.end() || !properties->second.is_object()) { + return out; + } + for (auto const& [name, property] : properties->second.get_object()) { + if (!property.is_object()) { + continue; + } + auto const& keywords = property.get_object(); + for (auto const& [keyword, kind] : {std::pair{std::string_view{"x-selectionOf"}, TableInputKind::Selection}, + std::pair{std::string_view{"x-rowOf"}, TableInputKind::Row}}) { + const auto* const found = keywords.find(std::string{keyword}); + if (found != keywords.end() && found->second.is_string()) { + out.push_back(TableInput{.member = name, .record = found->second.get_string(), .kind = kind}); + } + } + } + return out; +} + +namespace detail { + // --- Mutations ------------------------------------------------------------------------------------------------- MutationRuntime::MutationRuntime(MutationDecl const& decl, RtScope& scope, ModelAlias* alias) @@ -2464,6 +2698,10 @@ void MutationRuntime::run(Value body, std::shared_ptr bindings, void MutationRuntime::send(std::shared_ptr const& run) { run->id = ++_runs; _latest = run->id; + run->sessionRun = _core->session.nextRunId(); + for (RunObserver* const observer : _core->session.runObservers()) { + observer->started(RunStarted{.run = run->sessionRun, .action = _decl->action, .body = run->body}); + } applyOptimistic(*run); std::shared_ptr const channel = channelOf(*_alias, _scope->core); if (channel == nullptr) { @@ -2612,6 +2850,32 @@ void MutationRuntime::settle(std::shared_ptr const& run, std::optionalconcurrency == Concurrency::Serial) { next(run->serialKey); } + if (auto const observers = session.runObservers(); !observers.empty()) { + std::string code; + if (!succeeded) { + Value const refusal = detail::refusalValue(error); + if (Value const* const named = refusal.field("code"); named != nullptr && named->asString() != nullptr) { + code = *named->asString(); + } + } + // The rerun holds the mutation weakly: it may be chosen after the screen that ran it is gone. + std::weak_ptr const alive = _alive; + auto const rerun = [this, alive, bindings = run->bindings](Value body) { + if (!alive.expired()) { + this->run(std::move(body), bindings, [](bool, Value const&) {}); + } + }; + Value const replied = reply ? *reply : Value{}; + for (RunObserver* const observer : observers) { + observer->settled(RunSettled{.run = run->sessionRun, + .action = _decl->action, + .body = run->body, + .succeeded = succeeded, + .reply = replied, + .refusalCode = code, + .rerun = rerun}); + } + } run->done(succeeded, delivered); } @@ -2630,6371 +2894,4 @@ void MutationRuntime::next(std::string const& serialKey) { } // namespace detail -namespace detail { -namespace { - -// --- Declaring scopes ------------------------------------------------------------------------------------------ - -/// @brief The element a node of a scope keeps its state in. -/// @param scope The scope that declares it. -/// @param node The node. -/// @return The element, or `nullptr` for a node that keeps none. -[[nodiscard]] ElementState* elementFor(RtScope const& scope, DocNode const& node) { - // A scope that declares nothing (a locale scope and the scope of its mounted content) leaves its children's - // elements to the enclosing scope, where `collect` registered them, so the lookup continues there. - for (RtScope const* at = &scope; at != nullptr; at = at->transparent ? at->parent.get() : nullptr) { - for (auto const& element : at->elements) { - if (element->node == &node) { - return element.get(); - } - } - } - return nullptr; -} - -/// @brief The transfers of the `upload` commands in a list, nested lists included. -/// @param commands The list. -/// @param out Where the transfer ids go. -// NOLINTNEXTLINE(misc-no-recursion): one level per nested command list -void transfersOf(Commands const& commands, std::vector& out) { - for (Command const& command : commands) { - if (command.kind == CommandKind::Upload && !command.transfer.empty()) { - out.push_back(command.transfer); - } - transfersOf(command.commands, out); - transfersOf(command.alternative, out); - } -} -} // namespace - -// NOLINTBEGIN(misc-no-recursion): a document is a tree of nodes and parts, and collecting descends it. -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of node and part. -void ScreenCore::collect(DocNode const& node, RtScope& scope, std::vector& commands) { - KindSpec const* const spec = findKind(node.kind, false); - if (!node.id.empty() || statefulKind(node.kind)) { - auto element = std::make_unique(runtime()); - element->node = &node; - element->scope = &scope; - if (!node.id.empty()) { - NameRef name; - name.category = NameCategory::Element; - name.element = element.get(); - scope.names.insert_or_assign(node.id, name); - } - wireErrors(*element); - scope.elements.push_back(std::move(element)); - } - bool const createsScope = spec != nullptr && (spec->flags & kScope) != 0; - for (auto const& [key, list] : node.events) { - KeySpec const* const keyed = spec == nullptr ? nullptr : keySpec(*spec, key); - if (!createsScope || keyed == nullptr || (keyed->flags & kInner) == 0) { - commands.push_back(&list); - } - } - for (auto const& [chord, list] : node.keys) { - static_cast(chord); - commands.push_back(&list); - } - for (auto const& [key, nodes] : node.children) { - KeySpec const* const keyed = spec == nullptr ? nullptr : keySpec(*spec, key); - if (createsScope && keyed != nullptr && (keyed->flags & kInner) != 0) { - continue; - } - for (DocNodePtr const& child : nodes) { - collect(*child, scope, commands); - } - } - for (auto const& [key, parts] : node.parts) { - static_cast(key); - for (DocNodePtr const& part : parts) { - KindSpec const* const partSpec = findKind(part->kind, true); - if (partSpec != nullptr && (partSpec->flags & kScope) != 0) { - continue; - } - for (auto const& [event, list] : part->events) { - static_cast(event); - commands.push_back(&list); - } - for (auto const& [childKey, nodes] : part->children) { - KeySpec const* const keyed = partSpec == nullptr ? nullptr : keySpec(*partSpec, childKey); - if (keyed != nullptr && (keyed->flags & kInner) != 0) { - continue; - } - for (DocNodePtr const& child : nodes) { - collect(*child, scope, commands); - } - } - } - } -} -// NOLINTEND(misc-no-recursion) - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per kind of declaration. -void ScreenCore::declare(RtScope& scope, ScopeDecl const* decl, std::vector const& content, - std::vector const& commands) { - std::vector lists = commands; - for (DocNode const* const node : content) { - collect(*node, scope, lists); - } - std::vector transferIds; - for (Commands const* const list : lists) { - transfersOf(*list, transferIds); - } - for (std::string const& transferId : transferIds) { - if (scope.names.contains(transferId)) { - continue; - } - scope.transfers.push_back(std::make_unique(runtime())); - NameRef name; - name.category = NameCategory::Transfer; - name.transfer = scope.transfers.back().get(); - scope.names.insert_or_assign(transferId, name); - } - if (decl != nullptr) { - for (ModelDecl const& model : decl->models) { - auto alias = std::make_unique(); - alias->decl = &model; - alias->mode = model.instance; - if (alias->mode == InstanceMode::Default) { - std::optional const info = - session.options().catalog.model ? session.options().catalog.model(model.type) : std::nullopt; - alias->mode = info && info->stateless ? InstanceMode::Shared : InstanceMode::Private; - } - ModelAlias* const raw = alias.get(); - switch (raw->mode) { - case InstanceMode::Keyed: - raw->token = &scope.nodes.computed([&scope, raw] -> std::string { - std::string const key = instanceKeyText(evalIn(scope, nullptr, raw->decl->key)); - return key.empty() ? std::string{} : "shared:" + key; - }); - break; - case InstanceMode::Shared: - raw->token = &scope.nodes.computed([] { return std::string{"shared"}; }); - break; - case InstanceMode::Borrowed: { - auto const found = borrowed.find(model.name); - std::string token = found == borrowed.end() ? std::string{} : found->second.token; - raw->token = &scope.nodes.computed([token = std::move(token)] { return token; }); - break; - } - case InstanceMode::Private: - case InstanceMode::Default: - default: { - std::string token = session.privateToken(); - raw->token = &scope.nodes.computed([token = std::move(token)] { return token; }); - break; - } - } - NameRef name; - name.category = NameCategory::Model; - name.model = raw; - scope.names.insert_or_assign(model.name, name); - scope.models.push_back(std::move(alias)); - } - for (LetDecl const& let : decl->lets) { - NameRef name; - name.category = NameCategory::Let; - name.letExpr = let.value; - name.let = &scope.nodes.computed([&scope, expr = let.value] { return evalIn(scope, nullptr, expr); }); - scope.names.insert_or_assign(let.name, name); - } - for (StateDecl const& state : decl->state) { - auto slot = std::make_unique(); - slot->decl = &state; - slot->scope = &scope; - NameRef name; - name.category = NameCategory::State; - name.state = slot.get(); - scope.names.insert_or_assign(state.name, name); - scope.states.push_back(std::move(slot)); - } - auto const aliasOf = [&scope](std::string const& model) -> ModelAlias* { - NameRef const* const found = scope.find(model); - return found != nullptr && found->category == NameCategory::Model ? found->model : nullptr; - }; - for (QueryDecl const& query : decl->queries) { - scope.queries.push_back(std::make_unique(query, scope, aliasOf(query.model))); - NameRef name; - name.category = NameCategory::Query; - name.query = scope.queries.back().get(); - scope.names.insert_or_assign(query.name, name); - } - for (MutationDecl const& mutation : decl->mutations) { - scope.mutations.push_back(std::make_unique(mutation, scope, aliasOf(mutation.model))); - NameRef name; - name.category = NameCategory::Mutation; - name.mutation = scope.mutations.back().get(); - scope.names.insert_or_assign(mutation.name, name); - } - } - for (auto const& slot : scope.states) { - initState(scope, *slot); - } - for (auto const& element : scope.elements) { - wireElement(*element); - } - if (decl == nullptr) { - return; - } - for (CheckDecl const& check : decl->checks) { - auto made = std::make_unique(); - made->decl = ✓ - made->failing = &scope.nodes.computed([&scope, expr = check.assertion] { - Value const asserted = evalIn(scope, nullptr, expr); - bool const* const flag = asserted.asBool(); - return flag != nullptr && !*flag; - }); - made->message = &scope.nodes.computed( - [&scope, expr = check.message] { return textOf(evalIn(scope, nullptr, expr), scope.formatting()); }); - for (std::string const& target : check.targets) { - NameRef const* const found = scope.find(target); - if (found != nullptr && found->category == NameCategory::Element) { - found->element->checks.push_back(made.get()); - made->targets.push_back(found->element); - found->element->checksVersion.set(found->element->checksVersion.peek() + 1); - } - } - scope.checks.push_back(std::move(made)); - } - for (auto const& query : scope.queries) { - query->start(); - } - for (WatchDecl const& watch : decl->watches) { - auto& source = scope.nodes.computed([&scope, expr = watch.on] { return evalIn(scope, nullptr, expr); }); - scope.nodes.effect([this, &scope, &source, watched = &watch, first = true] mutable { - static_cast(source.get()); - if (first) { - first = false; - return; - } - bool const user = session.lastWriteByUser(); - if (watched->source == WatchSource::User && !user) { - return; - } - runtime().untracked([&] { - CommandCtx const ctx{ - .scope = scope.shared_from_this(), - .bindings = std::make_shared(), - .cancelClose = std::make_shared(false), - .boundary = nullptr, - }; - if (user) { - session.asUser([&] { runList(watched->body, ctx, {}); }); - } else { - runList(watched->body, ctx, {}); - } - }); - }); - } -} - -namespace { - -/// @brief What a date input reads from a value: the instant it shows, and whether the value names one at all. -struct DateReading { - /// @brief The instant shown; empty for an empty field. - std::optional instant; - /// @brief Whether the value names a date, an instant or nothing; `false` for text that names no date. - bool readable = true; -}; - -/// @brief Reads what a date input shows for @p value, in a display zone @p offsetMinutes from UTC. -/// -/// The value is read as the date functions read it (`readDateValue`): a timestamp is its instant; a `yyyy-MM-dd` -/// string is midnight of that date in the display zone; a string `DateTime::fromIso8601` reads is its instant; `null` -/// and `""` are empty. Any other value is empty and unreadable. -/// @param value The value. -/// @param offsetMinutes The display zone's offset from UTC, in minutes. -/// @return The instant, or nothing, and whether the value was readable. -[[nodiscard]] DateReading dateInstantOf(Value const& value, std::int32_t offsetMinutes) { - DateValue const reading = readDateValue(value); - switch (reading.form) { - case DateForm::Absent: - return {}; - case DateForm::Date: - return { - .instant = time::DateTime{std::chrono::sys_days{reading.date} - std::chrono::minutes{offsetMinutes}}, - }; - case DateForm::Timestamp: - case DateForm::InstantText: - return {.instant = reading.instant}; - case DateForm::Unreadable: - default: - return {.instant = std::nullopt, .readable = false}; - } -} - -/// @brief A date input's date text for @p instant in a display zone @p offsetMinutes from UTC. -/// @param instant The instant. -/// @param offsetMinutes The display zone's offset from UTC, in minutes. -/// @return `yyyy-MM-dd`. -[[nodiscard]] std::string dateTextOf(time::DateTime const& instant, std::int32_t offsetMinutes) { - auto const local = instant.value + std::chrono::minutes{offsetMinutes}; - std::chrono::year_month_day const date{std::chrono::floor(local)}; - return std::format("{:04}-{:02}-{:02}", static_cast(date.year()), static_cast(date.month()), - static_cast(date.day())); -} - -/// @brief A value as the places a number is entered with. -/// @param value The value. -/// @param format The formatting facts. -/// @return The places, 0 to the most a decimal holds; -1 for a value that is not a non-negative integer. -[[nodiscard]] int placesOf(Value const& value, FormatContext const& format) { - static_cast(format); // Only to fit `bindProp`'s converter signature. - std::int64_t const* const whole = value.asInt(); - if (whole == nullptr || *whole < 0) { - return -1; - } - return static_cast(std::min(*whole, math::kMaxDecimalPlaces)); -} - -/// @brief The fraction digits of a number as typed in the active locale. -/// @param text The typed text. -/// @param format The formatting facts. -/// @return The digits after the decimal separator; 0 for a text that is not a number, which no places rule judges. -[[nodiscard]] std::size_t fractionDigits(std::string_view text, FormatContext const& format) { - std::optional const canonical = render::normalizeLocaleNumber(text, withoutGrouping(format.numeric)); - if (!canonical.has_value()) { - return 0; - } - auto const dot = canonical->find('.'); - return dot == std::string::npos ? 0 : canonical->size() - dot - 1; -} - -/// @brief Whether two values show the same in an input: by text for a text input, by instant for a date input, by -/// value otherwise. -/// @param kind The input's kind. -/// @param lhs One value. -/// @param rhs The other. -/// @param format The formatting facts. -/// @return It. -[[nodiscard]] bool sameShown(std::string_view kind, Value const& lhs, Value const& rhs, FormatContext const& format) { - if (kind == "textInput" || kind == "filePicker") { - return textOf(lhs, format) == textOf(rhs, format); - } - if (kind == "dateTimeInput") { - return dateInstantOf(lhs, format.utcOffsetMinutes).instant == - dateInstantOf(rhs, format.utcOffsetMinutes).instant; - } - return lhs == rhs; -} - -/// @brief The key of a select option: a record's `key`, `id` or `value` field, or the option itself. -/// @param option The option. -/// @return The key. -[[nodiscard]] Value optionKey(Value const& option) { - if (option.asRecord() == nullptr) { - return option; - } - for (std::string_view const field : {"key", "id", "value"}) { - if (Value const* const found = option.field(field)) { - return *found; - } - } - return Value{}; -} -} // namespace - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one rule per source of an error. -void ScreenCore::wireErrors(ElementState& element) { - RtScope& scope = *element.scope; - element.errors = &scope.nodes.computed([this, &element] -> Value { - static_cast(element.checksVersion.get()); - DocNode const& field = *element.node; - RtScope const& owner = *element.scope; - std::vector errors; - // A group's `required` is its legend's mark only: a group has no value, so no `Required` is derived from it. - if (ExprPtr const required = field.kind != "group" ? field.prop("required") : nullptr) { - Value const requiredNow = evalIn(owner, nullptr, required); - bool const* const flag = requiredNow.asBool(); - if (flag != nullptr && *flag && !engaged(inputValue(element))) { - errors.emplace_back("Required"); - } - } - for (std::string& text : stringsOf(evalIn(owner, nullptr, field.prop("errors")))) { - errors.push_back(std::move(text)); - } - if (ExprPtr const places = field.kind == "textInput" ? field.prop("decimals") : nullptr) { - int const allowed = placesOf(evalIn(owner, nullptr, places), session.formatting()); - if (allowed >= 0 && fractionDigits(textOf(inputValue(element), session.formatting()), - session.formatting()) > static_cast(allowed)) { - // The key and fallback of a form field's `too-precise`, so both read alike in any language. - errors.emplace_back(render::resolveText(session.formatting().translations, session.formatting().locale, - std::nullopt, "morph.forms.error.too-precise", - "Too many decimal places")); - } - } - if (!field.id.empty()) { - std::vector const path{"errors", field.id}; - for (auto const& query : owner.queries) { - for (std::string& text : stringsOf(walk(query->value(), path))) { - errors.push_back(std::move(text)); - } - } - for (auto const& mutation : owner.mutations) { - for (std::string& text : stringsOf(walk(mutation->result(), path))) { - errors.push_back(std::move(text)); - } - } - } - for (CheckRuntime const* const check : element.checks) { - if (check->failing->get()) { - errors.push_back(check->message->get()); - } - } - return listOfStrings(errors); - }); -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of element. -void ScreenCore::wireElement(ElementState& element) { - DocNode const& node = *element.node; - RtScope& scope = *element.scope; - std::string_view const kind = node.kind; - if (kind == "form") { - wireForm(element); - return; - } - if (kind == "collection" || kind == "wizard") { - wireComposite(element); - return; - } - bool const input = kind == "textInput" || kind == "checkbox" || kind == "select" || kind == "dateTimeInput" || - kind == "slider" || kind == "filePicker"; - if (input) { - std::string_view key = "value"; - if (kind == "checkbox") { - key = "checked"; - } else if (kind == "select") { - key = "selected"; - } - ExprPtr const expr = kind == "filePicker" ? nullptr : node.prop(key); - bool const controlled = expr && (expr->kind != ExprKind::Literal || !expr->literal.isNull()); - if (controlled) { - element.bound = &scope.nodes.computed([&scope, expr] { return evalIn(scope, nullptr, expr); }); - element.draft.set(runtime().untracked([&] { return element.bound->get(); })); - scope.nodes.effect([this, &element, kind] { - Value const bound = element.bound->get(); - runtime().untracked([&] { - if (!element.edited.peek()) { - element.draft.set(bound); - } else if (sameShown(kind, element.draft.peek(), bound, session.formatting())) { - element.edited.set(false); - } - }); - }); - } else if (kind == "checkbox") { - element.draft.set(false); - } - } - if (kind == "select") { - element.rows = - &scope.nodes.computed([&scope, expr = node.prop("options")] { return evalIn(scope, nullptr, expr); }); - if (element.bound == nullptr && node.name("onStale") == "clear") { - scope.nodes.effect([this, &element] { - Value const options = element.rows->get(); - runtime().untracked([&] { - Value const selected = element.draft.peek(); - if (selected.isNull()) { - return; - } - ValueList const* const items = options.asList(); - bool const kept = items != nullptr && std::ranges::any_of(*items, [&](Value const& option) { - return optionKey(option) == selected; - }); - if (!kept) { - session.noteWrite(); - element.draft.set(Value{}); - } - }); - }); - } - } - if (kind == "table" && node.prop("rows")) { - element.rows = - &scope.nodes.computed([&scope, expr = node.prop("rows")] { return evalIn(scope, nullptr, expr); }); - // A bound selection is controlled, as a select's `selected` is: any expression but a literal `null` binds it. - ExprPtr const selection = node.prop("selection"); - if (selection && (selection->kind != ExprKind::Literal || !selection->literal.isNull())) { - element.bound = &scope.nodes.computed([&scope, selection] { return evalIn(scope, nullptr, selection); }); - } - // A bound sort is controlled as the selection is. - ExprPtr const sort = node.prop("sort"); - if (sort && (sort->kind != ExprKind::Literal || !sort->literal.isNull())) { - element.sortBound = &scope.nodes.computed([&scope, sort] { return evalIn(scope, nullptr, sort); }); - } - element.view = &scope.nodes.computed([this, &element] { return tableView(element, nullptr); }); - } -} - -namespace { - -/// @brief A table's sort as its element value reads it: the bound `sort` when the key binds one, else the table's -/// own. -/// @param element The table's element. -/// @return The sort. Tracked. -[[nodiscard]] Value tableSort(ElementState const& element) { - return element.sortBound != nullptr ? element.sortBound->get() : element.sort.get(); -} - -/// @brief A table's page values: `viewCount` (the rows it orders, every page), `page`, `pageCount`, and -/// `pageFirst` and `pageLast`, the 1-based positions of the page's first and last rows, both 0 when there are -/// none. A table that does not page reads page 0 of 1, over every row. -/// @param element The table's element. -/// @param name The value's name. -/// @return The value. Tracked. -[[nodiscard]] Value tablePageValue(ElementState const& element, std::string_view name) { - if (element.view == nullptr) { - return name == "pageCount" ? std::int64_t{1} : std::int64_t{0}; - } - TableView const& view = element.view->get(); - if (name == "viewCount") { - return static_cast(view.rows.size()); - } - if (name == "page") { - return view.page; - } - if (name == "pageCount") { - return view.pageCount; - } - bool const none = view.first == view.last; - if (name == "pageFirst") { - return none ? std::int64_t{0} : static_cast(view.first + 1); - } - return static_cast(view.last); -} - -/// @brief The selected keys of the rows a table holds on pages other than the one shown, in their order: what an -/// `Extend` report keeps, since the backend holds the shown page alone. -/// @param view The table's rows and page. -/// @param selection The selection, a list of keys. -/// @param rowKey A row's key. -/// @return The keys. -[[nodiscard]] ValueList selectedOffPage(TableView const& view, Value const& selection, - std::function const& rowKey) { - std::unordered_set onPage; - std::unordered_set offPage; - for (std::size_t index = 0; index < view.rows.size(); ++index) { - (index >= view.first && index < view.last ? onPage : offPage).insert(rowKey(view.rows.at(index))); - } - ValueList kept; - if (ValueList const* const selected = selection.asList()) { - for (Value const& item : *selected) { - Key const key = keyOf(item); - if (offPage.contains(key) && !onPage.contains(key)) { - kept.push_back(item); - } - } - } - return kept; -} - -/// @brief The sortable column part of a table with the id @p columnId. -/// @param table The table. -/// @param columnId The column's id. -/// @return The part, or `nullptr` when no sortable column has that id. -[[nodiscard]] DocNode const* sortableColumn(DocNode const& table, std::string_view columnId) { - for (DocNodePtr const& column : table.partList("columns")) { - if (column->id == columnId && column->flag("sortable")) { - return column.get(); - } - } - return nullptr; -} - -/// @brief One key of a table's sort: the column part that orders the rows, and whether it is descending. -struct SortKey { - /// @brief The sortable column. - DocNode const* column = nullptr; - /// @brief Whether the key sorts descending. - bool descending = false; -}; - -/// @brief A table's sort read as its keys: a list of `{"column", "direction"}` records naming sortable columns. -/// @param table The table. -/// @param sort The sort; `null` is the source order, as `[]` is. -/// @return The keys, most significant first; `nullopt` when @p sort is not such a list. -[[nodiscard]] std::optional> sortKeysOf(DocNode const& table, Value const& sort) { - std::vector keys; - if (sort.isNull()) { - return keys; - } - ValueList const* const items = sort.asList(); - if (items == nullptr) { - return std::nullopt; - } - for (Value const& item : *items) { - Value const* const column = item.field("column"); - Value const* const direction = item.field("direction"); - std::string const* const columnId = column == nullptr ? nullptr : column->asString(); - std::string const* const way = direction == nullptr ? nullptr : direction->asString(); - DocNode const* const part = columnId == nullptr ? nullptr : sortableColumn(table, *columnId); - if (part == nullptr || way == nullptr || (*way != "asc" && *way != "desc")) { - return std::nullopt; - } - keys.push_back(SortKey{.column = part, .descending = *way == "desc"}); - } - return keys; -} -} // namespace - -void ScreenCore::groupRows(ElementState const& element, Bindings const* bindings, TableView& view) { - auto const parts = element.node->partList("group"); - if (parts.empty()) { - return; - } - ExprPtr const groupBy = parts.front()->prop("by"); - RtScope const& scope = *element.scope; - ScopeEnv const tableEnv{scope, bindings}; - Evaluator runs{tableEnv}; - // A heading's key is its run's key and its ordinal among the runs with an equal key, since adjacent grouping - // can give two runs one key (samples A, B, A); the ordinal stays put across a sort, which moves no run. - std::map> ordinals; - Value key; - ValueList run; - auto const close = [&] { - std::string const json = canonicalJson(key); - Value const record = runRecord(key, std::exchange(run, {})); - ValueRecord entry = *record.asRecord(); - entry.insert_or_assign(std::string{kGroupHeadingField}, - Value{"\x1Fgroup:" + json + ":" + std::to_string(ordinals[json]++)}); - view.runs.emplace_back(std::move(entry)); - }; - for (Value const& row : view.rows) { - Value value = evaluate(*groupBy, ScopeEnv{scope, bindings, &row}); - if (!run.empty() && !runs.sameRun(key, value)) { - close(); - } - if (run.empty()) { - key = std::move(value); - } - run.push_back(row); - view.runOf.push_back(view.runs.size()); - } - if (!run.empty()) { - close(); - } -} - -void ScreenCore::sortedRows(ElementState const& element, Bindings const* bindings, TableView& view) { - DocNode const& node = *element.node; - RtScope const& scope = *element.scope; - Value const source = bindings == nullptr ? element.rows->get() : evalIn(scope, bindings, node.prop("rows")); - ValueList const* const items = source.asList(); - if (items == nullptr) { - return; - } - view.rows.assign(items->begin(), items->end()); - groupRows(element, bindings, view); - Value const sort = tableSort(element); - std::optional> const keys = sortKeysOf(node, sort); - std::string const sortPath = pointerAppend(node.path, "sort"); - if (!keys) { - report( - sortPath, - "sort is " + canonicalJson(sort) + - R"(; a table's sort is a list of {"column": , "direction": "asc" or "desc"})"); - return; - } - if (keys->empty()) { - return; - } - // Each row's keys are read once, then the rows are ordered by them: a change to the sort, the rows, or anything - // a `sortBy` reads sorts again. A grouped table orders by the group first, so every group keeps its place in - // the source order and its rows are sorted within it. - bool const grouped = !view.runOf.empty(); - std::vector> rowKeys; - rowKeys.reserve(view.rows.size()); - for (std::size_t index = 0; index < view.rows.size(); ++index) { - Value const& row = view.rows.at(index); - ScopeEnv const env{scope, bindings, &row}; - std::vector values; - values.reserve(keys->size() + 1); - if (grouped) { - values.emplace_back(static_cast(view.runOf.at(index))); - } - for (SortKey const& key : *keys) { - if (ExprPtr const sortBy = key.column->prop("sortBy")) { - values.push_back(evaluate(*sortBy, env)); - } else { - Value const* const field = row.field(key.column->id); - values.push_back(field == nullptr ? Value{} : *field); - } - } - rowKeys.push_back(std::move(values)); - } - std::vector descending; - descending.reserve(keys->size() + 1); - if (grouped) { - descending.push_back(false); - } - for (SortKey const& key : *keys) { - descending.push_back(key.descending); - } - ScopeEnv const env{scope, bindings}; - std::optional> const order = Evaluator{env}.sortRows(rowKeys, descending); - if (!order) { - report(sortPath, "the rows' values for the sort are not of one comparable kind; the rows keep their order"); - return; - } - std::vector sorted; - std::vector runOf; - sorted.reserve(view.rows.size()); - for (std::size_t const index : *order) { - sorted.push_back(view.rows.at(index)); - if (grouped) { - runOf.push_back(view.runOf.at(index)); - } - } - view.rows = std::move(sorted); - view.runOf = std::move(runOf); -} - -TableView ScreenCore::tableView(ElementState const& element, Bindings const* bindings) { - DocNode const& node = *element.node; - RtScope const& scope = *element.scope; - TableView view; - sortedRows(element, bindings, view); - view.last = view.rows.size(); - ExprPtr const sizeExpr = node.prop("pageSize"); - if (!sizeExpr) { - return view; - } - // A `pageSize` of `null` does not page; one that is no positive integer is reported and does not page either. - Value const size = evalIn(scope, bindings, sizeExpr); - std::int64_t const* const perPage = size.asInt(); - if (size.isNull() || perPage == nullptr || *perPage < 1) { - if (!size.isNull()) { - report(pointerAppend(node.path, "pageSize"), - "pageSize is " + canonicalJson(size) + "; a page holds a positive whole number of rows"); - } - return view; - } - // A `page` of `null` is the first; one that is negative or not a whole number is reported and shows the first. - // One past the last is the last: a filter that shrinks the rows under the user is normal, not an error. - std::int64_t asked = 0; - if (ExprPtr const pageExpr = node.prop("page")) { - Value const page = evalIn(scope, bindings, pageExpr); - std::int64_t const* const index = page.asInt(); - if (index != nullptr && *index >= 0) { - asked = *index; - } else if (!page.isNull()) { - report(pointerAppend(node.path, "page"), - "page is " + canonicalJson(page) + "; a page is a whole number from 0"); - } - } - auto const total = static_cast(view.rows.size()); - view.pageCount = std::max(1, (total + *perPage - 1) / *perPage); - view.page = std::min(asked, view.pageCount - 1); - view.first = static_cast(std::min(total, view.page * *perPage)); - view.last = static_cast(std::min(total, (view.page + 1) * *perPage)); - return view; -} - -namespace { - -/// @brief A table's selection as its element value reads it: the bound `selection` when the key binds one, else -/// the table's own. A bound value that is not a list (`null` while state starts empty) selects nothing. -/// @param element The table's element. -/// @return A list of keys. Tracked. -[[nodiscard]] Value tableSelection(ElementState const& element) { - if (element.bound == nullptr) { - return element.selection.get(); - } - Value const bound = element.bound->get(); - return bound.asList() != nullptr ? bound : Value{ValueList{}}; -} -} // namespace - -[[nodiscard]] Value jsonTextValue(std::string_view text) { - auto const json = parseJson(text); - if (!json) { - return Value{}; - } - auto value = valueFromJson(*json); - return value ? *std::move(value) : Value{}; -} - -namespace { - -/// @brief One field of a form as a record: `value` (the encoded value, `null` while blank or invalid), `draft` (the -/// text), `valid`, `required`, `visible`, `readonly` and `errors`. Tracked. -/// @param field The field. -/// @return The record. -[[nodiscard]] Value formFieldValue(forms::FieldState const& field) { - ValueRecord record; - forms::Encoding const& encoding = field.encoded().get(); - Value value; - if (encoding.has_value() && encoding->has_value()) { - value = (*encoding)->value.isNull() ? jsonTextValue((*encoding)->json) : (*encoding)->value; - } - std::optional const& error = field.error().get(); - record.insert_or_assign("value", std::move(value)); - record.insert_or_assign("draft", Value{field.spec().kind == forms::FieldKind::Object || - field.spec().kind == forms::FieldKind::ObjectArray - ? std::string{} - : field.draft()}); - record.insert_or_assign("valid", Value{!error.has_value()}); - record.insert_or_assign("required", Value{field.required().get()}); - record.insert_or_assign("visible", Value{field.visible().get()}); - record.insert_or_assign("readonly", Value{field.readonly().get()}); - record.insert_or_assign("errors", - error.has_value() ? Value{ValueList{Value{error->message}}} : Value{ValueList{}}); - return Value{std::move(record)}; -} - -/// @brief A form's element values (spec 5 §6): `ready`, `body` (the record the form would submit, `null` while not -/// ready), `submitted` (whether a submission was sent), `pending`, and each field by its wire name. Tracked. -/// @param element The form's element. -/// @param name The value's name. -/// @return The value; `null` for a name the form does not have, or a form without a session. -[[nodiscard]] Value formValue(ElementState const& element, std::string_view name) { - forms::FormSession const* const form = element.form.get(); - if (form == nullptr) { - return Value{}; - } - if (name == "ready") { - return form->ready(); - } - if (name == "body") { - std::optional const body = form->body(); - return body.has_value() ? jsonTextValue(*body) : Value{}; - } - if (name == "submitted") { - return form->submitAttempts() > 0; - } - if (name == "pending") { - return form->pending(); - } - for (auto const& field : form->fields()) { - if (field->spec().name == name) { - return formFieldValue(*field); - } - } - return Value{}; -} -} // namespace - -Value ScreenCore::inputValue(ElementState const& element) const { - std::string_view const kind = element.node->kind; - if (kind == "checkbox") { - return elementValue(element, "checked"); - } - if (kind == "select") { - return elementValue(element, "selected"); - } - return elementValue(element, "value"); -} - -// NOLINTNEXTLINE(misc-no-recursion,readability-function-cognitive-complexity): one case per element value. -Value ScreenCore::elementValue(ElementState const& element, std::string_view name) const { - DocNode const& node = *element.node; - RtScope const& scope = *element.scope; - std::string_view const kind = node.kind; - auto const flagOf = [&](std::string_view key, bool fallback) -> Value { - ExprPtr const expr = node.prop(key); - if (!expr) { - return fallback; - } - Value const value = evalIn(scope, nullptr, expr); - bool const* const flag = value.asBool(); - return flag != nullptr && *flag; - }; - auto const errors = [&] -> Value { return element.errors->get(); }; - auto const count = [](Value const& list) -> Value { - ValueList const* const items = list.asList(); - return static_cast(items == nullptr ? 0 : items->size()); - }; - if (name == "visible" || name == "enabled") { - return flagOf(name, true); - } - if (name == "errors") { - return errors(); - } - if (name == "valid") { - Value const current = errors(); - ValueList const* const items = current.asList(); - return items == nullptr || items->empty(); - } - if (name == "shownErrors") { - RtScope const& policy = scope.policyScope(); - std::string const mode = policy.showErrors.empty() ? _doc->showErrors : policy.showErrors; - bool const submittedNow = policy.submitted != nullptr && policy.submitted->get(); - if (mode == "always" || (mode == "submit" && submittedNow) || - (mode != "submit" && (submittedNow || element.touched.get() || touchedWithin(element)))) { - return errors(); - } - return Value{ValueList{}}; - } - if (kind == "dialog" || kind == "drawer") { - if (name == "open") { - return node.prop("open") ? flagOf("open", false) : Value{element.open.get()}; - } - if (name == "ready") { - RtScope const* const inner = element.inner.get(); - return inner != nullptr && inner->ready(); - } - if (name == "submitted") { - return element.submitted.get(); - } - return Value{}; - } - if (kind == "table") { - if (name == "selection") { - return tableSelection(element); - } - if (name == "activeKey") { - return element.activeKey.get(); - } - if (name == "selectedCount") { - return count(tableSelection(element)); - } - if (name == "sort") { - return tableSort(element); - } - if (name == "viewCount" || name == "page" || name == "pageCount" || name == "pageFirst" || - name == "pageLast") { - return tablePageValue(element, name); - } - if (name == "sourceCount") { - return element.rows == nullptr ? Value{std::int64_t{0}} : count(element.rows->get()); - } - ExprPtr const rows = node.prop("rows"); - if ((name == "pending" || name == "error") && rows && rows->kind == ExprKind::Query) { - ScopeEnv const env{scope, nullptr}; - return env.control(name == "pending" ? ExprKind::Pending : ExprKind::Error, rows->name); - } - return name == "pending" ? Value{false} : Value{}; - } - if (kind == "tabs") { - // The shown tab's id: the bound one, else the user's own pick, else the first tab's. - ExprPtr const selected = node.prop("selected"); - if (name != "selected") { - return Value{}; - } - if (selected && (selected->kind != ExprKind::Literal || !selected->literal.isNull())) { - return evalIn(scope, nullptr, selected); - } - if (Value picked = element.draft.get(); !picked.isNull()) { - return picked; - } - auto const tabs = node.partList("tabs"); - return tabs.empty() || tabs.front()->id.empty() ? Value{} : Value{tabs.front()->id}; - } - if (kind == "form") { - return formValue(element, name); - } - if (name == "draft") { - return element.draft.get(); - } - if (name == "dirty") { - return element.edited.get(); - } - if (name == "focused") { - return element.focused.get(); - } - if (name == "touched") { - return element.touched.get(); - } - if (name == "checked" || name == "selected") { - return element.bound != nullptr ? element.bound->get() : element.draft.get(); - } - if (name == "selectedOption") { - Value const selected = elementValue(element, "selected"); - ValueList const* const options = element.rows == nullptr ? nullptr : element.rows->get().asList(); - if (options != nullptr && !selected.isNull()) { - for (Value const& option : *options) { - if (optionKey(option) == selected) { - return option; - } - } - } - return Value{}; - } - if (name == "value") { - if (element.bound != nullptr) { - return element.bound->get(); - } - return element.committed.get(); - } - return Value{}; -} - -bool ScreenCore::touchedWithin(ElementState const& element) { - if (element.node->kind != "group") { - return false; - } - std::string const inside = element.node->path + "/"; - return std::ranges::any_of(element.scope->elements, [&inside](std::unique_ptr const& other) { - return other->node->path.starts_with(inside) && other->touched.get(); - }); -} - -// --- Commands -------------------------------------------------------------------------------------------------- - -// NOLINTBEGIN(misc-no-recursion): command lists nest -void ScreenCore::runList(Commands const& commands, CommandCtx const& ctx, Done done) { - if (!done) { - done = [](bool) {}; - } - if (commands.empty()) { - done(true); - return; - } - struct Join { - std::size_t left = 0; - bool ok = true; - Done done; - }; - if (recording) { - logList(commands); - } - auto const join = std::make_shared(Join{.left = commands.size() + 1, .ok = true, .done = std::move(done)}); - auto const finish = [join](bool succeeded) { - join->ok = join->ok && succeeded; - if (--join->left == 0) { - join->done(join->ok); - } - }; - for (Command const& command : commands) { - runOne(command, ctx, finish); - } - finish(true); -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per command of ui/1. -void ScreenCore::runOne(Command const& command, CommandCtx const& ctx, Done done) { - if (!done) { - done = [](bool) {}; - } - RtScope const& scope = *ctx.scope; - auto const eval = [&](ExprPtr const& expr) { return evalIn(scope, ctx.bindings.get(), expr); }; - auto const finish = [&done](bool succeeded) { done(succeeded); }; - switch (command.kind) { - case CommandKind::Set: - runSet(command, ctx, done); - return; - case CommandKind::Reset: - runReset(command, ctx, done); - return; - case CommandKind::Run: - runMutation(command, ctx, std::move(done)); - return; - case CommandKind::Refetch: { - // A loaded document's `refetch` names a query in scope (`loadDocument` checks it), as `run` names a - // mutation and `open` a dialog. - scope.find(command.target)->query->refetch(); - finish(true); - return; - } - case CommandKind::Open: - case CommandKind::Close: { - ElementState* target = nullptr; - if (command.kind == CommandKind::Close && command.target == "self") { - // `self` is the innermost dialog or drawer whose content holds the command, found lexically. A - // component's fallback scope has no parent, so the walk stops at its boundary as its names do. - RtScope const* walk = &scope; - while (walk->owner == nullptr && walk->parent) { - walk = walk->parent.get(); - } - target = walk->owner; - if (target == nullptr && walk != rootScope.lock().get()) { - report(command.path, "`close: self` inside a component names no dialog or drawer"); - finish(false); - return; - } - if (target == nullptr) { - finish((host != nullptr && host->closeSelf(_doc->id, std::nullopt)) || - unsupported(command, "`close: self`")); - return; - } - } else { - target = scope.find(command.target)->element; - } - ElementState& element = *target; - if (element.node->prop("open")) { - report(command.path, "the dialog's `open` is bound to an expression"); - finish(false); - return; - } - bool const opening = command.kind == CommandKind::Open; - if (opening && !element.open.peek()) { - element.submitted.set(false); - } - session.noteWrite(); - element.open.set(opening); - finish(true); - return; - } - case CommandKind::Navigate: { - NavigateRequest const request{ - .screen = command.target, - .route = eval(command.extra), - .params = eval(command.value), - .as = command.option, - .call = false, - }; - if (host == nullptr) { - finish(unsupported(command, "`navigate`")); - return; - } - // A navigation without `onResult` and `onCancel` asks for no answer, so it files no call: the screen it - // opens answers nobody, and its `return` is the application's. - if (command.commands.empty() && command.alternative.empty()) { - finish(host->navigate(request, {}, {}) || unsupported(command, "`navigate`")); - return; - } - std::weak_ptr const weak = ctx.scope; - CommandCtx const kept = detached(ctx); - auto onResult = [this, weak, kept, list = &command.commands](Value const& result) { - if (auto const held = weak.lock()) { - auto const bindings = std::make_shared(*kept.bindings); - bindings->push_back(Binding{.name = "event", .read = [result] { return result; }}); - CommandCtx const next{ - .scope = held, - .bindings = bindings, - .cancelClose = kept.cancelClose, - .boundary = kept.boundary, - }; - runtime().batch([&] { runList(*list, next, {}); }); - } - }; - auto onCancel = [this, weak, kept, list = &command.alternative] { - if (auto const held = weak.lock()) { - CommandCtx next = kept; - next.scope = held; - runtime().batch([&] { runList(*list, next, {}); }); - } - }; - finish(host->navigate(request, std::move(onResult), std::move(onCancel)) || - unsupported(command, "`navigate`")); - return; - } - case CommandKind::Return: - finish(host != nullptr && host->closeSelf(_doc->id, eval(command.value)) - ? true - : unsupported(command, "`return`")); - return; - case CommandKind::Focus: - if (focusTarget(command, scope, ctx.bindings.get())) { - finish(true); - return; - } - report(command.path, "`" + command.target + "` is not mounted"); - finish(false); - return; - case CommandKind::Host: - runHostCommand(command, ctx, done); - return; - case CommandKind::SwitchBackend: { - std::weak_ptr const weak = ctx.scope; - auto committed = [this, weak, target = command.target, path = command.path, - done](std::expected const& outcome) { - if (!weak.lock()) { - return; - } - if (!outcome) { - report(path, "backendSwitchFailed: " + outcome.error()); - done(false); - return; - } - session.backendChanged(target); - done(true); - }; - if (host != nullptr && host->switchBackend(command.target, std::move(committed))) { - return; - } - report(command.path, "backend `" + command.target + "` is not listed"); - finish(false); - return; - } - case CommandKind::ResetPrefs: { - ValueRecord prefsNow = prefs.peek(); - if (command.target == "all") { - prefsNow = prefDefaults; - } else if (auto const found = prefDefaults.find(command.target); found != prefDefaults.end()) { - prefsNow.insert_or_assign(command.target, found->second); - } - prefs.set(std::move(prefsNow)); - if (host != nullptr) { - host->resetPrefs(_doc->id, command.target); - } - finish(true); - return; - } - case CommandKind::SetLocale: - session.setLocale(command.target); - if (host != nullptr) { - host->setLocale(command.target); - } - finish(true); - return; - case CommandKind::SetContext: { - // The shell checks the value against the switcher's options; with no switcher it is unsupported. - Value const requested = eval(command.value); - if (session.requestContext(requested)) { - finish(true); - } else { - report(command.path, - "`setContext` was refused: " + std::string{session.can("context") - ? "the value is not one of the scope's options" - : "no scope switcher is declared"}); - finish(false); - } - return; - } - case CommandKind::Notify: { - std::string const text = textOf(eval(command.value), ctx.scope->formatting()); - finish(host != nullptr && host->notify(text, command.option) ? true : unsupported(command, "`notify`")); - return; - } - case CommandKind::Seq: { - // A step that waits for a reply keeps the rest of the sequence in that reply's handler, which the - // dispatcher may hold past the screen: the sequence holds its scope weakly and stops once it is gone. - CommandCtx const inner = detached(CommandCtx{ - .scope = nullptr, - .bindings = std::make_shared(*ctx.bindings), - .cancelClose = ctx.cancelClose, - .boundary = ctx.boundary, - }); - std::weak_ptr const weak = ctx.scope; - auto const step = std::make_shared>(); - *step = [this, inner, weak, list = &command.commands, done = std::move(done), - weakStep = std::weak_ptr>{step}](std::size_t index) { - auto const held = weak.lock(); - if (index == list->size() || !held) { - done(held != nullptr); - return; - } - auto const self = weakStep.lock(); - CommandCtx current = inner; - current.scope = held; - runOne(list->at(index), current, [self, index, done](bool succeeded) { - if (!succeeded) { - done(false); - return; - } - (*self)(index + 1); - }); - }; - (*step)(0); - return; - } - case CommandKind::All: { - CommandCtx const inner{ - .scope = ctx.scope, - .bindings = std::make_shared(*ctx.bindings), - .cancelClose = ctx.cancelClose, - .boundary = ctx.boundary, - }; - runList(command.commands, inner, std::move(done)); - return; - } - case CommandKind::If: { - Value const condition = eval(command.value); - bool const* const flag = condition.asBool(); - if (flag == nullptr) { - finish(true); - return; - } - runList(*flag ? command.commands : command.alternative, ctx, std::move(done)); - return; - } - case CommandKind::CancelClose: - *ctx.cancelClose = true; - finish(true); - return; - case CommandKind::Retry: - // `retry` is valid only inside a boundary's `error`, which is lowered with its boundary. - for (QueryRuntime* const query : ctx.boundary->queries) { - if (!runtime().untracked([&] { return query->error(); }).isNull()) { - query->refetch(); - } - } - finish(true); - return; - case CommandKind::SignIn: { - NameRef const* const found = scope.find(command.target); - Value const reply = found != nullptr && found->category == NameCategory::Mutation - ? runtime().untracked([&] { return found->mutation->result(); }) - : Value{}; - session.clear(); - finish(host != nullptr && host->signIn(reply) ? true : unsupported(command, "`signIn`")); - return; - } - case CommandKind::SignOut: - session.clear(); - if (host != nullptr) { - host->signOut(); - } - finish(true); - return; - case CommandKind::Upload: - case CommandKind::Download: - default: - runTransfer(command, ctx, std::move(done)); - return; - } -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): a single run, or a run per list item. -void ScreenCore::runMutation(Command const& command, CommandCtx const& ctx, Done done) const { - RtScope const& scope = *ctx.scope; - MutationRuntime& mutation = *scope.find(command.target)->mutation; - RtScope const& policy = scope.policyScope(); - if (policy.submitted != nullptr) { - policy.submitted->set(true); - } - if (policy.owner != nullptr && !runtime().untracked([&] { return policy.ready(); })) { - done(false); - return; - } - RtScope const& declaring = *[&] -> RtScope const* { - for (RtScope const* candidate = &scope; candidate != nullptr; candidate = candidate->parent.get()) { - if (candidate->names.contains(command.target)) { - return candidate; - } - } - return &scope; - }(); - auto const bodyFor = [&](Bindings const& bindings) { - if (command.value) { - return evalIn(scope, &bindings, command.value); - } - if (mutation.decl().body) { - return evalIn(declaring, &bindings, mutation.decl().body); - } - return Value{ValueRecord{}}; - }; - if (!command.extra) { - Value body = bodyFor(*ctx.bindings); - mutation.run(std::move(body), std::make_shared(*ctx.bindings), - [bindings = ctx.bindings, bindAs = command.binding, done = std::move(done)](bool succeeded, - Value const& reply) { - if (succeeded && !bindAs.empty()) { - bindings->push_back(Binding{.name = bindAs, .read = [reply] { return reply; }}); - } - done(succeeded); - }); - return; - } - Value const each = evalIn(scope, ctx.bindings.get(), command.extra); - ValueList const items = each.asList() == nullptr ? ValueList{} : *each.asList(); - if (items.empty()) { - done(true); - return; - } - struct Each { - std::size_t left = 0; - bool ok = true; - Done done; - }; - auto const state = std::make_shared(Each{.left = items.size(), .ok = true, .done = std::move(done)}); - std::vector bodies; - std::vector> bound; - for (Value const& item : items) { - Bindings bindings = *ctx.bindings; - if (!command.binding.empty()) { - bindings.push_back(Binding{.name = command.binding, .read = [item] { return item; }}); - } - bodies.push_back(bodyFor(bindings)); - bound.push_back(std::make_shared(std::move(bindings))); - } - if (mutation.decl().concurrency != Concurrency::Exclusive) { - for (std::size_t index = 0; index < bodies.size(); ++index) { - mutation.run(bodies.at(index), bound.at(index), [state](bool succeeded, Value const&) { - state->ok = state->ok && succeeded; - if (--state->left == 0) { - state->done(state->ok); - } - }); - } - return; - } - // An exclusive mutation refuses a run while another is in flight, so its elements go one after another. - auto const step = std::make_shared>(); - *step = [&mutation, bodies, bound, state, - weakStep = std::weak_ptr>{step}](std::size_t index) { - if (index == bodies.size()) { - state->done(state->ok); - return; - } - auto const self = weakStep.lock(); - mutation.run(bodies.at(index), bound.at(index), [self, state, index](bool succeeded, Value const&) { - if (!succeeded) { - state->done(false); - return; - } - (*self)(index + 1); - }); - }; - (*step)(0); -} - -// NOLINTEND(misc-no-recursion) -void ScreenCore::writeSlot(StateSlot& slot, std::span within, Value value, Command const& command, - Done const& done) { - slot.scope->core.initState(*slot.scope, slot); - Type const& type = slot.decl->type; - if (within.empty() && !type.isAny() && !type.admits(value)) { - report(command.path, "`set` writes a value that is not a " + type.name()); - done(false); - return; - } - Value next = withPath(slot.value->peek(), within, std::move(value)); - session.noteWrite(); - slot.value->set(std::move(next)); - done(true); -} - -void ScreenCore::runSetApp(Command const& command, std::span rest, Value value, Done const& done) { - if (RtScope const* const app = session.appScope(); app != nullptr && !rest.empty()) { - NameRef const* const named = app->find(rest.front()); - if (named != nullptr && named->category == NameCategory::State) { - writeSlot(*named->state, rest.subspan(1), std::move(value), command, done); - return; - } - report(command.path, "`app." + rest.front() + "` is not state of the app document"); - done(false); - return; - } - std::string name; - for (std::string const& segment : rest) { - name += name.empty() ? segment : "." + segment; - } - done(host != nullptr && host->setAppValue(name, value) ? true : unsupported(command, "`set` of `app`")); -} - -void ScreenCore::runSet(Command const& command, CommandCtx const& ctx, Done const& done) { - RtScope const& scope = *ctx.scope; - auto path = splitPath(command.target); - if (!path || path->empty()) { - done(false); - return; - } - std::string const head = path->front(); - std::span const rest = std::span{*path}.subspan(1); - Value value = evalIn(scope, ctx.bindings.get(), command.value); - if (head == "app") { - runSetApp(command, rest, std::move(value), done); - return; - } - NameRef const* const found = scope.find(head); - if (found != nullptr && found->category == NameCategory::State) { - writeSlot(*found->state, rest, std::move(value), command, done); - return; - } - if (found != nullptr && found->category == NameCategory::Element) { - ElementState& element = *found->element; - session.noteWrite(); - element.draft.set(value); - if (element.bound == nullptr) { - element.committed.set(std::move(value)); - } - done(true); - return; - } - report(command.path, "`set` names nothing writable here"); - done(false); -} - -void ScreenCore::runReset(Command const& command, CommandCtx const& ctx, Done const& done) { - RtScope const& scope = *ctx.scope; - NameRef const* const found = scope.find(command.target); - auto const resetStates = [this](RtScope const& owner) { - for (auto const& slot : owner.states) { - if (slot->value) { - Value init = runtime().untracked([&] { return evalIn(owner, nullptr, slot->decl->init); }); - slot->value->set(std::move(init)); - } - } - for (auto const& element : owner.elements) { - element->draft.set(element->bound != nullptr ? runtime().untracked([&] { return element->bound->get(); }) - : Value{}); - element->committed.set(Value{}); - element->edited.set(false); - element->touched.set(false); - } - }; - bool known = true; - session.noteWrite(); - if (found != nullptr && found->category == NameCategory::State) { - StateSlot& slot = *found->state; - initState(*slot.scope, slot); - slot.value->set(runtime().untracked([&] { return evalIn(*slot.scope, nullptr, slot.decl->init); })); - } else if (found != nullptr && found->category == NameCategory::Element) { - ElementState& element = *found->element; - element.submitted.set(false); - if (RtScope const* const inner = element.inner.peek()) { - resetStates(*inner); - } - } else { - report(command.path, "`reset` names no state or dialog here"); - known = false; - } - done(known); -} - -void ScreenCore::runHostCommand(Command const& command, CommandCtx const& ctx, Done const& done) { - // A command limited to other documents is one this document cannot see: missing, and nothing runs. - if (!session.hostNameIn(command.target, doc().id)) { - report(command.path, "host command `" + command.target + "` is missing"); - done(false); - return; - } - Value const args = evalIn(*ctx.scope, ctx.bindings.get(), command.value); - if (auto const& run = session.hostCommandRunner()) { - HostCommandResult const result = run(command.target, args); - if (result.kind == HostCommandResult::Kind::Missing) { - report(command.path, "host command `" + command.target + "` is missing"); - } else if (result.kind == HostCommandResult::Kind::Refused) { - report(command.path, result.reason); - } - done(result.kind == HostCommandResult::Kind::Ran); - return; - } - bool const known = host != nullptr && host->hostCommand(command.target, args); - if (!known) { - report(command.path, "host command `" + command.target + "` is missing"); - } - done(known); -} - -namespace { - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): a download and an upload, each settled. -/// @brief A transfer's share of its screen's pending count. -/// -/// A transfer is pending from the host accepting it to its settle: its completion carries on the command list that -/// started it, which the close protocol and save-and-close wait for. The count is taken once the host accepts, so a -/// refused transfer never counts, and a host that settles before it returns leaves nothing taken. It is given back -/// once, also when the transfer settles after its scope is gone, but not after the screen itself is gone, since the -/// count went with it. -class TransferHold { -public: - /// @brief A hold that counts nothing yet. - /// @param core The screen whose count it moves. - /// @param alive Expires with the screen. - TransferHold(ScreenCore& core, std::weak_ptr alive) : _core{&core}, _alive{std::move(alive)} {} - - /// @brief Counts the transfer, unless it has already settled. - void take() { - if (_state == State::NotTaken) { - _state = State::Taken; - _core->addPending(1); - } - } - - /// @brief Gives the count back, if one was taken and the screen is still there; the transfer counts no more. - void release() { - if (_state == State::Taken && !_alive.expired()) { - _core->addPending(-1); - } - _state = State::Released; - } - -private: - enum class State : std::uint8_t { NotTaken, Taken, Released }; - - ScreenCore* _core; - std::weak_ptr _alive; - State _state = State::NotTaken; -}; - -} // namespace - -[[nodiscard]] std::string base64Encode(std::string_view bytes) { - static constexpr std::string_view kAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - std::string out; - out.reserve(((bytes.size() + 2) / 3) * 4); - for (std::size_t index = 0; index < bytes.size(); index += 3) { - std::size_t const left = std::min(3, bytes.size() - index); - std::uint32_t group = 0; - for (std::size_t offset = 0; offset < 3; ++offset) { - group <<= 8U; - if (offset < left) { - group |= static_cast(bytes.at(index + offset)); - } - } - for (std::size_t digit = 0; digit < 4; ++digit) { - out.push_back(digit <= left ? kAlphabet.at((group >> (18U - (6U * digit))) & 0x3FU) : '='); - } - } - return out; -} - -[[nodiscard]] std::optional base64Decode(std::string_view text) { - while (!text.empty() && text.back() == '=') { - text.remove_suffix(1); - } - if (text.size() % 4 == 1) { - return std::nullopt; - } - auto const digitOf = [](char chr) -> int { - if (chr >= 'A' && chr <= 'Z') { - return chr - 'A'; - } - if (chr >= 'a' && chr <= 'z') { - return chr - 'a' + 26; - } - if (chr >= '0' && chr <= '9') { - return chr - '0' + 52; - } - if (chr == '+') { - return 62; - } - return chr == '/' ? 63 : -1; - }; - std::string out; - out.reserve((text.size() * 3) / 4); - std::uint32_t group = 0; - int bits = 0; - for (char const chr : text) { - int const digit = digitOf(chr); - if (digit < 0) { - return std::nullopt; - } - group = (group << 6U) | static_cast(digit); - bits += 6; - if (bits >= 8) { - bits -= 8; - out.push_back(static_cast((group >> static_cast(bits)) & 0xFFU)); - } - } - return out; -} - -[[nodiscard]] std::size_t base64Size(std::string_view text) { - while (!text.empty() && text.back() == '=') { - text.remove_suffix(1); - } - return (text.size() * 3) / 4; -} - -[[nodiscard]] std::string sizeText(std::size_t bytes) { - constexpr std::size_t kKiB = 1024; - if (bytes < kKiB) { - return std::to_string(bytes) + " bytes"; - } - bool const mebi = bytes >= kKiB * kKiB; - std::size_t const unit = mebi ? kKiB * kKiB : kKiB; - // One decimal place, rounded half up, and none when it is zero. - std::size_t const tenths = ((bytes * 10) + (unit / 2)) / unit; - std::string text = std::to_string(tenths / 10); - if (tenths % 10 != 0) { - text += "." + std::to_string(tenths % 10); - } - return text + (mebi ? " MiB" : " KiB"); -} - -[[nodiscard]] std::expected inlineBytes(Value const& value) { - if (std::string const* const text = value.asString()) { - if (std::optional bytes = base64Decode(*text)) { - return *std::move(bytes); - } - return std::unexpected(std::string{"the text is not base64"}); - } - if (ValueList const* const list = value.asList()) { - std::string bytes; - bytes.reserve(list->size()); - for (Value const& item : *list) { - std::int64_t const* const byte = item.asInt(); - if (byte == nullptr || *byte < 0 || *byte > 255) { - return std::unexpected(std::string{"a byte list holds integers 0 to 255"}); - } - bytes.push_back(static_cast(static_cast(*byte))); - } - return bytes; - } - return std::unexpected(std::string{"inline bytes are base64 text or a list of bytes"}); -} - -void ScreenCore::runTransfer(Command const& command, CommandCtx const& ctx, Done done) { - Value const file = evalIn(*ctx.scope, ctx.bindings.get(), command.value); - if (command.kind == CommandKind::Download) { - runDownload(command, ctx, file, std::move(done)); - } else { - runUpload(command, ctx, file, std::move(done)); - } -} - -void ScreenCore::runDownload(Command const& command, CommandCtx const& ctx, Value const& file, Done done) { - Value const name = evalIn(*ctx.scope, ctx.bindings.get(), command.extra); - auto const hold = std::make_shared(*this, _alive); - auto const settled = [this, weak = std::weak_ptr{ctx.scope}, target = command.target, - preview = command.option == "preview", done, - hold](std::expected const& reply) { - auto const held = weak.lock(); - if (!held) { - hold->release(); - return; - } - runtime().batch([&] { - bool const succeeded = reply.has_value(); - NameRef const* const found = succeeded && preview ? held->find(target) : nullptr; - if (found != nullptr && found->category == NameCategory::State) { - initState(*found->state->scope, *found->state); - session.noteWrite(); - found->state->value->set(*reply); - } - done(succeeded); - hold->release(); - }); - }; - if (command.bytes) { - std::optional const inlined = inlineDownload(command, ctx, file, name); - if (!inlined) { - done(false); - return; - } - if (host == nullptr || !host->saveFile(*inlined, command.option, settled)) { - unsupported(command, "`download`"); - done(false); - return; - } - hold->take(); - return; - } - if (host == nullptr || !host->download(file, command.option, name, settled)) { - unsupported(command, "`download`"); - done(false); - return; - } - hold->take(); -} - -// Inline bytes are checked before the host is asked: content over the cap, or that does not decode, never reaches it. -std::optional ScreenCore::inlineDownload( - Command const& command, CommandCtx const& ctx, - // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the command's `file` and `name`, in its order. - Value const& file, Value const& name) { - std::size_t const cap = session.options().maxInlineFileBytes; - std::size_t size = 0; - if (std::string const* const text = file.asString()) { - size = base64Size(*text); - } else if (ValueList const* const list = file.asList()) { - size = list->size(); - } - std::expected bytes = size > cap ? std::unexpected(std::string{}) : inlineBytes(file); - if (size > cap || (bytes && bytes->size() > cap)) { - report(command.path, "download: " + sizeText(bytes ? bytes->size() : size) + " is over the " + sizeText(cap) + - " inline cap; serve it through the file store"); - return std::nullopt; - } - if (!bytes) { - report(command.path, "download: " + bytes.error()); - return std::nullopt; - } - return InlineFile{ - .name = textOf(name, ctx.scope->formatting()), - .mediaType = command.mediaType - ? textOf(evalIn(*ctx.scope, ctx.bindings.get(), command.mediaType), ctx.scope->formatting()) - : std::string{}, - .bytes = *std::move(bytes), - }; -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one branch per outcome an upload can have. -void ScreenCore::runUpload(Command const& command, CommandCtx const& ctx, Value const& file, Done done) { - RtScope const& scope = *ctx.scope; - std::weak_ptr const weak = ctx.scope; - auto const hold = std::make_shared(*this, _alive); - NameRef const* const transferName = command.transfer.empty() ? nullptr : scope.find(command.transfer); - TransferState* const transfer = - transferName != nullptr && transferName->category == NameCategory::Transfer ? transferName->transfer : nullptr; - auto const progress = [weak, transfer](Value fraction) { - if (weak.lock() && transfer != nullptr) { - transfer->progress.set(std::move(fraction)); - } - }; - // Settles with the members the mutation's body gets beside its own (the reference or the inline file), or the - // failure. - auto const settled = [this, weak, kept = detached(ctx), transfer, command = &command, done, - hold](std::expected reply) { - auto const held = weak.lock(); - if (!held) { - hold->release(); - return; - } - runtime().batch([&] { - if (transfer != nullptr) { - transfer->pending.set(false); - transfer->error.set(reply ? Value{} : Value{reply.error()}); - } - if (!reply) { - done(false); - hold->release(); - return; - } - NameRef const* const found = held->find(command->target); - // The mutation's body cannot name the reference (a body is checked where the mutation is declared), - // so the reference is added to it under `as`, `file` by default. - MutationRuntime& mutation = *found->mutation; - Value const base = evalIn(*held, kept.bindings.get(), mutation.decl().body); - ValueRecord fields = base.asRecord() == nullptr ? ValueRecord{} : *base.asRecord(); - for (auto& [member, value] : *reply) { - fields.insert_or_assign(member, std::move(value)); - } - // The run takes its own count before this one is given back, so pending never reads zero in between. - mutation.run(Value{std::move(fields)}, std::make_shared(*kept.bindings), - [done](bool succeeded, Value const&) { done(succeeded); }); - hold->release(); - }); - }; - if (host == nullptr) { - unsupported(command, "`upload`"); - done(false); - return; - } - if (transfer != nullptr) { - transfer->pending.set(true); - transfer->progress.set(Value{std::int64_t{0}}); - transfer->error.set(Value{}); - } - NameRef const* const target = scope.find(command.target); - UploadRequest request{.file = file, .modelType = {}, .action = {}}; - if (target != nullptr && target->category == NameCategory::Mutation && target->mutation != nullptr) { - request.modelType = target->mutation->typeId(); - request.action = target->mutation->decl().action; - } - std::string const member = command.binding.empty() ? std::string{"file"} : command.binding; - bool started = false; - if (command.bytes) { - std::size_t const cap = session.options().maxInlineFileBytes; - started = host->readFile( - file, cap, - [this, settled, progress, cap, member, command = &command](std::expected read) { - if (!read) { - settled(std::unexpected(read.error())); - return; - } - if (read->bytes.size() > cap) { - // The host should have refused it; the cap holds whether or not it did. - std::string why = "upload: " + sizeText(read->bytes.size()) + " is over the " + sizeText(cap) + - " inline cap; send it through the file store"; - report(command->path, why); - settled(std::unexpected(std::move(why))); - return; - } - progress(Value{std::int64_t{1}}); - ValueRecord added; - added.insert_or_assign(member, Value{base64Encode(read->bytes)}); - if (!command->nameAs.empty()) { - added.insert_or_assign(command->nameAs, Value{read->name}); - } - if (!command->typeAs.empty()) { - added.insert_or_assign(command->typeAs, Value{read->mediaType}); - } - settled(std::move(added)); - }); - } else { - started = host->uploadFor(request, progress, [settled, member](std::expected reference) { - if (!reference) { - settled(std::unexpected(reference.error())); - return; - } - ValueRecord added; - added.insert_or_assign(member, *std::move(reference)); - settled(std::move(added)); - }); - } - if (!started) { - if (transfer != nullptr) { - transfer->pending.set(false); - transfer->progress.set(Value{}); - } - unsupported(command, "`upload`"); - done(false); - return; - } - hold->take(); -} - -} // namespace detail - -namespace detail { -namespace { - -// --- Lowering -------------------------------------------------------------------------------------------------- - -/// @brief A value as a `bool` property: `true` only for `true`. -/// @param value The value. -/// @param format Unused. -/// @return It. -[[nodiscard]] bool boolOf(Value const& value, FormatContext const& format) { - static_cast(format); - bool const* const flag = value.asBool(); - return flag != nullptr && *flag; -} - -/// @brief A value as a text property. -/// @param value The value. -/// @param format The formatting facts. -/// @return Its text. -[[nodiscard]] std::string stringOf(Value const& value, FormatContext const& format) { return textOf(value, format); } -} // namespace - -[[nodiscard]] std::string componentText(Value const& value, std::string_view type, FormatContext const& format) { - if (type == "json") { - return canonicalJson(value); - } - if (type == "int" || type == "exact") { - if (std::int64_t const* const whole = value.asInt()) { - return std::to_string(*whole); - } - // A value that cannot be rounded at its own places is written as its exact JSON, never clamped. - if (Decimal const* const number = value.asDecimal()) { - return detail::decimalText(number->value, static_cast(number->value.decimalPlaces.value)) - .value_or(canonicalJson(value)); - } - if (Quantity const* const quantity = value.asQuantity()) { - auto const text = - detail::decimalText(quantity->value, static_cast(quantity->value.decimalPlaces.value)); - return text ? *text + " " + quantity->unit : canonicalJson(value); - } - } - return textOf(value, format); -} - -namespace { - -/// @brief An exact rational as the nearest double, unrounded. -/// -/// `Rational::toDouble` rounds to the value's own places, which is a display reading: `29 / 100` keeps its operands' -/// 0 places and would read as 0. The view tree wants the magnitude, so the lowering reads it here. -/// @param value The rational. -/// @return Its numerator divided by its denominator. -[[nodiscard]] double realOf(math::Rational const& value) noexcept { - return static_cast(value.numerator) / static_cast(value.denominator); -} -} // namespace - -[[nodiscard]] double componentNumber(Value const& value) { - if (std::int64_t const* const whole = value.asInt()) { - return static_cast(*whole); - } - if (Decimal const* const number = value.asDecimal()) { - return realOf(number->value); - } - if (Quantity const* const quantity = value.asQuantity()) { - return realOf(quantity->value); - } - return 0.0; -} - -[[nodiscard]] Value componentPayload(std::string const& payload, Type const* type) { - std::string_view const text{payload}; - if (text.starts_with("i:")) { - std::int64_t whole = 0; - std::string_view const digits = text.substr(2); - char const* const last = std::to_address(digits.end()); - auto const [end, error] = std::from_chars(std::to_address(digits.begin()), last, whole); - if (error == std::errc{} && end == last) { - return Value{whole}; - } - } - if (text.starts_with("s:")) { - return Value{std::string{text.substr(2)}}; - } - if (auto json = parseJson(text); json && type != nullptr) { - if (auto value = valueFromJson(*json, *type)) { - return std::move(*value); - } - } - return Value{payload}; -} - -[[nodiscard]] std::int64_t intOf(Value const& value, std::int64_t fallback) { - if (std::int64_t const* const number = value.asInt()) { - return *number; - } - if (Decimal const* const number = value.asDecimal()) { - // Integer division truncates toward zero, and reads the exact value rather than one rounded to its places. - return number->value.numerator / number->value.denominator; - } - return fallback; -} - -namespace { - -/// @brief A text role by name. -/// @param name `normal`, `muted`, `heading` (or `title`), `section`, `error`, `success`, `mono`, `display`, `small`, -/// `overline`, `caption`, `label`, `headline`. -/// @return The role; `nullopt` for any other name. -[[nodiscard]] std::optional roleNamed(std::string_view name) { - if (name == "normal") { - return TextRole::Normal; - } - if (name == "muted") { - return TextRole::Muted; - } - if (name == "heading" || name == "title") { - return TextRole::Heading; - } - if (name == "section") { - return TextRole::Section; - } - if (name == "error") { - return TextRole::Error; - } - if (name == "success") { - return TextRole::Success; - } - if (name == "mono") { - return TextRole::Mono; - } - if (name == "display") { - return TextRole::Display; - } - if (name == "small") { - return TextRole::Small; - } - if (name == "overline") { - return TextRole::Overline; - } - if (name == "caption") { - return TextRole::Caption; - } - if (name == "label") { - return TextRole::Label; - } - if (name == "headline") { - return TextRole::Headline; - } - return std::nullopt; -} - -/// @brief What a role that names none is told: the names `roleNamed` reads. -constexpr std::string_view kRoleNames = - "a role is normal, muted, heading, section, error, success, mono, display, small, overline, caption, label or " - "headline"; - -/// @brief A text role by name, as `roleNamed` reads it. -/// @param value The name. -/// @param format Unused. -/// @return The role; `Normal` for any other name. -[[nodiscard]] TextRole roleOf(Value const& value, FormatContext const& format) { - return roleNamed(textOf(value, format)).value_or(TextRole::Normal); -} - -/// @brief A tone by name. -/// @param value `neutral`, `info`, `ok` (or `success`), `warn` (or `warning`), `err` (or `error`). -/// @param format Unused. -/// @return The tone; `Neutral` for anything else. -[[nodiscard]] Tone toneOf(Value const& value, FormatContext const& format) { - std::string const text = textOf(value, format); - if (text == "info") { - return Tone::Info; - } - if (text == "ok" || text == "success") { - return Tone::Ok; - } - if (text == "warn" || text == "warning") { - return Tone::Warn; - } - if (text == "err" || text == "error") { - return Tone::Err; - } - return Tone::Neutral; -} -} // namespace - -[[nodiscard]] std::optional toneNamed(Value const& value) { - if (value.isNull()) { - return Tone::Neutral; - } - static constexpr std::array, 5> kTones = { - { - {"neutral", Tone::Neutral}, - {"info", Tone::Info}, - {"ok", Tone::Ok}, - {"warn", Tone::Warn}, - {"err", Tone::Err}, - }, - }; - if (std::string const* const text = value.asString()) { - // A loop, not std::ranges::find: an array's iterator is a pointer on some standard libraries and not on - // others, so `auto` there reads differently to each. - for (auto const& [name, tone] : kTones) { - if (name == *text) { - return tone; - } - } - } - return std::nullopt; -} - -[[nodiscard]] std::vector spansOf(Value const& value, FormatContext const& format, bool& dropped, - bool* badTone) { - std::vector spans; - if (value.isNull()) { - return spans; - } - ValueList const* const runs = value.asList(); - if (runs == nullptr) { - dropped = true; - return spans; - } - auto const flag = [](Value const* field) { - bool const* const set = field != nullptr ? field->asBool() : nullptr; - return set != nullptr && *set; - }; - for (Value const& run : *runs) { - if (run.asRecord() == nullptr) { - if (run.isNull() || run.asList() != nullptr) { - dropped = true; - } else { - spans.push_back(TextSpan{.text = textOf(run, format)}); - } - continue; - } - Value const* const text = run.field("text"); - if (text == nullptr) { - dropped = true; - continue; - } - Tone tone = Tone::Neutral; - if (Value const* const named = run.field("tone")) { - if (std::optional const known = toneNamed(*named)) { - tone = *known; - } else if (badTone != nullptr) { - *badTone = true; - } - } - spans.push_back(TextSpan{ - .text = textOf(*text, format), - .strong = flag(run.field("strong")), - .mono = flag(run.field("mono")), - .tone = tone, - .action = flag(run.field("action")), - }); - } - return spans; -} - -namespace { - -/// @brief Whether a scope declares any name, so a node in it reads names the screen's own scope lacks. -/// @param scope The scope. -/// @return True when it declares a model, state, let, query, mutation, watch or check. -[[nodiscard]] bool declaresNames(ScopeDecl const& scope) noexcept { - return !(scope.models.empty() && scope.state.empty() && scope.lets.empty() && scope.queries.empty() && - scope.mutations.empty() && scope.watches.empty() && scope.checks.empty()); -} - -/// @brief What a span list with a run it drops is told. -constexpr std::string_view kSpansReason = - "spans is a list of runs, each a value or a record with `text`; a list, a null or a record without `text` is " - "dropped"; - -/// @brief What a tone of no known name is told. -constexpr std::string_view kToneNames = "a tone is neutral, info, ok, warn or err, or null for none"; - -/// @brief What a span list with a run of a tone of no known name is told. -constexpr std::string_view kSpanToneReason = - "a run's tone is neutral, info, ok, warn or err, or null for none; a run of another tone is drawn untoned"; - -/// @brief A splitter's `sizes`: a list of numbers, each read as `intOf` reads it. -/// @param value The value. -/// @return The sizes; `nullopt` for anything but a list whose every item is an `int` or a decimal. -[[nodiscard]] std::optional> splitterSizesOf(Value const& value) { - ValueList const* const items = value.asList(); - if (items == nullptr) { - return std::nullopt; - } - std::vector sizes; - sizes.reserve(items->size()); - for (Value const& item : *items) { - if (item.asInt() == nullptr && item.asDecimal() == nullptr) { - return std::nullopt; - } - sizes.push_back(static_cast(intOf(item, 0))); - } - return sizes; -} -} // namespace - -[[nodiscard]] Sizing sizingOf(Value const& value) { - if (Value const* const fixed = value.field("fixed")) { - return Sizing::fixed(static_cast(intOf(*fixed, 0))); - } - if (Value const* const percent = value.field("percent")) { - return Sizing::percent(static_cast(intOf(*percent, 1))); - } - if (Value const* const stretch = value.field("stretch")) { - return Sizing::stretch(static_cast(intOf(*stretch, 1))); - } - return Sizing::content(); -} - -[[nodiscard]] bool isSizing(Value const& value) { - if (std::string const* const text = value.asString()) { - return *text == "content"; - } - ValueRecord const* const record = value.asRecord(); - if (record == nullptr || record->size() != 1 || record->begin()->second.asInt() == nullptr) { - return false; - } - if (record->contains("percent")) { - std::int64_t const share = *record->begin()->second.asInt(); - return share >= 1 && share <= 100; - } - return record->contains("fixed") || record->contains("stretch"); -} - -namespace { - -/// @brief An alignment by name, as the loader checked it: `start`, `center`, `end`, or stretch for none. -/// @param name The name; empty for none. -/// @return The alignment. -[[nodiscard]] Align alignOf(std::string_view name) { - if (name == "start") { - return Align::Start; - } - if (name == "center") { - return Align::Center; - } - if (name == "end") { - return Align::End; - } - return Align::Stretch; -} - -/// @brief A table cell's place by name: across its column (`align`) or down its row (`valign`). -/// @param name `start`, `center` or `end`. -/// @return The place; `nullopt` for any other name, `stretch` included. -[[nodiscard]] std::optional cellPlaceNamed(std::string_view name) { - if (name == "start") { - return Align::Start; - } - if (name == "center") { - return Align::Center; - } - if (name == "end") { - return Align::End; - } - return std::nullopt; -} - -/// @brief A justification by name, as the loader checked it: `center`, `end`, `between`, or start for none. -/// @param name The name; empty for none. -/// @return The justification. -[[nodiscard]] Justify justifyOf(std::string_view name) { - if (name == "center") { - return Justify::Center; - } - if (name == "end") { - return Justify::End; - } - if (name == "between") { - return Justify::Between; - } - return Justify::Start; -} - -/// @brief An axis by name: `horizontal`, or vertical for anything else. -/// @param value The value. -/// @return The axis. -[[nodiscard]] Axis axisOf(Value const& value) { - std::string const* const text = value.asString(); - return text != nullptr && *text == "horizontal" ? Axis::Horizontal : Axis::Vertical; -} - -/// @brief A step's state by name: `active`, `done`, `failed`, or pending for anything else. -/// @param name The name. -/// @return The state. -[[nodiscard]] StepState stepStateOf(std::string_view name) { - if (name == "active") { - return StepState::Active; - } - if (name == "done") { - return StepState::Done; - } - return name == "failed" ? StepState::Failed : StepState::Pending; -} - -/// @brief The options of a select, from a list of scalars or of records with a key and a `label`. -/// @param options The list. -/// @param format The formatting facts. -/// @return The options. -[[nodiscard]] std::vector selectOptions(Value const& options, FormatContext const& format) { - std::vector out; - if (ValueList const* const items = options.asList()) { - for (Value const& option : *items) { - Value const key = optionKey(option); - Value const* const label = option.field("label"); - out.push_back(SelectOption{.key = keyOf(key), .label = textOf(label != nullptr ? *label : key, format)}); - } - } - return out; -} - -/// @brief What a percent sizes, as a refusal or a report says it. -constexpr std::string_view kPercentPlaces = - "`percent` sizes a width along a row or a horizontal splitter; nothing here takes a share"; -/// @brief Why a percent inside a case or an overlay's content is not a share. -constexpr std::string_view kPercentInHolder = "size the `switch` or the overlay itself; its content fills it"; - -/// @brief The default spacing step between the children of a document panel or collapsible, the mockups' 8 px. -constexpr int kPanelGap = 2; -/// @brief The default spacing step between the children of a document dialog or drawer, the mockups' 12 px. -constexpr int kDialogGap = 3; - -/// @brief A node's size request. -/// @param node The node; may be null. -/// @return Its layout hints, or none for a null node or a kind that has no `Common`. -[[nodiscard]] LayoutHints layoutHintsOf(Node const& node) { - if (!node) { - return {}; - } - return std::visit( - [](auto const& spec) -> LayoutHints { - if constexpr (requires { spec.common.layout; }) { - return spec.common.layout; - } else { - return {}; - } - }, - node->kind); -} - -/// @brief A node with its width sizing replaced; a node of a kind with no layout is returned as it is. -/// @param node The node. -/// @param width The sizing. -/// @return The node. -[[nodiscard]] Node withWidth(Node const& node, Sizing width) { - if (!node) { - return node; - } - auto copy = std::make_shared(*node); - std::visit( - [&width](auto& spec) { - if constexpr (requires { spec.common.layout; }) { - spec.common.layout.width = width; - } - }, - copy->kind); - return copy; -} - -/// @brief The size request of a holder of @p sizings: a stretch by the largest weight where any is a stretch, and -/// content otherwise (a share of a row is not a holder's: `listColumn` passes a lone child's on). -/// @param sizings One dimension's sizing of each child. -/// @return The holder's sizing. -[[nodiscard]] Sizing holderSizing(std::span sizings) { - int weight = 0; - for (Sizing const& sizing : sizings) { - if (sizing.kind == Sizing::Kind::Stretch) { - weight = std::max(weight, sizing.amount); - } - } - return weight > 0 ? Sizing::stretch(weight) : Sizing::content(); -} - -/// @brief The column that holds a node list. It stretches along an axis when one of its children does, so the -/// content means what its nodes would mean written inline in the holder's parent. -/// @param children The content. -/// @param gap The spacing step between children. -/// @return The column; bounds and `alignSelf` stay unset, because they belong to a child. -[[nodiscard]] Column listColumn(std::vector children, int gap = 0) { - std::vector widths; - std::vector heights; - for (Node const& child : children) { - LayoutHints const hints = layoutHintsOf(child); - widths.push_back(hints.width); - heights.push_back(hints.height); - } - // A lone child's share of its row is the holder's, and the child fills the holder, so the share is taken once. - if (children.size() == 1 && widths.front().kind == Sizing::Kind::Percent) { - Sizing const share = widths.front(); - children.front() = withWidth(children.front(), Sizing::stretch(1)); - Column column{.children = std::move(children), .gap = gap}; - column.common.layout.width = share; - column.common.layout.height = holderSizing(heights); - return column; - } - Column column{.children = std::move(children), .gap = gap}; - column.common.layout.width = holderSizing(widths); - column.common.layout.height = holderSizing(heights); - return column; -} - -/// @brief Content whose scope is made when it mounts and released when it unmounts: a one-row `forEach` whose -/// row view builds it. -/// @param build Builds the content, its scope included. -/// @param hints The size request of the content. A slot reads the sizing of its direct child alone, which is this -/// `forEach`, so the content's stretch reaches the slot only through these. -/// @return The node. -[[nodiscard]] Node lazy(std::function build, LayoutHints const& hints = {}) { - Common common; - common.layout = hints; - return ui::forEach([] { return std::vector{0}; }, [](int const&) { return Key{std::int64_t{0}}; }, - [build = std::move(build)](reactive::Signal const&) { return build(); }, - Axis::Vertical, 0, common); -} - -/// @brief A column of content that holds its scope for as long as it is mounted: its `visible` is a binding -/// that keeps the scope alive and reads nothing. -/// @param children The content. -/// @param scope The scope. -/// @param keys The chords of the content. -/// @param gap The spacing step between the children. -/// @return The node. -[[nodiscard]] Node holding(std::vector children, std::shared_ptr scope, - std::vector keys = {}, int gap = 0) { - Column column = listColumn(std::move(children), gap); - column.common.visible = Prop{[held = std::move(scope)] { return held != nullptr; }}; - column.common.keys = std::move(keys); - return ui::column(std::move(column)); -} - -/// @brief Whether an expression reads a name in @p names. -/// @param expr The expression. -/// @param names The names. -/// @return Whether any form of the expression names one. -// NOLINTBEGIN(misc-no-recursion): an expression nests its arguments and fields, and the walk follows them. -[[nodiscard]] bool readsAny(ExprPtr const& expr, std::set> const& names) { - if (!expr) { - return false; - } - if (!expr->name.empty() && names.contains(expr->name)) { - return true; - } - return std::ranges::any_of(expr->args, [&](ExprPtr const& arg) { return readsAny(arg, names); }) || - std::ranges::any_of(expr->fields, [&](auto const& field) { return readsAny(field.second, names); }); -} -// NOLINTEND(misc-no-recursion) - -/// @brief Collects the element ids of a document subtree. -/// @param node The root. -/// @param out Receives the ids. -// NOLINTNEXTLINE(misc-no-recursion): a node's children and parts are nodes, and the walk follows them. -void collectIds(DocNode const& node, std::set>& out) { - if (!node.id.empty()) { - out.insert(node.id); - } - for (auto const* group : {&node.children, &node.parts}) { - for (auto const& [key, list] : *group) { - for (DocNodePtr const& child : list) { - collectIds(*child, out); - } - } - } -} -} // namespace - -// NOLINTNEXTLINE(misc-no-recursion): lowering a node lowers its children, which come back through here. -Node ScreenCore::lowerAll(std::span nodes, LowerCtx const& ctx, int gap) { - LowerCtx listCtx = ctx; - listCtx.listGap = gap; - if (nodes.size() == 1) { - return lower(*nodes.front(), listCtx); - } - std::vector children; - children.reserve(nodes.size()); - for (DocNodePtr const& child : nodes) { - children.push_back(lower(*child, listCtx)); - } - // Several nodes share a holder, and a share of a row is not a share of a holder: each is reported and takes its - // content size. - for (auto&& [child, written] : std::views::zip(children, nodes)) { - if (layoutHintsOf(child).width.kind == Sizing::Kind::Percent) { - report(written->path, - "a percent among several nodes is a share of their holder; " + std::string{kPercentPlaces}); - child = withWidth(child, Sizing::content()); - } - } - Column holder = listColumn(std::move(children), gap); - // The column is the mount's, not the document's: a child that bleeds reaches past the padding of the container - // the document names, so the column passes that padding on instead of hiding it. - holder.holder = true; - return ui::column(std::move(holder)); -} - -void ScreenCore::fillHolder(std::vector& children, std::string const& path) { - for (Node& child : children) { - if (layoutHintsOf(child).width.kind == Sizing::Kind::Percent) { - report(path, kPercentInHolder); - child = withWidth(child, Sizing::stretch(1)); - } - } -} - -LayoutHints ScreenCore::nodeHints(DocNode const& node, std::set> const& own, - LowerCtx const& ctx) { - LayoutHints hints; - if (ExprPtr const sizing = node.prop("sizing")) { - if (sizing->kind != ExprKind::Literal && readsAny(sizing, own)) { - report(sizing->path, - "this sizing reads a name the case declares, so the case is held at its " - "content size"); - } else { - Value const value = once(ctx, sizing); - Value const* const width = value.field("width"); - Value const* const height = value.field("height"); - if (width != nullptr || height != nullptr) { - hints.width = width != nullptr && isSizing(*width) ? sizingOf(*width) : Sizing::content(); - hints.height = height != nullptr && isSizing(*height) ? sizingOf(*height) : Sizing::content(); - } else if (isSizing(value)) { - hints.width = sizingOf(value); - } - } - } - return hints; -} - -LayoutHints ScreenCore::holderHints(std::span content, ScopeDecl const* decl, - LowerCtx const& ctx) { - std::set> own; - for (DocNode const* const node : content) { - collectIds(*node, own); - } - if (decl != nullptr) { - for (ModelDecl const& model : decl->models) { - own.insert(model.name); - } - for (StateDecl const& state : decl->state) { - own.insert(state.name); - } - for (LetDecl const& let : decl->lets) { - own.insert(let.name); - } - for (QueryDecl const& query : decl->queries) { - own.insert(query.name); - } - for (MutationDecl const& mutation : decl->mutations) { - own.insert(mutation.name); - } - } - std::vector widths; - std::vector heights; - for (DocNode const* const node : content) { - LayoutHints const hints = nodeHints(*node, own, ctx); - widths.push_back(hints.width); - heights.push_back(hints.height); - } - LayoutHints out; - out.width = holderSizing(widths); - out.height = holderSizing(heights); - return out; -} - -// NOLINTBEGIN(misc-no-recursion): a menu nests, and lowering descends the document. -Node ScreenCore::lower(DocNode const& node, LowerCtx const& ctx) { - if (recording) { - if (loweredNodes.size() >= kPruneLoweredAt && loweredNodes.size() % kPruneLoweredAt == 0) { - std::erase_if(loweredNodes, [](LoweredNode const& entry) { return entry.scope.expired(); }); - } - loweredNodes.push_back(LoweredNode{.node = &node, .scope = ctx.scope, .bindings = ctx.bindings}); - } - // Only a switch reads the gap of the list around it; every other kind's children are held by a holder that sets - // their gap, so none sees its grandparent's. - if (ctx.listGap != 0 && node.kind != "switch") { - LowerCtx plain = ctx; - plain.listGap = 0; - return lowerKind(node, plain, elementFor(*ctx.scope, node)); - } - return lowerKind(node, ctx, elementFor(*ctx.scope, node)); -} - -Prop ScreenCore::roleProp(LowerCtx const& ctx, ExprPtr const& expr) { - if (!expr || expr->kind == ExprKind::Literal) { - return bindProp(ctx, expr, TextRole::Normal, roleOf); - } - return slotProp([this, scope = ctx.scope, bindings = ctx.bindings, expr] { - Value const value = evalIn(*scope, bindings.get(), expr); - std::optional const role = roleNamed(textOf(value, scope->formatting())); - if (!role) { - report(expr->path, "role is " + canonicalJson(value) + "; " + std::string{kRoleNames}); - } - return role.value_or(TextRole::Normal); - }); -} - -Prop ScreenCore::surfaceOf(DocNode const& node, LowerCtx const& ctx) { - ExprPtr const expr = node.prop("surface"); - auto nameOf = [this, path = pointerAppend(node.path, "surface")](Value const& value) -> std::string { - if (std::string const* const name = value.asString()) { - return *name; - } - if (!value.isNull()) { - report(path, "a surface is the name of one; " + canonicalJson(value) + " is not a string"); - } - return {}; - }; - if (!expr || expr->kind == ExprKind::Literal) { - return expr ? Prop{nameOf(expr->literal)} : Prop{std::string{}}; - } - return slotProp([scope = ctx.scope, bindings = ctx.bindings, expr, nameOf = std::move(nameOf)] { - return nameOf(evalIn(*scope, bindings.get(), expr)); - }); -} - -KeyValueItem ScreenCore::keyValueItemOf(Value const& item, std::string const& path, RtScope const& scope) { - FormatContext const& format = scope.formatting(); - Value const* const label = item.field("label"); - Value const* const value = item.field("value"); - KeyValueItem out{ - .label = label == nullptr ? std::string{} : textOf(*label, format), - .value = value == nullptr ? std::string{} : textOf(*value, format), - }; - if (Value const* const spans = item.field("spans")) { - bool dropped = false; - bool badTone = false; - out.spans = spansOf(*spans, format, dropped, &badTone); - if (dropped) { - report(path, kSpansReason); - } - if (badTone) { - report(path, kSpanToneReason); - } - } - if (Value const* const tone = item.field("tone")) { - std::optional const named = toneNamed(*tone); - if (!named) { - report(path, "an item's tone is " + canonicalJson(*tone) + "; " + std::string{kToneNames}); - } - out.tone = named.value_or(Tone::Neutral); - } - return out; -} - -// A group needs no widget of its own: it lowers to kinds every backend has, so the view tree and the contract do not -// change. Its description is a line read in order after its children, since `Common` carries no accessible -// description. -Node ScreenCore::lowerGroup(DocNode const& node, LowerCtx const& ctx, ElementState* element, - std::vector children) { - Text legend{ - .text = bindProp(ctx, node.prop("label"), std::string{}, stringOf), - .role = TextRole::Label, - }; - legend.field.required = bindProp(ctx, node.prop("required"), false, boolOf); - std::vector column; - column.reserve(children.size() + 3); - column.push_back(ui::text(std::move(legend))); - std::ranges::move(children, std::back_inserter(column)); - if (ExprPtr const description = node.prop("description")) { - Text line{.text = bindProp(ctx, description, std::string{}, stringOf), .role = TextRole::Muted}; - line.common.visible = slotProp([scope = ctx.scope, bindings = ctx.bindings, description] { - return !textOf(evalIn(*scope, bindings.get(), description), scope->formatting()).empty(); - }); - column.push_back(ui::text(std::move(line))); - } - // The shown errors, one line each: a check that targets the group shows its message here. - auto const shown = [this, element, scope = ctx.scope, bindings = ctx.bindings, errors = node.prop("errors")] { - return stringsOf(element != nullptr ? elementValue(*element, "shownErrors") - : evalIn(*scope, bindings.get(), errors)); - }; - Text messages{ - .text = slotProp([shown] { - std::string joined; - for (std::string const& message : shown()) { - joined += (joined.empty() ? "" : "\n") + message; - } - return joined; - }), - .role = TextRole::Error, - }; - messages.common.visible = slotProp([shown] { return !shown().empty(); }); - column.push_back(ui::text(std::move(messages))); - Column spec{ - .children = std::move(column), - .gap = static_cast(intOf(node.prop("gap") ? once(ctx, node.prop("gap")) : Value{}, 0)), - }; - commonOf(node, ctx, element, spec.common); - if (spec.common.a11y.role.empty()) { - spec.common.a11y.role = "group"; - } - bool const named = std::ranges::any_of(node.partList("a11y"), - [](DocNodePtr const& a11y) { return a11y->prop("name") != nullptr; }); - if (!named) { - spec.common.a11y.name = bindProp(ctx, node.prop("label"), std::string{}, stringOf); - } - return ui::column(std::move(spec)); -} - -Prop> ScreenCore::spansProp(LowerCtx const& ctx, ExprPtr const& expr) { - return slotProp>([this, scope = ctx.scope, bindings = ctx.bindings, expr] { - bool dropped = false; - bool badTone = false; - std::vector spans = - spansOf(evalIn(*scope, bindings.get(), expr), scope->formatting(), dropped, &badTone); - if (dropped) { - report(expr->path, kSpansReason); - } - if (badTone) { - report(expr->path, kSpanToneReason); - } - return spans; - }); -} - -// The size request: `sizing` (the width, or both dimensions), `alignSelf`, and the bounds. -void ScreenCore::layoutOf(DocNode const& node, LowerCtx const& ctx, LayoutHints& layout) { - if (ExprPtr const sizing = node.prop("sizing")) { - // The width, or both dimensions from a `{width, height}` record, one left out being content. The loader - // refuses a literal of another form; a computed one that is none is reported and lowers to content. - Value const value = once(ctx, sizing); - Value const* const width = value.field("width"); - Value const* const height = value.field("height"); - bool const record = width != nullptr || height != nullptr; - bool const valid = record ? (width == nullptr || isSizing(*width)) && (height == nullptr || isSizing(*height)) - : isSizing(value); - if (!valid) { - report(sizing->path, "sizing is " + canonicalJson(value) + - "; a sizing is \"content\", {\"fixed\": n}, {\"stretch\": w}, {\"percent\": n} " - "with n from 1 to 100, or a record of width and height of them"); - } else if (record) { - layout.width = width != nullptr ? sizingOf(*width) : Sizing::content(); - layout.height = height != nullptr ? sizingOf(*height) : Sizing::content(); - if (layout.height.kind == Sizing::Kind::Percent) { - report(sizing->path, kPercentPlaces); - layout.height = Sizing::content(); - } - } else { - layout.width = sizingOf(value); - } - } - if (std::string_view const placed = node.name("alignSelf"); !placed.empty()) { - layout.alignSelf = alignOf(placed); - } - layout.bleed = node.flag("bleed"); - // Literal integers, checked at load. - for (auto const& [key, bound] : { - std::pair{"minWidth", &LayoutHints::minWidth}, - std::pair{"maxWidth", &LayoutHints::maxWidth}, - std::pair{"minHeight", &LayoutHints::minHeight}, - std::pair{"maxHeight", &LayoutHints::maxHeight}, - }) { - if (ExprPtr const expr = node.prop(key); expr != nullptr && expr->literal.asInt() != nullptr) { - layout.*bound = static_cast(*expr->literal.asInt()); - } - } -} - -namespace { - -/// @brief Where a declaration is lowered, as a focus key reads it. -struct FocusPlace { - /// @brief The focus key of the component use it is lowered for, and `>`; empty outside a component. - std::string prefix; - /// @brief The keys of the rows that enclose it, outermost first. - std::vector rows; -}; - -/// @brief Where @p scope is: the row keys of its chain and the component use it is lowered for. -/// @param scope The scope. -/// @return It. -[[nodiscard]] FocusPlace focusPlace(RtScope const& scope) { - FocusPlace place; - for (RtScope const* current = &scope; current != nullptr; current = current->parent.get()) { - if (current->row != nullptr) { - place.rows.push_back(current->rowKey); - } - if (current->parent == nullptr) { - place.prefix = current->usePrefix; - } - } - std::ranges::reverse(place.rows); - return place; -} - -/// @brief A focus key: a declaration's pointer under its component use's prefix, with one key per enclosing row. -/// @param place Where the declaration is lowered. -/// @param path The declaring node's JSON Pointer. -/// @return The key, unique per declaration, row and component use. -[[nodiscard]] std::string focusKey(FocusPlace const& place, std::string_view path) { - std::string key = place.prefix; - key += path; - for (std::string const& row : place.rows) { - key += '@'; - key += row; - } - return key; -} - -/// @brief The focus key of the element @p path declares, lowered in @p scope. -/// @param path The declaring node's JSON Pointer. -/// @param scope The scope it is lowered in. -/// @return The key. -[[nodiscard]] std::string focusKeyOf(std::string_view path, RtScope const& scope) { - return focusKey(focusPlace(scope), path); -} -} // namespace - -void ScreenCore::commonOf(DocNode const& node, LowerCtx const& ctx, ElementState* element, Common& common) { - static_cast(element); - common.visible = bindProp(ctx, node.prop("visible"), true, boolOf); - common.enabled = bindProp(ctx, node.prop("enabled"), true, boolOf); - common.tooltip = bindProp(ctx, node.prop("tooltip"), std::string{}, stringOf); - layoutOf(node, ctx, common.layout); - common.testId = std::string{node.name("testId")}; - if (!node.id.empty()) { - common.focusId = focusKeyOf(node.path, *ctx.scope); - } - common.surface = surfaceOf(node, ctx); - if (ExprPtr const autofocus = node.prop("autofocus")) { - common.autofocus = boolOf(once(ctx, autofocus), ctx.scope->formatting()); - } - for (DocNodePtr const& a11y : node.partList("a11y")) { - common.a11y.name = bindProp(ctx, a11y->prop("name"), std::string{}, stringOf); - common.a11y.role = std::string{a11y->name("role")}; - } - for (DocNodePtr const& drag : node.partList("drag")) { - ExprPtr const payload = drag->prop("payload"); - common.dragKey = - slotProp>([scope = ctx.scope, bindings = ctx.bindings, payload] -> std::optional { - Value const value = evalIn(*scope, bindings.get(), payload); - return value.isNull() ? std::nullopt : std::optional{keyOf(value)}; - }); - } - for (DocNodePtr const& drop : node.partList("drop")) { - ExprPtr const accepts = drop->prop("accepts"); - common.accepts = [this, scope = ctx.scope, bindings = ctx.bindings, accepts](Key const& key) { - if (!accepts) { - return true; - } - Value const accepted = runtime().untracked([&] { return evalIn(*scope, bindings.get(), accepts); }); - if (ValueList const* const items = accepted.asList()) { - return std::ranges::any_of(*items, [&](Value const& item) { return keyOf(item) == key; }); - } - return accepted.isNull() || keyOf(accepted) == key; - }; - common.onDrop = [this, ctx, commands = drop->event("onDrop")](Key const& key) { - runEvent(commands, ctx, valueOfKey(key)); - }; - } - for (auto const& [chord, commands] : node.keys) { - common.keys.push_back( - KeyBinding{.chord = chord, .onPress = [this, ctx, list = &commands] { runEvent(list, ctx, Value{}); }}); - } -} - -void ScreenCore::fieldOf(DocNode const& node, LowerCtx const& ctx, ElementState* element, FieldState& field) { - field.readonly = bindProp(ctx, node.prop("readonly"), false, boolOf); - field.required = bindProp(ctx, node.prop("required"), false, boolOf); - field.stale = bindProp(ctx, node.prop("stale"), false, boolOf); - if (element != nullptr) { - field.errors = slotProp>( - [this, scope = ctx.scope, element] { return stringsOf(elementValue(*element, "shownErrors")); }); - } else if (ExprPtr const errors = node.prop("errors")) { - field.errors = slotProp>([scope = ctx.scope, bindings = ctx.bindings, errors] { - return stringsOf(evalIn(*scope, bindings.get(), errors)); - }); - } - // A tone evaluates the value and is not an error: it changes the field's look and nothing of `valid`. - if (node.prop("description")) { - field.description = bindProp(ctx, node.prop("description"), std::string{}, stringOf); - } - if (node.prop("labelHint")) { - field.labelHint = bindProp(ctx, node.prop("labelHint"), std::string{}, stringOf); - } - if (ExprPtr const tone = node.prop("tone")) { - field.tone = slotProp([this, scope = ctx.scope, bindings = ctx.bindings, tone] { - Value const value = evalIn(*scope, bindings.get(), tone); - std::optional const named = toneNamed(value); - if (!named) { - report(tone->path, "tone is " + canonicalJson(value) + "; " + std::string{kToneNames}); - } - return named.value_or(Tone::Neutral); - }); - } -} - -MenuItem ScreenCore::menuItemOf(DocNode const& part, LowerCtx const& ctx) { - MenuItem item; - if (part.flag("separator")) { - item.separator = true; - return item; - } - item.label = bindProp(ctx, part.prop("label"), std::string{}, stringOf); - item.description = bindProp(ctx, part.prop("description"), std::string{}, stringOf); - item.visible = bindProp(ctx, part.prop("visible"), true, boolOf); - if (Commands const* const commands = part.event("onClick")) { - item.onSelect = [this, ctx, commands] { runEvent(commands, ctx, Value{}); }; - } - if (ExprPtr const icon = part.prop("icon")) { - item.icon = textOf(once(ctx, icon), ctx.scope->formatting()); - } - item.keys = std::string{part.name("keys")}; - if (ExprPtr const checked = part.prop("checked")) { - item.checked = slotProp>( - [scope = ctx.scope, bindings = ctx.bindings, checked] -> std::optional { - Value const value = evalIn(*scope, bindings.get(), checked); - bool const* const flag = value.asBool(); - return flag == nullptr ? std::nullopt : std::optional{*flag}; - }); - } - item.enabled = bindProp(ctx, part.prop("enabled"), true, boolOf); - return item; -} - -// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. -std::vector ScreenCore::menuItems(std::span parts, LowerCtx const& ctx) { - std::vector items; - for (DocNodePtr const& part : parts) { - MenuItem item = menuItemOf(*part, ctx); - if (!item.separator) { - item.items = menuItems(part->partList("items"), ctx); - } - items.push_back(std::move(item)); - } - return items; -} - -// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. -std::vector ScreenCore::lowerHeadMenu(std::span parts, LowerCtx const& ctx) { - std::vector models; - models.reserve(parts.size()); - for (DocNodePtr const& part : parts) { - models.push_back(HeadMenuModel{ - .id = part->id, - .path = part->path, - .item = menuItemOf(*part, ctx), - .items = lowerHeadMenu(part->partList("items"), ctx), - }); - } - return models; -} - -std::vector ScreenCore::lowerHeadTools(std::span parts, LowerCtx const& ctx) { - static constexpr int kSearchWidth = 30; - std::vector models; - models.reserve(parts.size()); - for (DocNodePtr const& part : parts) { - bool const search = part->name("kind") == "search"; - HeadToolModel model{ - .id = part->id, - .path = part->path, - .kind = search ? HeadToolKind::Search : HeadToolKind::Select, - .label = bindProp(ctx, part->prop("label"), std::string{}, stringOf), - .value = bindProp(ctx, part->prop("value"), std::string{}, stringOf), - .placeholder = bindProp(ctx, part->prop("placeholder"), std::string{}, stringOf), - .options = {}, - .selected = {}, - .width = search ? kSearchWidth : 0, - .enabled = bindProp(ctx, part->prop("enabled"), true, boolOf), - .visible = bindProp(ctx, part->prop("visible"), true, boolOf), - .edit = {}, - .submit = {}, - }; - if (ExprPtr const width = part->prop("width")) { - if (std::int64_t const* const units = width->literal.asInt()) { - model.width = static_cast(*units); - } - } - if (!search) { - model.options = slotProp>( - [scope = ctx.scope, bindings = ctx.bindings, options = part->prop("options")] { - return selectOptions(evalIn(*scope, bindings.get(), options), scope->formatting()); - }); - model.selected = slotProp>( - [scope = ctx.scope, bindings = ctx.bindings, selected = part->prop("selected")] -> std::optional { - Value const value = selected ? evalIn(*scope, bindings.get(), selected) : Value{}; - return value.isNull() ? std::nullopt : std::optional{keyOf(value)}; - }); - } - Commands const* const edited = part->event(search ? "onChange" : "onChoose"); - model.edit = [this, ctx, edited](Value event) { runEvent(edited, ctx, std::move(event)); }; - if (search) { - model.submit = [this, ctx, onSubmit = part->event("onSubmit")](Value event) { - runEvent(onSubmit, ctx, std::move(event)); - }; - } - models.push_back(std::move(model)); - } - return models; -} - -ActionModels ScreenCore::lowerActionParts(std::span parts, LowerCtx const& ctx) { - ActionModels models; - models.reserve(parts.size()); - for (DocNodePtr const& part : parts) { - ActionModel model{ - .id = part->id, - .path = part->path, - .label = bindProp(ctx, part->prop("label"), std::string{}, stringOf), - .icon = bindProp(ctx, part->prop("icon"), std::string{}, stringOf), - .iconOnly = bindProp(ctx, part->prop("iconOnly"), false, boolOf), - .emphasis = ButtonEmphasis::Normal, - .enabled = bindProp(ctx, part->prop("enabled"), true, boolOf), - .visible = bindProp(ctx, part->prop("visible"), true, boolOf), - .run = {}, - }; - model.emphasis = emphasisNamed(part->name("emphasis")).value_or(ButtonEmphasis::Normal); - if (Commands const* const commands = part->event("onClick")) { - model.run = [this, ctx, commands] { runEvent(commands, ctx, Value{}); }; - } - models.push_back(std::move(model)); - } - return models; -} - -Node ScreenCore::actionBarOf(ActionModels actions) { - ActionBar bar; - for (ActionModel& action : actions) { - Button button{ - .label = action.label, - .emphasis = action.emphasis, - .onClick = std::move(action.run), - .common = {}, // NOLINT(readability-trailing-comma): the comma ends the designator, not the empty braces. - .icon = action.icon.evaluate(), - }; - if (action.iconOnly.isBound() || action.iconOnly.constant()) { - // The label is the button's name and tooltip; the caption is empty while the icon stands alone. - button.label = Prop{[label = action.label, iconOnly = action.iconOnly] { - return iconOnly.evaluate() ? std::string{} : label.evaluate(); - }}; - button.common.a11y.name = action.label; - button.common.tooltip = action.label; - } - button.common.visible = std::move(action.visible); - button.common.enabled = std::move(action.enabled); - button.common.testId = "action_" + action.id; - bar.children.push_back(ui::button(std::move(button))); - } - return ui::actionBar(std::move(bar)); -} - -std::vector ScreenCore::lowerBadgeParts(std::span parts, LowerCtx const& ctx) { - std::vector badges; - badges.reserve(parts.size()); - for (DocNodePtr const& part : parts) { - badges.push_back(BadgeModel{ - .text = bindProp(ctx, part->prop("text"), std::string{}, stringOf), - .tone = bindProp(ctx, part->prop("tone"), Tone::Neutral, toneOf), - .icon = bindProp(ctx, part->prop("icon"), std::string{}, stringOf), - .visible = bindProp(ctx, part->prop("visible"), true, boolOf), - }); - } - return badges; -} - -// The readers every kind's lowering shares, each bound to the node being lowered. -class ScreenCore::KindKit { -public: - KindKit(ScreenCore& core, DocNode const& node, LowerCtx const& ctx, ElementState* element) - : _core{core}, _node{node}, _ctx{ctx}, _element{element}, _format{ctx.scope->formatting()} {} - - // The children under @p key, each lowered with @p gap as the gap of the list around it. - [[nodiscard]] std::vector children(std::string_view key, int gap = 0) const { - LowerCtx listCtx = _ctx; - listCtx.listGap = gap; - std::vector out; - for (DocNodePtr const& child : _node.nodes(key)) { - out.push_back(_core.lower(*child, listCtx)); - } - return out; - } - - // The children under @p key as one node: none is empty, several share a holder that sets @p gap. - [[nodiscard]] Node child(std::string_view key, int gap = 0) const { - auto const nodes = _node.nodes(key); - return nodes.empty() ? Node{} : _core.lowerAll(nodes, _ctx, gap); - } - - [[nodiscard]] std::int64_t onceInt(std::string_view key, std::int64_t fallback) const { - ExprPtr const expr = _node.prop(key); - return expr ? intOf(_core.once(_ctx, expr), fallback) : fallback; - } - - [[nodiscard]] bool onceBool(std::string_view key, bool fallback) const { - ExprPtr const expr = _node.prop(key); - return expr ? boolOf(_core.once(_ctx, expr), _format) : fallback; - } - - // A stack's padding: one step, or the loader-checked constant list of the vertical and the horizontal step. A - // computed padding that yields a list is not a step: it is reported once and taken as 0. - [[nodiscard]] Padding stackPadding() const { - ExprPtr const expr = _node.prop("padding"); - if (!expr) { - return {}; - } - Value const value = _core.once(_ctx, expr); - if (ValueList const* const steps = value.asList()) { - if (expr->kind == ExprKind::Literal && steps->size() == 2) { - return Padding{static_cast(intOf(steps->at(0), 0)), static_cast(intOf(steps->at(1), 0))}; - } - _core.report(_node.path + "/padding", "a computed `padding` is one spacing step, not a list; taken as 0"); - return {}; - } - return Padding{static_cast(intOf(value, 0))}; - } - - [[nodiscard]] std::string onceText(std::string_view key) const { - ExprPtr const expr = _node.prop(key); - return expr ? textOf(_core.once(_ctx, expr), _format) : std::string{}; - } - - [[nodiscard]] Prop textProp(std::string_view key) const { - return _core.bindProp(_ctx, _node.prop(key), std::string{}, stringOf); - } - - // A field shows no caption of its own, so its label is what names it to assistive technology. An `a11y` part - // that gives a name was written for that purpose and wins; one that gives only a role leaves the label. - void nameByLabel(Common& common) const { - bool const named = std::ranges::any_of(_node.partList("a11y"), - [](DocNodePtr const& a11y) { return a11y->prop("name") != nullptr; }); - if (_node.prop("label") && !named) { - common.a11y.name = textProp("label"); - } - } - - // A standalone input draws its label as a caption only when the document asks for it (`showLabel`). - template - void captionOf(Spec& spec) const { - if (_node.prop("label")) { - spec.label = textProp("label"); - } - spec.showLabel = _node.flag("showLabel"); - } - - [[nodiscard]] Action action(std::string_view key) const { - Commands const* const commands = _node.event(key); - if (commands == nullptr) { - return {}; - } - return [core = &_core, ctx = _ctx, commands] { core->runEvent(commands, ctx, Value{}); }; - } - - [[nodiscard]] ActionButton actionPart() const { - ActionButton button; - for (DocNodePtr const& part : _node.partList("action")) { - button.label = _core.bindProp(_ctx, part->prop("label"), std::string{}, stringOf); - if (Commands const* const commands = part->event("onClick")) { - button.onClick = [core = &_core, ctx = _ctx, commands] { core->runEvent(commands, ctx, Value{}); }; - } - } - return button; - } - - // A reader of the element's value under @p name. - [[nodiscard]] auto read(std::string_view name) const { - return [element = _element, core = &_core, name = std::string{name}] { - return core->elementValue(*element, name); - }; - } - -private: - // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members): the kit lives inside one lowering call, in - // which all four outlive it. - ScreenCore& _core; - DocNode const& _node; - LowerCtx const& _ctx; - ElementState* _element; - FormatContext const& _format; - // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) -}; - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of ui/1. -std::optional ScreenCore::lowerWidget(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - std::string_view const kind = node.kind; - FormatContext const& format = ctx.scope->formatting(); - KindKit const kit{*this, node, ctx, element}; - if (kind == "text") { - Text spec{.role = roleProp(ctx, node.prop("role"))}; - // A text with spans shows them, so its `text`, an older client's fallback, is not lowered. - if (ExprPtr const spans = node.prop("spans")) { - spec.spans = spansProp(ctx, spans); - } else { - spec.text = kit.textProp("text"); - } - if (!node.name("align").empty()) { - spec.align = textAlignNamed(node.name("align")); - } - fieldOf(node, ctx, element, spec.field); - commonOf(node, ctx, element, spec.common); - return ui::text(std::move(spec)); - } - if (kind == "button") { - Button spec{.label = kit.textProp("label")}; - spec.icon = kit.onceText("icon"); - spec.emphasis = emphasisNamed(node.name("emphasis")).value_or(ButtonEmphasis::Normal); - if (node.name("style") == "item") { - spec.style = ButtonStyle::Item; - } - spec.shape = shapeNamed(node.name("shape")).value_or(ControlShape::Default); - spec.size = sizeNamed(node.name("size")).value_or(ButtonSize::Normal); - spec.mono = node.flag("mono"); - spec.weight = weightNamed(node.name("weight")).value_or(0); - if (node.prop("selected")) { - spec.selected = bindProp(ctx, node.prop("selected"), false, boolOf); - // An entry's content, drawn in place of its label: one node as it is, several in a column. - if (std::vector content = kit.children("children"); content.size() == 1) { - spec.child = std::move(content.front()); - } else if (!content.empty()) { - spec.child = ui::column(Column{.children = std::move(content)}); - } - } - Commands const* const onClick = node.event("onClick"); - Commands const* const onActivate = node.event("onActivate"); - if (onClick != nullptr || onActivate != nullptr) { - spec.onClick = [this, ctx, onClick, onActivate] { - runEvent(onClick, ctx, Value{}); - runEvent(onActivate, ctx, Value{}); - }; - } - commonOf(node, ctx, element, spec.common); - return ui::button(std::move(spec)); - } - if (kind == "textInput") { - std::string const commitOn = node.name("commitOn").empty() ? "change" : std::string{node.name("commitOn")}; - auto const commit = [this, ctx, element, commitOn, onChange = node.event("onChange")]( - std::string const& when, std::string const& text) { - if (commitOn != when) { - return; - } - if (element->bound == nullptr) { - session.noteWrite(); - element->committed.set(Value{text}); - } - runEvent(onChange, ctx, Value{text}); - }; - TextInput spec; - spec.value = - slotProp([this, element] { return textOf(element->draft.get(), session.formatting()); }); - spec.onChange = [this, element, commit](std::string text) { - session.asUser([&] { - session.noteWrite(); - element->draft.set(Value{text}); - element->edited.set(true); - }); - commit("change", text); - }; - spec.onCommit = [this, ctx, element, commit, onCommit = node.event("onCommit")](std::string const& text) { - element->touched.set(true); - commit("blur", text); - runEvent(onCommit, ctx, Value{text}); - }; - // Only a field that does something on Enter submits: one without `onSubmit` that does not commit on Enter - // lets Enter go on to its ancestors' chords, a dialog's `default` among them. - if (Commands const* const onSubmit = node.event("onSubmit"); onSubmit != nullptr || commitOn == "enter") { - spec.onSubmit = [this, ctx, commit, onSubmit](std::string const& text) { - commit("enter", text); - runEvent(onSubmit, ctx, Value{text}); - }; - } - spec.placeholder = kit.textProp("placeholder"); - std::string const mode = kit.onceText("mode"); - spec.mode = TextInputMode::SingleLine; - if (mode == "multiline") { - spec.mode = TextInputMode::Multiline; - } else if (mode == "password") { - spec.mode = TextInputMode::Password; - } - // A multiline input shows no unit and no icon; a computed mode that turns out multiline is reported and - // its unit and icon left out, so the mount never meets them there. The loader refuses a literal one. - for (std::string_view const key : { - std::string_view{"unit"}, - std::string_view{"icon"}, - std::string_view{"prefix"}, - std::string_view{"decimals"}, - }) { - if (ExprPtr const given = node.prop(key); given != nullptr && spec.mode == TextInputMode::Multiline) { - report(given->path, "a multiline input shows no " + std::string{key}); - } - } - spec.mono = node.flag("mono"); - spec.wrap = spec.mode != TextInputMode::Multiline || node.flag("wrap", true); - if (spec.mode != TextInputMode::Multiline) { - spec.emphasis = node.name("emphasis") == "prominent" ? InputEmphasis::Prominent : InputEmphasis::Normal; - spec.icon = kit.onceText("icon"); - spec.align = alignOf(node.name("align")); - if (spec.align == Align::Stretch) { - spec.align = Align::Start; - } - if (node.prop("unit")) { - spec.unit = kit.textProp("unit"); - } - if (node.prop("prefix")) { - spec.prefix = kit.textProp("prefix"); - } - if (ExprPtr const places = node.prop("decimals")) { - spec.decimals = bindProp(ctx, places, -1, placesOf); - } - } - fieldOf(node, ctx, element, spec.field); - commonOf(node, ctx, element, spec.common); - kit.nameByLabel(spec.common); - kit.captionOf(spec); - return ui::textInput(std::move(spec)); - } - if (kind == "checkbox") { - Checkbox spec{ - .label = kit.textProp("label"), - .checked = slotProp([read = kit.read("checked")] { - Value const value = read(); - bool const* const flag = value.asBool(); - return flag != nullptr && *flag; - }), - }; - spec.onToggle = [this, ctx, element, onToggle = node.event("onToggle"), - onChange = node.event("onChange")](bool checked) { - // A toggle is a check box's commit, so it touches the box. - session.asUser([&] { - if (element->bound == nullptr) { - session.noteWrite(); - element->draft.set(checked); - } - element->touched.set(true); - }); - runEvent(onToggle, ctx, Value{checked}); - runEvent(onChange, ctx, Value{checked}); - }; - fieldOf(node, ctx, element, spec.field); - commonOf(node, ctx, element, spec.common); - return ui::checkbox(std::move(spec)); - } - if (kind == "select") { - Select spec; - spec.options = slotProp>( - [scope = ctx.scope, element] { return selectOptions(element->rows->get(), scope->formatting()); }); - spec.selected = slotProp>([read = kit.read("selected")] -> std::optional { - Value const selected = read(); - return selected.isNull() ? std::nullopt : std::optional{keyOf(selected)}; - }); - spec.onSelect = [this, ctx, element, onChoose = node.event("onChoose"), - onChange = node.event("onChange")](Key const& key) { - Value const chosen = valueOfKey(key); - // A choice is a select's commit, so it touches the select. - session.asUser([&] { - if (element->bound == nullptr) { - session.noteWrite(); - element->draft.set(chosen); - } - element->touched.set(true); - }); - runEvent(onChoose, ctx, chosen); - runEvent(onChange, ctx, chosen); - }; - // A computed style of no known name is reported once and drawn as a dropdown; the loader refuses a constant - // one. - if (ExprPtr const style = node.prop("style")) { - std::string const name = textOf(once(ctx, style), ctx.scope->formatting()); - if (name == "radio") { - spec.style = SelectStyle::Radio; - } else if (name == "segmented") { - spec.style = SelectStyle::Segmented; - } else if (name != "dropdown") { - report(style->path, "style is `" + name + "`; a select's style is dropdown, radio or segmented"); - } - } - fieldOf(node, ctx, element, spec.field); - commonOf(node, ctx, element, spec.common); - kit.nameByLabel(spec.common); - kit.captionOf(spec); - return ui::select(std::move(spec)); - } - if (kind == "slider") { - Slider spec; - spec.value = slotProp([read = kit.read("value"), element] { - return intOf(element->bound != nullptr ? read() : element->draft.get(), 0); - }); - spec.minimum = kit.onceInt("min", 0); - spec.maximum = kit.onceInt("max", 100); - spec.step = kit.onceInt("step", 1); - spec.onChange = [this, ctx, element, onChange = node.event("onChange")](std::int64_t value) { - session.asUser([&] { - session.noteWrite(); - element->draft.set(value); - element->edited.set(true); - if (element->bound == nullptr) { - element->committed.set(value); - } - }); - runEvent(onChange, ctx, Value{value}); - }; - spec.onCommit = [this, ctx, element, onCommit = node.event("onCommit")](std::int64_t value) { - element->touched.set(true); - runEvent(onCommit, ctx, Value{value}); - }; - fieldOf(node, ctx, element, spec.field); - commonOf(node, ctx, element, spec.common); - kit.nameByLabel(spec.common); - return ui::slider(std::move(spec)); - } - if (kind == "dateTimeInput") { - DateTimeInput spec; - DateMode const mode = kit.onceText("mode") == "date" ? DateMode::Date : DateMode::DateTime; - std::optional heldAtLoad; - if (auto const found = _doc->dateValueKinds.find(&node); found != _doc->dateValueKinds.end()) { - heldAtLoad = found->second; - } - std::string const valuePath = pointerAppend(node.path, "value"); - std::int32_t const offsetMinutes = format.utcOffsetMinutes; - spec.value = slotProp>([this, element, offsetMinutes, - valuePath] -> std::optional { - DateReading const reading = dateInstantOf(element->draft.get(), offsetMinutes); - if (!reading.readable) { - report(valuePath, "`dateTimeInput` shows a timestamp or an ISO-8601 date or date-time string"); - } - return reading.instant ? std::optional{time::Timestamp{*reading.instant}} : std::nullopt; - }); - spec.onChange = [this, ctx, element, heldAtLoad, mode, offsetMinutes, onChange = node.event("onChange"), - onCommit = node.event("onCommit")](std::optional value) { - bool asString = element->bound != nullptr && element->bound->get().asString() != nullptr; - if (heldAtLoad) { - asString = *heldAtLoad == TypeKind::String; - } - std::optional const instant = value ? value->value : std::nullopt; - Value entered; - if (!asString) { - if (instant) { - entered = Value{*instant}; - } - } else if (!instant) { - entered = Value{std::string{}}; - } else if (mode == DateMode::Date) { - entered = Value{dateTextOf(*instant, offsetMinutes)}; - } else { - entered = Value{instant->toIso8601()}; - } - element->touched.set(true); - session.asUser([&] { - session.noteWrite(); - element->draft.set(entered); - element->edited.set(true); - if (element->bound == nullptr) { - element->committed.set(entered); - } - }); - runEvent(onChange, ctx, entered); - runEvent(onCommit, ctx, entered); - }; - spec.mode = mode; - spec.offsetMinutes = offsetMinutes; - // Tracked: a locale switch changes the pattern the screen's dates are written in, and the input follows. - spec.pattern = slotProp([this, mode] { - FormatContext const& now = session.formatting(); - return mode == DateMode::Date ? now.datePattern : now.dateTimePattern; - }); - fieldOf(node, ctx, element, spec.field); - commonOf(node, ctx, element, spec.common); - kit.nameByLabel(spec.common); - kit.captionOf(spec); - return ui::dateTimeInput(std::move(spec)); - } - if (kind == "filePicker") { - FilePicker spec; - spec.path = - slotProp([this, element] { return textOf(element->draft.get(), session.formatting()); }); - spec.onPicked = [this, ctx, element, onPick = node.event("onPick")](std::string path) { - session.asUser([&] { - session.noteWrite(); - element->draft.set(Value{path}); - element->committed.set(Value{path}); - }); - runEvent(onPick, ctx, Value{path}); - }; - spec.mode = kit.onceText("mode") == "save" ? FilePickerMode::Save : FilePickerMode::Open; - fieldOf(node, ctx, element, spec.field); - commonOf(node, ctx, element, spec.common); - kit.nameByLabel(spec.common); - return ui::filePicker(std::move(spec)); - } - if (kind == "menu") { - Menu spec{.items = menuItems(node.partList("items"), ctx)}; - if (node.name("style") == "button") { - spec.style = MenuStyle::Button; - spec.label = kit.textProp("label"); - spec.icon = kit.onceText("icon"); - if (node.name("emphasis") == "primary") { - spec.emphasis = ButtonEmphasis::Primary; - } else if (node.name("emphasis") == "danger") { - spec.emphasis = ButtonEmphasis::Danger; - } else if (node.name("emphasis") == "ghost") { - spec.emphasis = ButtonEmphasis::Ghost; - } - } - commonOf(node, ctx, element, spec.common); - return ui::menu(std::move(spec)); - } - return std::nullopt; -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of ui/1. -std::optional ScreenCore::lowerDisplay(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - std::string_view const kind = node.kind; - KindKit const kit{*this, node, ctx, element}; - if (kind == "banner") { - Banner spec{.tone = bindProp(ctx, node.prop("tone"), Tone::Info, toneOf)}; - if (ExprPtr const spans = node.prop("spans")) { - spec.spans = spansProp(ctx, spans); - } else { - spec.text = kit.textProp("text"); - } - spec.action = kit.actionPart(); - spec.dismissible = kit.onceBool("dismissible", false); - spec.onDismiss = kit.action("onDismiss"); - spec.actionStyle = bannerActionStyleNamed(node.name("actionStyle")).value_or(BannerActionStyle::Ghost); - spec.actionStretch = node.flag("actionStretch"); - commonOf(node, ctx, element, spec.common); - return ui::banner(std::move(spec)); - } - if (kind == "badge") { - Badge spec{ - .tone = bindProp(ctx, node.prop("tone"), Tone::Neutral, toneOf), - .text = kit.textProp("text"), - }; - spec.icon = kit.onceText("icon"); - std::string_view const style = node.name("style"); - spec.style = BadgeStyle::Filled; - if (style == "outline") { - spec.style = BadgeStyle::Outline; - } else if (style == "quiet") { - spec.style = BadgeStyle::Quiet; - } - spec.shape = shapeNamed(node.name("shape")).value_or(ControlShape::Default); - spec.mono = node.flag("mono"); - if (Commands const* const onRemove = node.event("onRemove")) { - spec.onRemove = [this, ctx, onRemove] { runEvent(onRemove, ctx, Value{}); }; - spec.removeLabel = kit.textProp("removeLabel"); - } - commonOf(node, ctx, element, spec.common); - return ui::badge(std::move(spec)); - } - if (kind == "progress") { - Progress spec; - spec.value = slotProp>( - [scope = ctx.scope, bindings = ctx.bindings, expr = node.prop("value")] -> std::optional { - Value const value = evalIn(*scope, bindings.get(), expr); - if (std::int64_t const* const number = value.asInt()) { - return static_cast(*number); - } - if (Decimal const* const number = value.asDecimal()) { - return realOf(number->value); - } - return std::nullopt; - }); - spec.label = kit.textProp("label"); - commonOf(node, ctx, element, spec.common); - return ui::progress(std::move(spec)); - } - if (kind == "steps") { - Steps spec; - spec.items = - slotProp>([scope = ctx.scope, bindings = ctx.bindings, expr = node.prop("items")] { - std::vector steps; - Value const items = evalIn(*scope, bindings.get(), expr); - if (ValueList const* const list = items.asList()) { - for (Value const& item : *list) { - Value const* const label = item.field("label"); - Value const* const state = item.field("state"); - Value const* const detail = item.field("detail"); - std::string const name = state == nullptr ? std::string{} : textOf(*state, {}); - steps.push_back(Step{ - .label = label == nullptr ? std::string{} : textOf(*label, scope->formatting()), - .state = stepStateOf(name), - .detail = detail == nullptr ? std::string{} : textOf(*detail, scope->formatting()), - }); - } - } - return steps; - }); - spec.current = slotProp>( - [scope = ctx.scope, bindings = ctx.bindings, expr = node.prop("current")] -> std::optional { - std::int64_t const index = intOf(evalIn(*scope, bindings.get(), expr), -1); - return index < 0 ? std::nullopt : std::optional{static_cast(index)}; - }); - spec.labelled = bindProp(ctx, node.prop("labelled"), true, boolOf); - commonOf(node, ctx, element, spec.common); - return ui::steps(std::move(spec)); - } - if (kind == "chart") { - return lowerChart(node, ctx, element); - } - if (kind == "keyValue") { - KeyValue spec; - spec.captions = node.name("fieldLayout") == "stacked" ? CaptionPlacement::Above : CaptionPlacement::Beside; - // The loader has checked `captionWidth` is a literal integer. - if (ExprPtr const width = node.prop("captionWidth")) { - spec.captionWidth = static_cast(*width->literal.asInt()); - } - spec.items = slotProp>( - [this, scope = ctx.scope, bindings = ctx.bindings, expr = node.prop("items")] { - std::vector out; - Value const items = evalIn(*scope, bindings.get(), expr); - if (ValueList const* const list = items.asList()) { - for (Value const& item : *list) { - out.push_back(keyValueItemOf(item, expr->path, *scope)); - } - } - return out; - }); - commonOf(node, ctx, element, spec.common); - return ui::keyValue(std::move(spec)); - } - if (kind == "emptyState") { - EmptyState spec{.title = kit.textProp("title"), .text = kit.textProp("text")}; - spec.icon = kit.onceText("icon"); - spec.action = kit.actionPart(); - commonOf(node, ctx, element, spec.common); - return ui::emptyState(std::move(spec)); - } - return std::nullopt; -} - -Node ScreenCore::lowerStack(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - std::string_view const kind = node.kind; - KindKit const kit{*this, node, ctx, element}; - int const gap = static_cast(kit.onceInt("gap", 0)); - if (std::string const arrangement = arrangedBy(node.id); !arrangement.empty()) { - return lowerArranged(node, ctx, element, arrangement, kind == "column" ? Axis::Vertical : Axis::Horizontal, - gap); - } - if (kind == "column") { - Column spec{ - .children = kit.children("children", gap), - .gap = gap, - .align = alignOf(node.name("align")), - .justify = justifyOf(node.name("justify")), - .divided = node.flag("divided"), - .padding = kit.stackPadding(), - }; - if (node.prop("selected")) { - spec.selected = bindProp(ctx, node.prop("selected"), false, boolOf); - } - commonOf(node, ctx, element, spec.common); - return ui::column(std::move(spec)); - } - Row spec{ - .children = kit.children("children"), - .gap = gap, - .align = alignOf(node.name("align")), - .justify = justifyOf(node.name("justify")), - .wrap = node.flag("wrap"), - .divided = node.flag("divided"), - .padding = kit.stackPadding(), - }; - if (node.prop("selected")) { - spec.selected = bindProp(ctx, node.prop("selected"), false, boolOf); - } - commonOf(node, ctx, element, spec.common); - return ui::row(std::move(spec)); -} - -Node ScreenCore::lowerGrid(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - KindKit const kit{*this, node, ctx, element}; - Grid spec{ - .columns = static_cast(kit.onceInt("columns", 1)), - .gap = static_cast(kit.onceInt("gap", 0)), - .align = alignOf(node.name("align")), - .minColumnWidth = static_cast(kit.onceInt("minColumnWidth", 0)), - }; - for (DocNodePtr const& track : node.partList("tracks")) { - ExprPtr const width = track->prop("width"); - spec.tracks.push_back(GridTrack{ - .width = width ? sizingOf(once(ctx, width)) : Sizing::stretch(), - .align = cellPlaceNamed(track->name("align")).value_or(Align::Start), - }); - } - for (DocNodePtr const& cell : node.nodes("children")) { - ExprPtr const span = cell->prop("span"); - spec.cells.push_back( - GridCell{.node = lower(*cell, ctx), .span = static_cast(span ? intOf(once(ctx, span), 1) : 1)}); - } - commonOf(node, ctx, element, spec.common); - return ui::grid(std::move(spec)); -} - -Node ScreenCore::lowerPanel(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - KindKit const kit{*this, node, ctx, element}; - Panel spec{.title = kit.textProp("title"), .padding = static_cast(kit.onceInt("padding", 0))}; - spec.header = kit.child("header"); - spec.child = kit.child("children", static_cast(kit.onceInt("gap", kPanelGap))); - spec.collapsible = kit.onceBool("collapsible", false); - spec.collapsed = bindProp(ctx, node.prop("collapsed"), false, boolOf); - if (Commands const* const commands = node.event("onToggle")) { - spec.onToggle = [this, ctx, commands](bool collapsed) { runEvent(commands, ctx, Value{collapsed}); }; - } - commonOf(node, ctx, element, spec.common); - return ui::panel(std::move(spec)); -} - -Node ScreenCore::lowerSplitter(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - KindKit const kit{*this, node, ctx, element}; - ExprPtr const orientation = node.prop("orientation"); - Splitter spec{ - .children = kit.children("children"), - .orientation = - orientation && axisOf(once(ctx, orientation)) == Axis::Vertical ? Axis::Vertical : Axis::Horizontal, - }; - // No `onResize`: a user's drag stays the splitter's own, and the document's sizes are where it starts. - if (ExprPtr const sizes = node.prop("sizes")) { - spec.sizes = bindProp>( - ctx, sizes, {}, [this, path = sizes->path](Value const& value, FormatContext const& /*format*/) { - std::optional> parsed = splitterSizesOf(value); - if (!parsed) { - report(path, "sizes is " + canonicalJson(value) + "; sizes is a list of numbers, one per pane"); - } - return std::move(parsed).value_or(std::vector{}); - }); - } - commonOf(node, ctx, element, spec.common); - // A literal `sizes` that matches the panes places them, so a pane's own width is not used. - if (ExprPtr const sizes = node.prop("sizes"); sizes && sizes->kind == ExprKind::Literal) { - std::optional> const given = splitterSizesOf(sizes->literal); - if (given && given->size() == spec.children.size()) { - for (std::size_t at = 0; at < spec.children.size(); ++at) { - // A stretch pane asks only to fill, which `sizes` leaves it to do; a fixed or percent pane names a - // size. - Sizing::Kind const kind = layoutHintsOf(spec.children.at(at)).width.kind; - if (spec.orientation == Axis::Horizontal && - (kind == Sizing::Kind::Fixed || kind == Sizing::Kind::Percent)) { - report(sizes->path, "this splitter's `sizes` places its panes; pane " + std::to_string(at) + - "'s sizing is not used"); - } - } - } - } - return ui::splitter(std::move(spec)); -} - -void ScreenCore::reportActionBarGaps(DocNode const& bar, LowerCtx const& ctx) { - for (DocNodePtr const& child : bar.nodes("children")) { - if (child->kind != "forEach" || child->prop("gap") == nullptr) { - continue; - } - ExprPtr const axis = child->prop("axis"); - if (axis != nullptr && axis->kind != ExprKind::Literal && axisOf(once(ctx, axis)) == Axis::Horizontal) { - report(child->path + "/gap", kActionBarGapRefusal); - } - } -} - -Node ScreenCore::lowerCollapsible(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - KindKit const kit{*this, node, ctx, element}; - Collapsible spec{.title = kit.textProp("title"), .open = bindProp(ctx, node.prop("open"), true, boolOf)}; - if (Commands const* const commands = node.event("onToggle")) { - spec.onToggle = [this, ctx, commands](bool open) { runEvent(commands, ctx, Value{open}); }; - } - spec.header = kit.child("header"); - spec.child = kit.child("children", static_cast(kit.onceInt("gap", kPanelGap))); - commonOf(node, ctx, element, spec.common); - return ui::collapsible(std::move(spec)); -} - -Node ScreenCore::lowerDropZone(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - KindKit const kit{*this, node, ctx, element}; - DropZone spec; - spec.accept = stringsOf(node.prop("accept") ? once(ctx, node.prop("accept")) : Value{}); - spec.multiple = kit.onceBool("multiple", false); - if (Commands const* const commands = node.event("onDrop")) { - spec.onDrop = [this, ctx, commands](std::vector const& paths) { - runEvent(commands, ctx, listOfStrings(paths)); - }; - } - spec.child = kit.child("children"); - commonOf(node, ctx, element, spec.common); - return ui::dropZone(std::move(spec)); -} - -Node ScreenCore::lowerPage(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - KindKit const kit{*this, node, ctx, element}; - Page spec; - spec.geometry = pageGeometryOf(node); - std::optional const outer = std::exchange(pageBeingLowered, spec.geometry); - spec.children = kit.children("children"); - pageBeingLowered = outer; - commonOf(node, ctx, element, spec.common); - return ui::page(std::move(spec)); -} - -Node ScreenCore::lowerPageRegion(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - if (!pageBeingLowered) { - report(node.path, "a page region belongs in a page"); - return ui::text(Text{.text = std::string{}, .role = TextRole::Muted}); - } - KindKit const kit{*this, node, ctx, element}; - PageRegion spec; - spec.geometry = regionGeometryOf(node, *pageBeingLowered); - std::optional const outer = std::exchange(pageBeingLowered, std::nullopt); - spec.children = kit.children("children"); - pageBeingLowered = outer; - commonOf(node, ctx, element, spec.common); - return ui::pageRegion(std::move(spec)); -} - -Node ScreenCore::lowerLocaleScope(DocNode const& node, LowerCtx const& ctx) { - auto const holder = std::make_shared(*this, ctx.scope, nullptr, ctx.scope->nodes.depth() + 2); - holder->transparent = true; - ExprPtr const locale = node.prop("locale"); - holder->localeFormat = &holder->nodes.computed([this, scope = ctx.scope, bindings = ctx.bindings, - locale] -> std::shared_ptr { - Value const value = evalIn(*scope, bindings.get(), locale); - std::string const* const tag = value.asString(); - if (tag == nullptr && !value.isNull()) { - report(locale->path, "the locale is " + canonicalJson(value) + "; a locale is a BCP 47 tag, a string"); - } - if (tag == nullptr || tag->empty()) { - return session.sharedFormatting(); - } - if (session.firstUnlistedLocale(*tag)) { - report(locale->path, "no formatting facts for locale `" + *tag + "`; numbers, money and dates use en's"); - } - return session.scopedFormatting(*tag); - }); - // The children are mounted again whenever the tag changes: a value a node reads once, as it is lowered (a - // table's column labels, a `once` property, a literal), is written in the facts at that moment, and only a new - // lowering writes it in the new ones. The key is the tag as the scope resolves it; a tag that is not known yet - // is the key `""`, apart from every tag. - std::vector content; - for (DocNodePtr const& child : node.nodes("children")) { - content.push_back(child.get()); - } - LayoutHints const hints = holderHints(content, nullptr, ctx); - Switch spec; - spec.selector = slotProp([scope = ctx.scope, bindings = ctx.bindings, locale] { - Value const value = evalIn(*scope, bindings.get(), locale); - std::string const* const tag = value.asString(); - return Key{tag == nullptr ? std::string{} : *tag}; - }); - spec.fallback = lazy( - [this, ctx, holder, content, path = node.path] -> Node { - auto const inner = std::make_shared(*this, holder, nullptr, holder->nodes.depth() + 2); - inner->transparent = true; - LowerCtx const innerCtx{.scope = inner, .bindings = ctx.bindings, .boundary = ctx.boundary, .listGap = 0}; - std::vector children; - children.reserve(content.size()); - for (DocNode const* const child : content) { - children.push_back(lower(*child, innerCtx)); - } - fillHolder(children, path); - return holding(std::move(children), inner, {}, 0); - }, - hints); - commonOf(node, ctx, nullptr, spec.common); - return ui::switchOf(std::move(spec)); -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of ui/1. -Node ScreenCore::lowerKind(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - std::string_view const kind = node.kind; - KindKit const kit{*this, node, ctx, element}; - if (std::optional widget = lowerWidget(node, ctx, element)) { - return std::move(*widget); - } - if (kind == "group") { - return lowerGroup(node, ctx, element, kit.children("children")); - } - if (kind == "column" || kind == "row") { - return lowerStack(node, ctx, element); - } - if (kind == "grid") { - return lowerGrid(node, ctx, element); - } - if (kind == "spacer") { - Spacer spec; - commonOf(node, ctx, element, spec.common); - return ui::spacer(std::move(spec)); - } - if (kind == "panel") { - return lowerPanel(node, ctx, element); - } - if (kind == "scroll") { - ExprPtr const axis = node.prop("axis"); - Scroll spec{.child = kit.child("children"), .axis = axis ? axisOf(once(ctx, axis)) : Axis::Vertical}; - commonOf(node, ctx, element, spec.common); - return ui::scroll(std::move(spec)); - } - if (kind == "switch") { - return lowerSwitch(node, ctx); - } - if (kind == "tabs") { - return lowerTabs(node, ctx, element); - } - if (kind == "dialog" || kind == "drawer") { - return lowerDialog(node, ctx, element); - } - if (kind == "busy") { - Busy spec{.active = bindProp(ctx, node.prop("active"), false, boolOf), .label = kit.textProp("label")}; - commonOf(node, ctx, element, spec.common); - return ui::busy(std::move(spec)); - } - if (kind == "forEach" || kind == "table") { - return lowerRows(node, ctx, element); - } - if (std::optional display = lowerDisplay(node, ctx, element)) { - return std::move(*display); - } - if (kind == "splitter") { - return lowerSplitter(node, ctx, element); - } - if (kind == "collapsible") { - return lowerCollapsible(node, ctx, element); - } - if (kind == "dropZone") { - return lowerDropZone(node, ctx, element); - } - if (kind == "actionBar") { - KindKit const bar{*this, node, ctx, element}; - ActionBar spec{ - .children = bar.children("children"), - .align = alignOf(node.name("align")), - .justify = justifyOf(node.name("justify")), - .wrap = node.flag("wrap"), - }; - reportActionBarGaps(node, ctx); - commonOf(node, ctx, element, spec.common); - return ui::actionBar(std::move(spec)); - } - if (kind == "page") { - return lowerPage(node, ctx, element); - } - if (kind == "pageRegion") { - return lowerPageRegion(node, ctx, element); - } - if (kind == "localeScope") { - return lowerLocaleScope(node, ctx); - } - if (kind == "boundary") { - return lowerBoundary(node, ctx); - } - if (kind == "custom") { - return lowerCustom(node, ctx); - } - if (kind == "customize") { - return lowerCustomize(node, ctx); - } - if (kind == "form") { - return lowerForm(node, ctx, element); - } - if (kind == "collection" || kind == "wizard") { - return lowerComposite(node, ctx, element); - } - report(node.path, "`" + node.kind + "` is a node kind this interpreter does not lower"); - return ui::text(Text{.text = std::string{node.kind}, .role = TextRole::Muted}); -} - -namespace { - -/// @brief A document field overlay's expressions, evaluated once, as the engine's overlay. -/// @param scope The scope the form is declared in. -/// @param part The `fields` entry. -/// @param format How values read as text and numbers. -/// @return The overlay. -[[nodiscard]] forms::FieldOverlay overlayOf(RtScope const& scope, DocNode const& part, FormatContext const& format) { - auto const read = [&](std::string_view key) -> std::optional { - ExprPtr const expr = part.prop(key); - if (!expr) { - return std::nullopt; - } - return scope.core.runtime().untracked([&] { return evalIn(scope, nullptr, expr); }); - }; - auto const text = [&](std::string_view key) -> std::optional { - auto const value = read(key); - return value.has_value() && !value->isNull() ? std::optional{textOf(*value, format)} - : std::nullopt; - }; - auto const flag = [&](std::string_view key) { - auto const value = read(key); - bool const* const set = value.has_value() ? value->asBool() : nullptr; - return set != nullptr && *set; - }; - forms::FieldOverlay overlay{.omit = flag("omit"), .hidden = flag("hidden")}; - overlay.label = text("label"); - overlay.unit = text("unit"); - overlay.widget = text("widget"); - if (auto const decimals = read("decimals"); - decimals.has_value() && decimals->asInt() != nullptr && *decimals->asInt() >= 0) { - overlay.decimals = static_cast(std::min(*decimals->asInt(), 18)); - } - if (auto const blankAs = text("blankAs")) { - overlay.blankAs = *blankAs == "empty" ? forms::BlankAs::Empty : forms::BlankAs::Omit; - } - return overlay; -} - -/// @brief A lowering context whose scope is held weakly: what an Effect the scope itself owns may keep, so the scope -/// does not keep itself alive. -struct DetachedLower { - /// @brief The scope, weakly. - std::weak_ptr scope; - /// @brief The names bound there. - std::shared_ptr bindings; - /// @brief The innermost boundary. - std::shared_ptr boundary; -}; - -/// @brief Detaches a lowering context's scope. -/// @param ctx The context. -/// @return The context, its scope held weakly. -[[nodiscard]] DetachedLower detachedLower(LowerCtx const& ctx) { - return DetachedLower{.scope = ctx.scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; -} - -/// @brief Puts a detached context's scope back. -/// @param held The detached context. -/// @return The context; its scope is null once the scope is gone. -[[nodiscard]] LowerCtx attached(DetachedLower const& held) { - return LowerCtx{.scope = held.scope.lock(), .bindings = held.bindings, .boundary = held.boundary}; -} -} // namespace - -// Builds the form's session when its element is declared, so its values can be read before the form is drawn. -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per kind of form element and its sessions. -void ScreenCore::wireForm(ElementState& element) { - DocNode const& node = *element.node; - RtScope& scope = *element.scope; - std::string const action{node.name("action")}; - Catalog const& catalog = session.options().catalog; - std::optional const schema = catalog.schema ? catalog.schema(action) : std::nullopt; - if (!schema.has_value()) { - report(node.path, "no schema for `" + action + "`: the catalog has none for a `form` to build from"); - return; - } - NameRef const* const alias = scope.find(node.name("model")); - if (alias == nullptr || alias->model == nullptr) { - report(node.path, "`" + std::string{node.name("model")} + "` is not a model alias"); - return; - } - forms::FieldOverlays overlays; - // `fields` is one record part holding a `field` part per overlaid member. - for (DocNodePtr const& record : node.partList("fields")) { - for (DocNodePtr const& part : record->partList("fields")) { - forms::FieldOverlay overlay = overlayOf(scope, *part, session.formatting()); - // A computed `decimals` is carried by the effect below alone: baking the value read now would make it - // the fallback when the expression later gives no places, where the schema's places belong. - if (ExprPtr const places = part->prop("decimals"); places && places->kind != ExprKind::Literal) { - overlay.decimals.reset(); - } - overlays.insert_or_assign(part->id, std::move(overlay)); - } - } - auto model = forms::FormModel::fromSchema(action, *schema, overlays); - if (!model) { - report(node.path, - "the form of `" + action + "` does not build: " + model.error().path + ": " + model.error().message); - return; - } - if (node.name("submit") == "explicit") { - model = model->withSubmitMode(forms::SubmitMode::Explicit); - } else if (node.name("submit") == "auto") { - model = model->withSubmitMode(forms::SubmitMode::Automatic); - } - element.form = std::make_unique(runtime(), *std::move(model), aliasSubmits(alias->model), - aliasCalls(alias->model), engineOptions()); - followFormatting(element, scope); - // An overlay's `decimals` follows its expression: the field keeps the draft as typed and checks it again against - // the places the expression gives now. - for (DocNodePtr const& record : node.partList("fields")) { - for (DocNodePtr const& part : record->partList("fields")) { - ExprPtr const places = part->prop("decimals"); - if (!places) { - continue; - } - forms::FieldState* state = nullptr; - try { - state = &element.form->field(part->id); - } catch (std::out_of_range const&) { - continue; // The overlay names a field the form does not have (an omitted one). - } - scope.nodes.effect([this, &scope, places, state] { - int const now = placesOf(evalIn(scope, nullptr, places), session.formatting()); - runtime().untracked([&] { - state->places().set(now >= 0 ? std::optional{static_cast(now)} - : std::nullopt); - }); - }); - } - } - if (ExprPtr const prefill = node.prop("prefill")) { - // A prefill follows its expression. A value of the record being edited (the first value, or one under the - // same `key`) keeps the fields the user changed; another record, a new `key`, or any later value of a form - // without one, loads every field. - forms::FormSession* const form = element.form.get(); - struct Followed { - bool loaded = false; - Value key; - }; - auto const followed = std::make_shared(); - scope.nodes.effect([this, &scope, prefill, key = node.prop("key"), form, followed] { - Value const value = evalIn(scope, nullptr, prefill); - if (value.isNull()) { - return; - } - runtime().untracked([&] { - Value const current = key ? evalIn(scope, nullptr, key) : Value{}; - bool const same = !followed->loaded || (key && current == followed->key); - followed->loaded = true; - followed->key = current; - std::string const json = glz::write_json(valueToJson(value)).value_or(std::string{}); - if (same) { - form->refill(json); - } else { - form->prefill(json); - } - }); - }); - } -} - -Node ScreenCore::lowerForm(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - forms::FormSession* const form = element == nullptr ? nullptr : element->form.get(); - if (form == nullptr) { - return ui::text(Text{.text = std::string{node.name("action")}, .role = TextRole::Muted}); - } - // The form's events, each run once per change of the count it watches. - auto const watch = [this, &ctx](Commands const* commands, auto count, auto payload) { - if (commands == nullptr || commands->empty()) { - return; - } - auto const seen = std::make_shared(runtime().untracked(count)); - ctx.scope->nodes.effect([this, held = detachedLower(ctx), commands, count, payload, seen] { - std::uint64_t const now = count(); - if (now == *seen) { - return; - } - *seen = now; - runtime().untracked([&] { runEvent(commands, attached(held), payload()); }); - }); - }; - watch( - node.event("onSubmit"), [form] { return form->submitAttempts(); }, - [form] { - std::optional const body = form->body(); - return body.has_value() ? jsonTextValue(*body) : Value{}; - }); - watch( - node.event("onSuccess"), [form] { return form->successCount(); }, - [form] { - std::optional const& reply = form->lastReply(); - return reply.has_value() ? jsonTextValue(*reply) : Value{}; - }); - if (Commands const* const onError = node.event("onError"); onError != nullptr && !onError->empty()) { - // Each failure is a new exception: run once per failure, with its text. - auto const seen = - std::make_shared(runtime().untracked([form] { return form->lastError(); })); - ctx.scope->nodes.effect([this, held = detachedLower(ctx), onError, form, seen] { - std::exception_ptr const error = form->lastError(); - if (error == nullptr || error == *seen) { - return; - } - *seen = error; - runtime().untracked([&] { runEvent(onError, attached(held), Value{failureText(error)}); }); - }); - } - forms::FormViewOptions options{.showTitle = false}; - presentForm(node, ctx, options); - options.title = bindProp(ctx, node.prop("title"), std::string{}, stringOf); - // A field whose overlay names a component is drawn by it; only top-level fields take one, as every overlay. - for (DocNodePtr const& record : node.partList("fields")) { - for (DocNodePtr const& overlay : record->partList("fields")) { - if (!overlay->name("component").empty()) { - options.overrides.byField(overlay->id, - [this, ctx, field = overlay.get()](forms::FieldView const& view) { - return fieldComponent(view, *field, ctx); - }); - } - } - } - Column column{.children = {forms::formView(*form, std::move(options))}}; - commonOf(node, ctx, element, column.common); - return ui::column(std::move(column)); -} - -[[nodiscard]] std::expected changeWire(std::string const& payload, - std::string_view type) { - std::string_view text{payload}; - if (type == "string") { - if (text.starts_with("s:")) { - text.remove_prefix(2); - } - // Parentheses: braces would pick the initializer-list constructor and make a one-element array. - return forms::detail::engine::Json(std::string{text}); - } - if (text.starts_with("i:")) { - text.remove_prefix(2); - } - std::optional json = forms::detail::engine::parseJson(text); - if (!json) { - return std::unexpected(std::string{"it is not JSON"}); - } - bool const fits = type == "json" || json->is_null() || (type == "bool" && json->is_boolean()) || - ((type == "int" || type == "number") && json->is_number()) || - (type == "exact" && (json->is_number() || json->is_string())); - if (!fits) { - bool const vowel = type == "int" || type == "exact"; - return std::unexpected("it is not " + std::string{vowel ? "an " : "a "} + std::string{type}); - } - return *std::move(json); -} - -namespace { - -/// @brief What a form fills of a field component's props: the field's value, errors, read-only and required state, -/// and label, each a tracked read of the field. -/// @param prop The prop's name. -/// @param state The field. -/// @return The read, or empty for a prop the form does not fill. -[[nodiscard]] std::function formFilled(std::string const& prop, forms::FieldState const* state) { - if (prop == "value") { - return [state] { - forms::Encoding const& encoding = state->encoded().get(); - if (!encoding.has_value() || !encoding->has_value()) { - return Value{}; - } - return (*encoding)->value.isNull() ? jsonTextValue((*encoding)->json) : (*encoding)->value; - }; - } - if (prop == "errors") { - return [state] { - std::optional const& error = state->error().get(); - return error.has_value() ? Value{ValueList{Value{error->message}}} : Value{ValueList{}}; - }; - } - if (prop == "readonly") { - return [state] { return Value{state->readonly().get()}; }; - } - if (prop == "required") { - return [state] { return Value{state->required().get()}; }; - } - if (prop == "label") { - return [state] { return Value{state->label()}; }; - } - return {}; -} -} // namespace - -// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): a prop's name, then its declared type. -CustomProp ScreenCore::componentProp(std::string const& prop, std::string const& type, std::function read) { - if (type == "bool") { - return CustomProp{ - .name = prop, - .value = slotProp([this, read = std::move(read)] { return boolOf(read(), session.formatting()); }), - }; - } - if (type == "number") { - return CustomProp{ - .name = prop, - .value = slotProp([read = std::move(read)] { return componentNumber(read()); }), - }; - } - return CustomProp{ - .name = prop, - .value = slotProp( - [this, read = std::move(read), type] { return componentText(read(), type, session.formatting()); }), - }; -} - -void ScreenCore::changeField(forms::FieldState& state, forms::FieldSpec const& spec, std::string const& path, - std::string_view valueType, std::string const& payload) { - auto wire = changeWire(payload, valueType); - // A base64 member holds a file's bytes, which a document moves inline only under the session's cap. - if (std::size_t const cap = session.options().maxInlineFileBytes; - wire && spec.bytes && wire->is_string() && base64Size(wire->get_string()) > cap) { - report(path, "field " + spec.name + ": " + std::to_string(base64Size(wire->get_string())) + - " bytes is over the " + std::to_string(cap) + " inline cap"); - return; - } - if (wire) { - if (auto edited = state.edit(*wire); !edited) { - wire = std::unexpected(edited.error()); - } - } - if (!wire) { - report(path, "field " + spec.name + ": the component's change does not decode: " + wire.error()); - } -} - -Node ScreenCore::fieldComponent(forms::FieldView const& view, DocNode const& overlay, LowerCtx const& ctx) { - std::string const name{overlay.name("component")}; - // A loaded document's field component is declared, with a `value` prop and a `change` event. - Component const& component = _doc->components.at(name); - forms::FieldState* const state = &view.state(); - Custom spec{ - .name = name, - .fallback = view.defaultControl(), - .props = {}, - .minVersion = - static_cast(std::clamp(component.version, 0, std::numeric_limits::max())), - .onEvent = {}, - }; - for (auto const& [prop, type] : component.props) { - if (prop == "value" && type == "json") { - // The wire JSON itself, so an object's or a collection's every digit reaches the component. - spec.props.push_back(CustomProp{ - .name = prop, - .value = slotProp([state] { - forms::Encoding const& encoding = state->encoded().get(); - return encoding.has_value() && encoding->has_value() ? (*encoding)->json : std::string{"null"}; - }), - }); - continue; - } - std::function read = formFilled(prop, state); - if (!read) { - ExprPtr given; - for (DocNodePtr const& record : overlay.partList("props")) { - if (ExprPtr const expr = record->prop(prop)) { - given = expr; - } - } - read = [scope = ctx.scope, bindings = ctx.bindings, given] { - return given ? evalIn(*scope, bindings.get(), given) : Value{}; - }; - } - spec.props.push_back(componentProp(prop, type, std::move(read))); - } - spec.onEvent = [this, state, path = overlay.path, fieldSpec = &view.spec(), - valueType = component.props.at("value")](std::string const& event, std::string const& payload) { - if (event == "change") { - changeField(*state, *fieldSpec, path, valueType, payload); - } - }; - return ui::custom(std::move(spec)); -} - -// Every call goes through the alias's channel, bound for its current instance when the call is made. -forms::Submitter ScreenCore::aliasCalls(ModelAlias* alias) { - return [this, alias](std::string_view actionId, std::string const& body) -> async::Completion { - std::shared_ptr const channel = channelOf(*alias, *this); - if (channel == nullptr) { - auto [failed, promise] = async::Completion::makeSettleable(&runtime().owner()); - promise.reject(std::make_exception_ptr(std::runtime_error{"the node's model alias is not bound"})); - return std::move(failed); - } - return channel->execute(std::string{actionId}, body, CallOptions{}); - }; -} - -// The calls of a form, collection or wizard: a success other than of @p read, the collection's own query, tells the -// session, which applies the action's effects, as a mutation's success does. -forms::Submitter ScreenCore::aliasSubmits(ModelAlias* alias, std::string read) { - return [this, alias, call = aliasCalls(alias), read = std::move(read)]( - std::string_view actionId, std::string body) -> async::Completion { - async::Completion completion = call(actionId, std::move(body)); - if (actionId != read) { - completion.then([this, alive = std::weak_ptr{_alive}, alias, typeId = alias->decl->type, - action = std::string{actionId}](std::string const& reply) { - if (alive.expired()) { - return; - } - auto json = parseJson(reply); - auto value = json ? valueFromJson(*json) : std::unexpected(json.error()); - std::string const token = runtime().untracked([&] { return alias->token->get(); }); - session.actionSucceeded(typeId, action, value ? *value : Value{}, ReplyUse::Applied, token); - }); - } - return completion; - }; -} - -// The session's locale, translations, display zone and date patterns, as every form the engine builds here reads them. -forms::FormSessionOptions ScreenCore::engineOptions() const { - FormatContext const& format = session.formatting(); - forms::FormSessionOptions options{}; - options.locale = withoutGrouping(format.numeric); - options.bcp47 = format.locale; - options.translations = format.translations; - options.displayOffsetMinutes = format.utcOffsetMinutes; - options.datePattern = format.datePattern; - options.dateTimePattern = format.dateTimePattern; - return options; -} - -// Keeps a form's, collection's or wizard's number locale, date patterns, translations and locale at the session's -// current formatting, so its field texts follow a `setLocale` or `setTranslations` without a remount. The -// engine's number locale holds views into the facts it was given, so the effect also holds the facts it last applied. -void ScreenCore::followFormatting(ElementState& element, RtScope& scope) { - auto const held = std::make_shared>(); - forms::FormSession* const form = element.form.get(); - forms::CollectionSession* const collection = element.collection.get(); - forms::WizardSession* const wizard = element.wizard.get(); - scope.nodes.effect([this, held, form, collection, wizard] { - std::shared_ptr const format = session.formattingHandle(); - runtime().untracked([&] { - render::NumericLocale const locale = withoutGrouping(format->numeric); - if (form != nullptr) { - form->setFormat(locale, format->datePattern, format->dateTimePattern); - form->setTranslations(format->translations, format->locale); - } - if (collection != nullptr) { - collection->setFormat(locale, format->datePattern, format->dateTimePattern); - collection->setTranslations(format->translations, format->locale); - } - if (wizard != nullptr) { - wizard->setFormat(locale, format->datePattern, format->dateTimePattern); - wizard->setTranslations(format->translations, format->locale); - } - *held = format; - }); - }); -} - -// Builds a collection's or wizard's session when its element is declared. The node's `action` is the collection's -// query or the wizard's first step; the catalog answers the document for it, and every call (the query, the actions, -// every step's submission) goes through the node's model alias. -void ScreenCore::wireComposite(ElementState& element) { - DocNode const& node = *element.node; - RtScope& scope = *element.scope; - bool const collection = node.kind == "collection"; - std::string const action{node.name("action")}; - Catalog const& catalog = session.options().catalog; - auto const& lookup = collection ? catalog.view : catalog.wizard; - std::optional const document = lookup ? lookup(action) : std::nullopt; - if (!document.has_value()) { - report(node.path, std::string{"no "} + (collection ? "view" : "wizard") + " document for `" + action + - "`: the catalog has none for a `" + node.kind + "` to build from"); - return; - } - NameRef const* const alias = scope.find(node.name("model")); - if (alias == nullptr || alias->model == nullptr) { - report(node.path, "`" + std::string{node.name("model")} + "` is not a model alias"); - return; - } - forms::SchemaLookup const schemas = catalog.schema ? forms::SchemaLookup{catalog.schema} : forms::SchemaLookup{}; - forms::Submitter const call = aliasCalls(alias->model); - if (collection) { - auto model = forms::CollectionModel::fromSchema(*document); - if (!model) { - report(node.path, "the collection of `" + action + "` does not build: " + model.error().path + ": " + - model.error().message); - return; - } - if (model->query() != action) { - report(node.path, "the view document of `" + action + "` lists `" + std::string{model->query()} + "`"); - return; - } - std::string query{model->query()}; - element.collection = std::make_unique(runtime(), *std::move(model), schemas, - aliasSubmits(alias->model, std::move(query)), - call, engineOptions()); - followFormatting(element, scope); - return; - } - // The wizard's id, the stem of its translation keys, is the action it starts with. - auto model = forms::WizardModel::fromSchema(action, *document); - if (!model) { - report(node.path, - "the wizard of `" + action + "` does not build: " + model.error().path + ": " + model.error().message); - return; - } - if (model->steps().front().action != action) { - report(node.path, - "the wizard document of `" + action + "` starts with `" + model->steps().front().action + "`"); - return; - } - try { - element.wizard = std::make_unique(runtime(), *std::move(model), schemas, - aliasSubmits(alias->model), call, engineOptions()); - followFormatting(element, scope); - } catch (std::invalid_argument const& error) { - report(node.path, error.what()); - } -} - -// The presentation keys a form, a collection and a wizard share, but the title: the label of the explicit-mode button -// and the status line naming it, bound in the node's scope; whether the status line shows, the grid's columns and the -// field layout and the inline caption column's width, as read at load. -void ScreenCore::presentForm(DocNode const& node, LowerCtx const& ctx, forms::FormViewOptions& options) { - if (ExprPtr const label = node.prop("submitLabel")) { - options.submitLabel = bindProp(ctx, label, std::string{}, stringOf); - } - if (auto const shown = node.flags.find("showStatus"); shown != node.flags.end()) { - options.showStatus = shown->second; - } - if (ExprPtr const columns = node.prop("columns"); columns != nullptr && columns->literal.asInt() != nullptr) { - options.gridColumns = static_cast(*columns->literal.asInt()); - options.flatGridColumns = options.gridColumns; - } - if (node.name("fieldLayout") == "inline") { - options.fieldLayout = forms::FieldLayout::Inline; - } - // The loader has checked `captionWidth` is a literal integer. - if (ExprPtr const width = node.prop("captionWidth")) { - options.inlineLabelWidth = static_cast(*width->literal.asInt()); - } -} - -Node ScreenCore::lowerComposite(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - // The editor's and the steps' titles are the dialog's and the header's; the forms do not repeat them. A `title` - // replaces the view's own heading. - forms::FormViewOptions form{}; - form.showTitle = false; - presentForm(node, ctx, form); - Prop title = bindProp(ctx, node.prop("title"), std::string{}, stringOf); - Node view; - if (element != nullptr && element->collection != nullptr) { - forms::CollectionViewOptions options{}; - options.form = std::move(form); - options.title = std::move(title); - view = forms::collectionView(*element->collection, std::move(options)); - } else if (element != nullptr && element->wizard != nullptr) { - forms::WizardViewOptions options{}; - options.form = std::move(form); - options.title = std::move(title); - view = forms::wizardView(*element->wizard, options); - } else { - return ui::text(Text{.text = std::string{node.name("action")}, .role = TextRole::Muted}); - } - Column column{.children = {std::move(view)}}; - commonOf(node, ctx, element, column.common); - return ui::column(std::move(column)); -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): an overlay's scope, content, actions and keys are one lowering. -// NOLINTNEXTLINE(readability-function-cognitive-complexity): an overlay's scope, content, actions and keys are one lowering. -Node ScreenCore::lowerDialog(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - Prop open = node.prop("open") ? bindProp(ctx, node.prop("open"), false, boolOf) - : slotProp([element] { return element->open.get(); }); - std::vector bodyContent; - for (DocNodePtr const& child : node.nodes("children")) { - bodyContent.push_back(child.get()); - } - int const bodyGap = - node.prop("gap") ? static_cast(intOf(once(ctx, node.prop("gap")), kDialogGap)) : kDialogGap; - LayoutHints const bodyHints = holderHints(bodyContent, node.scope ? &*node.scope : nullptr, ctx); - Node body = lazy( - [this, ctx, &node, element, bodyGap] -> Node { - auto const inner = std::make_shared(*this, ctx.scope, nullptr, ctx.scope->nodes.depth() + 2); - inner->owner = element; - addPending(1); - inner->submitted = &element->submitted; - inner->showErrors = std::string{node.name("showErrors")}; - std::vector content; - for (DocNodePtr const& child : node.nodes("children")) { - content.push_back(child.get()); - } - std::vector lists; - for (std::string_view const key : {"default", "cancel"}) { - if (Commands const* const commands = node.event(key)) { - lists.push_back(commands); - } - } - for (DocNodePtr const& action : node.partList("actions")) { - if (Commands const* const commands = action->event("onClick")) { - lists.push_back(commands); - } - } - declare(*inner, node.scope ? &*node.scope : nullptr, content, lists); - element->inner.set(inner.get()); - LowerCtx const innerCtx{ - .scope = inner, - .bindings = ctx.bindings, - .boundary = ctx.boundary, - .listGap = bodyGap, - }; - std::vector children; - children.reserve(content.size()); - for (DocNode const* const child : content) { - children.push_back(lower(*child, innerCtx)); - } - // The overlay's actions end its scoped content, so they bind in its scope; the mount puts them in its - // footer. - if (ActionModels actions = lowerActionParts(node.partList("actions"), innerCtx); !actions.empty()) { - children.push_back(actionBarOf(std::move(actions))); - } - std::vector keys; - if (Commands const* const commands = node.event("default")) { - keys.push_back(KeyBinding{ - .chord = "Enter", - .onPress = [this, innerCtx, commands] { runEvent(commands, innerCtx, Value{}); }, - }); - } - if (Commands const* const commands = node.event("cancel")) { - keys.push_back(KeyBinding{ - .chord = "Esc", - .onPress = [this, innerCtx, commands] { runEvent(commands, innerCtx, Value{}); }, - }); - } - fillHolder(children, node.path); - return holding(std::move(children), inner, std::move(keys), bodyGap); - }, - bodyHints); - Action onDismiss = [this, ctx, element, commands = node.event("onDismiss")] { - session.asUser([&] { - session.noteWrite(); - element->open.set(false); - }); - runEvent(commands, ctx, Value{}); - }; - if (node.kind == "drawer") { - ExprPtr const side = node.prop("side"); - Drawer spec{ - .open = std::move(open), - .title = bindProp(ctx, node.prop("title"), std::string{}, stringOf), - .description = bindProp(ctx, node.prop("description"), std::string{}, stringOf), - .child = std::move(body), - .onDismiss = std::move(onDismiss), - .side = side && textOf(once(ctx, side), ctx.scope->formatting()) == "start" ? Side::Start : Side::End, - .headNote = bindProp(ctx, node.prop("headNote"), std::string{}, stringOf), - .footerNote = bindProp(ctx, node.prop("footerNote"), std::string{}, stringOf), - .closeButton = bindProp(ctx, node.prop("closeButton"), false, boolOf), - .dismissLabel = bindProp(ctx, node.prop("dismissLabel"), std::string{"Close"}, stringOf), - }; - if (ExprPtr const spans = node.prop("descriptionSpans")) { - spec.descriptionSpans = spansProp(ctx, spans); - } - commonOf(node, ctx, element, spec.common); - return ui::drawer(std::move(spec)); - } - Dialog spec{ - .open = std::move(open), - .title = bindProp(ctx, node.prop("title"), std::string{}, stringOf), - .description = bindProp(ctx, node.prop("description"), std::string{}, stringOf), - .child = std::move(body), - .onDismiss = std::move(onDismiss), - .common = {}, // NOLINT(readability-trailing-comma): the comma ends the designator, not the empty braces. - .sheet = bindProp(ctx, node.prop("sheet"), false, boolOf), - .dismissLabel = bindProp(ctx, node.prop("dismissLabel"), std::string{"Close"}, stringOf), - .headNote = bindProp(ctx, node.prop("headNote"), std::string{}, stringOf), - .footerNote = bindProp(ctx, node.prop("footerNote"), std::string{}, stringOf), - .closeButton = bindProp(ctx, node.prop("closeButton"), false, boolOf), - }; - if (ExprPtr const spans = node.prop("descriptionSpans")) { - spec.descriptionSpans = spansProp(ctx, spans); - } - commonOf(node, ctx, element, spec.common); - return ui::dialog(std::move(spec)); -} - -Node ScreenCore::lowerSwitch(DocNode const& node, LowerCtx const& ctx) { - std::vector whens; - Switch spec; - std::int64_t index = 0; - for (DocNodePtr const& part : node.partList("cases")) { - whens.push_back(part->prop("when")); - DocNode const* const casePart = part.get(); - std::vector caseContent; - for (DocNodePtr const& child : casePart->nodes("children")) { - caseContent.push_back(child.get()); - } - LayoutHints const caseHints = holderHints(caseContent, casePart->scope ? &*casePart->scope : nullptr, ctx); - spec.cases.push_back(SwitchCase{ - .key = Key{index++}, - .node = lazy( - [this, ctx, casePart, caseGap = ctx.listGap] -> Node { - auto const inner = - std::make_shared(*this, ctx.scope, nullptr, ctx.scope->nodes.depth() + 2); - std::vector content; - for (DocNodePtr const& child : casePart->nodes("children")) { - content.push_back(child.get()); - } - declare(*inner, casePart->scope ? &*casePart->scope : nullptr, content, {}); - LowerCtx const innerCtx{ - .scope = inner, - .bindings = ctx.bindings, - .boundary = ctx.boundary, - .listGap = caseGap, - }; - std::vector children; - children.reserve(content.size()); - for (DocNode const* const child : content) { - children.push_back(lower(*child, innerCtx)); - } - fillHolder(children, casePart->path); - return holding(std::move(children), inner, {}, caseGap); - }, - caseHints), - }); - } - spec.selector = slotProp( - [scope = ctx.scope, bindings = ctx.bindings, selected = node.prop("on"), whens = std::move(whens)] { - Value const value = evalIn(*scope, bindings.get(), selected); - for (std::size_t at = 0; at < whens.size(); ++at) { - if (evalIn(*scope, bindings.get(), whens.at(at)) == value) { - return Key{static_cast(at)}; - } - } - return Key{std::int64_t{-1}}; - }); - auto const fallback = node.nodes("default"); - spec.fallback = fallback.empty() ? Node{} : lowerAll(fallback, ctx, ctx.listGap); - commonOf(node, ctx, nullptr, spec.common); - return ui::switchOf(std::move(spec)); -} - -// The tab a bound `selected` names. A value that names no tab shows the first, and is reported once. -Prop ScreenCore::controlledTabSelection(DocNode const& node, LowerCtx const& ctx, ExprPtr const& selected, - std::shared_ptr> const& ids) { - auto const unknownReported = std::make_shared(false); - return Prop{[this, scope = ctx.scope, bindings = ctx.bindings, selected, ids, unknownReported, - path = pointerAppend(node.path, "selected")] -> std::size_t { - Value const value = evalIn(*scope, bindings.get(), selected); - std::string const* const named = value.asString(); - auto const found = named == nullptr ? ids->end() : std::ranges::find(*ids, *named); - if (found != ids->end()) { - return static_cast(std::distance(ids->begin(), found)); - } - if (!*unknownReported) { - *unknownReported = true; - report(path, canonicalJson(value) + " names no tab; the first is shown"); - } - return 0; - }}; -} - -// A document names tabs by id; the view tree by index, so the ids map to indices once. A bound `selected` is the -// controlled index: a pick runs `onChoose` and the page follows `selected` alone. Without it the node keeps the -// user's pick itself, as a bound index too, whose page follows the pick: a constant would move only the highlight. -Node ScreenCore::lowerTabs(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - Tabs spec; - auto const ids = std::make_shared>(); - for (DocNodePtr const& tab : node.partList("tabs")) { - auto const nodes = tab->nodes("children"); - ids->push_back(tab->id); - spec.tabs.push_back(Tab{ - .label = bindProp(ctx, tab->prop("label"), std::string{}, stringOf), - .node = nodes.empty() ? Node{} : lowerAll(nodes, ctx), - }); - } - spec.moreLabel = bindProp(ctx, node.prop("moreLabel"), std::string{"More"}, stringOf); - if (ExprPtr const inset = node.prop("inset")) { - spec.inset = static_cast(intOf(once(ctx, inset), 0)); - } - if (ExprPtr const pageInset = node.prop("pageInset")) { - spec.pageInset = static_cast(intOf(once(ctx, pageInset), 0)); - } - spec.stripSurface = std::string{node.name("stripSurface")}; - ExprPtr const selected = node.prop("selected"); - Commands const* const onChoose = node.event("onChoose"); - bool const controlled = selected && (selected->kind != ExprKind::Literal || !selected->literal.isNull()); - auto const picked = std::make_shared>(runtime(), std::size_t{0}); - spec.selected = controlled ? controlledTabSelection(node, ctx, selected, ids) - : Prop{[picked] { return picked->get(); }}; - spec.onSelect = [this, ctx, onChoose, ids, picked, controlled, element](std::size_t index) { - if (!controlled) { - picked->set(index); - if (element != nullptr && index < ids->size()) { - element->draft.set(Value{ids->at(index)}); - } - } - if (onChoose != nullptr && index < ids->size()) { - runEvent(onChoose, ctx, Value{ids->at(index)}); - } - }; - commonOf(node, ctx, element, spec.common); - return ui::tabs(std::move(spec)); -} - -// Focuses the declaration the command's target resolved to: of several candidates (cases of one switch), the one -// that is mounted. Each candidate is keyed by the command's own enclosing row keys, as many as enclose the -// candidate; with `row`, the innermost of them is the row's key instead. -bool ScreenCore::focusTarget(Command const& command, RtScope const& scope, Bindings const* bindings) { - if (!focusElement) { - return false; - } - auto const found = _doc->focusTargets.find(command.path); - if (found == _doc->focusTargets.end()) { - return focusElement(command.target); - } - FocusPlace const place = focusPlace(scope); - std::optional row; - if (found->second.row) { - Value const value = evalIn(scope, bindings, command.extra); - if (value.isNull()) { - return false; - } - row = canonicalJson(valueOfKey(keyOf(value))); - } - for (FocusCandidate const& candidate : found->second.candidates) { - std::size_t const kept = row ? candidate.rows - 1 : candidate.rows; - if (candidate.rows == 0 && row) { - continue; - } - if (kept > place.rows.size()) { - continue; - } - FocusPlace candidatePlace{ - .prefix = place.prefix, - .rows = {place.rows.begin(), std::next(place.rows.begin(), static_cast(kept))}, - }; - if (row) { - candidatePlace.rows.push_back(*row); - } - if (focusElement(focusKey(candidatePlace, candidate.path))) { - return true; - } - } - return false; -} - -std::shared_ptr ScreenCore::rowScope(DocNode const& node, LowerCtx const& ctx, - reactive::Signal const& row, - std::vector const& content, std::string key) { - auto scope = std::make_shared(*this, ctx.scope, &row, ctx.scope->nodes.depth() + 2); - scope->rowKey = std::move(key); - declare(*scope, node.scope ? &*node.scope : nullptr, content, {}); - return scope; -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): a list of rows and a table. -Node ScreenCore::lowerRows(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - ExprPtr const rowsExpr = node.prop("rows"); - if (!rowsExpr) { - report(node.path, "a model-backed `table` needs the table engine, which this interpreter does not lower yet"); - return ui::text(Text{.text = std::string{"table"}, .role = TextRole::Muted}); - } - std::function()> rows = [scope = ctx.scope, bindings = ctx.bindings, rowsExpr] { - Value const value = evalIn(*scope, bindings.get(), rowsExpr); - ValueList const* const items = value.asList(); - return items == nullptr ? std::vector{} : std::vector{items->begin(), items->end()}; - }; - auto keyFn = [scope = ctx.scope, bindings = ctx.bindings, keyExpr = node.prop("key")](Value const& row) -> Key { - if (Value const* const heading = row.field(kGroupHeadingField); heading != nullptr && heading->asString()) { - return Key{*heading->asString()}; - } - if (!keyExpr) { - Value const rowKey = rowId(row); - return keyOf(rowKey.isNull() ? row : rowKey); - } - ScopeEnv const env{*scope, bindings.get(), &row}; - return keyOf(evaluate(*keyExpr, env)); - }; - if (node.kind == "forEach") { - std::vector content; - for (DocNodePtr const& child : node.nodes("children")) { - content.push_back(child.get()); - } - auto rowView = [this, ctx, &node, content, keyFn](reactive::Signal const& row) -> Node { - std::string key = runtime().untracked([&] { return canonicalJson(valueOfKey(keyFn(row.peek()))); }); - auto const scope = rowScope(node, ctx, row, content, std::move(key)); - LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; - std::vector children; - children.reserve(content.size()); - for (DocNode const* const child : content) { - children.push_back(lower(*child, rowCtx)); - } - return holding(std::move(children), scope); - }; - ExprPtr const axis = node.prop("axis"); - ExprPtr const gap = node.prop("gap"); - Common common; - commonOf(node, ctx, element, common); - Axis const along = axis ? axisOf(once(ctx, axis)) : Axis::Vertical; - bool wrap = node.flag("wrap"); - if (wrap && along != Axis::Horizontal) { - // Only a computed axis gets here: the loader refuses a literal one that is not horizontal. - report(node.path + "/wrap", - "`wrap` fills lines along a row; this `forEach`'s `axis` is not \"horizontal\""); - wrap = false; - } - bool divided = node.flag("divided"); - if (divided && along != Axis::Vertical) { - report(node.path + "/divided", - "`divided` draws rules between rows of a column; this `forEach`'s `axis` is \"horizontal\""); - divided = false; - } - return ui::forEach(std::move(rows), std::move(keyFn), std::move(rowView), along, - gap ? static_cast(intOf(once(ctx, gap), 0)) : 0, common, wrap, divided); - } - // The table's rows, sorted: the element's own view, which its element values read too, unless names bound - // where the table is lowered (a component's `props`) reach its rows, which the element cannot see. - reactive::Computed const* view = element == nullptr ? nullptr : element->view; - if (view != nullptr && ctx.bindings != nullptr && !ctx.bindings->empty()) { - view = &ctx.scope->nodes.computed( - [this, element, bindings = ctx.bindings] { return tableView(*element, bindings.get()); }); - } - if (view != nullptr) { - // The page's rows, each group's heading entry before the first of its rows the page holds, so a group split - // across pages gets its heading on both. - rows = [view] { - TableView const& shown = view->get(); - std::vector entries; - entries.reserve(shown.last - shown.first); - for (std::size_t index = shown.first; index < shown.last; ++index) { - if (!shown.runOf.empty() && - (index == shown.first || shown.runOf.at(index) != shown.runOf.at(index - 1))) { - entries.push_back(shown.runs.at(shown.runOf.at(index))); - } - entries.push_back(shown.rows.at(index)); - } - return entries; - }; - } - std::vector columns; - std::vector cells; - std::vector fields; - // One entry per column, in the same order as `cells`/`fields`. Captured by `cellsOf` below (not `columns` - // itself, which is moved into `ui::table(...)` further down and so cannot be read from inside a lambda - // that outlives this function) so the default-cell closure can apply each column's role to its generated cell. - std::vector roles; - FormatContext const& format = ctx.scope->formatting(); - // The table's `valign` is the default of every column that gives none; the loader checked both names. - Align const tableValign = cellPlaceNamed(node.name("valign")).value_or(Align::Center); - if (ExprPtr const derived = node.prop("columns")) { - Value const list = once(ctx, derived); - // A computed place that names none is reported once for the table, whichever column and key it was. - bool placeReported = false; - auto const placeOf = [&](Value const& item, std::string_view key, Align fallback) { - Value const* const given = item.field(key); - if (given == nullptr || given->isNull()) { - return fallback; - } - std::string const* const name = given->asString(); - std::optional const placed = name == nullptr ? std::nullopt : cellPlaceNamed(*name); - if (!placed && !placeReported) { - placeReported = true; - report(derived->path, "a column's `" + std::string{key} + "` is " + canonicalJson(*given) + - "; a cell's place is start, center or end"); - } - return placed.value_or(fallback); - }; - if (ValueList const* const items = list.asList()) { - for (Value const& item : *items) { - Value const* const field = item.field("id"); - Value const* const label = item.field("label"); - fields.push_back(field == nullptr ? std::string{} : textOf(*field, format)); - columns.push_back(TableColumn{ - .label = textOf(label != nullptr ? *label : Value{fields.back()}, format), - .align = placeOf(item, "align", Align::Start), - .valign = placeOf(item, "valign", tableValign), - }); - cells.push_back(nullptr); - roles.push_back(TextRole::Normal); - } - } - } - // A part's column index, which a header click reports, counts the derived columns before it. - std::size_t const derivedCount = columns.size(); - for (DocNodePtr const& part : node.partList("columns")) { - ExprPtr const label = part->prop("label"); - ExprPtr const width = part->prop("width"); - ExprPtr const role = part->prop("role"); - TextRole columnRole = TextRole::Normal; - if (role) { - // Read once, with the rest of the column; a value that names no role is reported, as a text's is. - Value const value = once(ctx, role); - std::optional const named = roleNamed(textOf(value, format)); - if (!named) { - report(role->path, "role is " + canonicalJson(value) + "; " + std::string{kRoleNames}); - } - columnRole = named.value_or(TextRole::Normal); - } - bool const shrink = part->flag("shrink"); - Sizing const sized = width ? sizingOf(once(ctx, width)) : Sizing::content(); - if (shrink && sized.kind != Sizing::Kind::Stretch) { - report(part->path + "/shrink", - "`shrink` lets a stretch column go narrower than its header; this column's width does not stretch"); - } - columns.push_back(TableColumn{ - .label = label ? textOf(once(ctx, label), format) : std::string{}, - .width = sized, - .role = columnRole, - .align = cellPlaceNamed(part->name("align")).value_or(Align::Start), - .valign = cellPlaceNamed(part->name("valign")).value_or(tableValign), - .sortable = part->flag("sortable"), - .wrap = part->flag("wrap", true), - .shrink = shrink && sized.kind == Sizing::Kind::Stretch, - }); - cells.push_back(part.get()); - fields.emplace_back(part->id); - roles.push_back(columnRole); - } - auto const registry = std::make_shared, std::less<>>>(); - // A value that names no tone is reported once for the table, whichever row and value it was. - auto const toneReported = std::make_shared(false); - // Likewise for a `rowSpans` value that is no list of spans. - auto const spansReported = std::make_shared(false); - auto cellsOf = [this, ctx, &node, cells, fields, roles, registry, keyFn, toneReported, - spansReported](reactive::Signal const& row) { - if (row.peek().field(kGroupHeadingField) != nullptr) { - return headingRow(node, ctx, row, - runtime().untracked([&] { return canonicalJson(valueOfKey(keyFn(row.peek()))); })); - } - std::vector content; - for (DocNode const* const column : cells) { - if (column != nullptr) { - for (DocNodePtr const& cell : column->nodes("cell")) { - content.push_back(cell.get()); - } - } - } - std::string key = runtime().untracked([&] { return canonicalJson(valueOfKey(keyFn(row.peek()))); }); - auto const scope = rowScope(node, ctx, row, content, key); - (*registry)[std::move(key)] = scope; - LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; - std::vector out; - for (std::size_t index = 0; index < cells.size(); ++index) { - DocNode const* const column = cells.at(index); - auto const nodes = column == nullptr ? std::span{} : column->nodes("cell"); - if (!nodes.empty()) { - out.push_back(lowerAll(nodes, rowCtx)); - continue; - } - out.push_back(ui::text(Text{ - .text = slotProp([scope = rowCtx.scope, &row, field = fields.at(index)] { - Value const* const value = row.get().field(field); - return value == nullptr ? std::string{} : textOf(*value, scope->formatting()); - }), - .role = roles.at(index), - })); - } - if (!out.empty()) { - // The row's first cell owns the row's scope, which lives as long as the row's node: a cell is placed by - // its column, so the scope is not held by a wrapping container, which the column would place instead. - auto const owner = std::make_shared> const>(out.front(), scope); - out.front() = Node{owner, owner->first.get()}; - } - TableRowView rowView{.cells = std::move(out), .tone = std::nullopt}; - // The row's name, in its own scope: what its select box and assistive technology read. - if (ExprPtr const labelExpr = node.prop("rowLabel")) { - rowView.label = bindProp(rowCtx, labelExpr, std::string{}, stringOf); - } - if (ExprPtr const toneExpr = node.prop("rowTone")) { - rowView.tone = slotProp>( - [this, scope, bindings = ctx.bindings, toneExpr, toneReported] -> std::optional { - return rowToneOf(evalIn(*scope, bindings.get(), toneExpr), toneExpr->path, *toneReported); - }); - } - if (ExprPtr const spansExpr = node.prop("rowSpans")) { - rowView.spans = slotProp>([this, scope, bindings = ctx.bindings, spansExpr, - spansReported, fields] { - return rowSpansOf(evalIn(*scope, bindings.get(), spansExpr), fields, spansExpr->path, *spansReported); - }); - } - return rowView; - }; - TableOptions options; - options.showHeader = node.flag("showHeader", true); - options.selectColumn = node.flag("selectColumn"); - if (ExprPtr const selectAll = node.prop("selectAllLabel")) { - options.selectAllLabel = bindProp(ctx, selectAll, std::string{}, stringOf); - } - if (ExprPtr const threshold = node.prop("virtualizeThreshold")) { - options.virtualize.threshold = - static_cast(std::max(0, intOf(once(ctx, threshold), 2000))); - } - if (ExprPtr const overscan = node.prop("virtualizeOverscan")) { - options.virtualize.overscan = - static_cast(std::max(0, intOf(once(ctx, overscan), 10))); - } - std::string const mode = - node.prop("selectionMode") ? textOf(once(ctx, node.prop("selectionMode")), format) : std::string{}; - options.selectionMode = SelectionMode::None; - if (mode == "single") { - options.selectionMode = SelectionMode::Single; - } else if (mode == "multiple") { - options.selectionMode = SelectionMode::Multiple; - } - // The selection the table shows: the bound `selection`, or the table's own. A slot even for a literal list, so - // a bound selection is fixed until the document writes it, and a user's change the document leaves unwritten - // snaps back. A bound value that is neither a list nor `null` is reported once. - auto const selectionReported = std::make_shared(false); - options.selection = slotProp>([this, element, selectionReported, path = node.path] { - std::vector keys; - if (element->bound != nullptr) { - Value const bound = element->bound->get(); - if (!bound.isNull() && bound.asList() == nullptr && !*selectionReported) { - *selectionReported = true; - report(pointerAppend(path, "selection"), - "selection is " + canonicalJson(bound) + "; a table's selection is a list of keys"); - } - } - Value const selection = tableSelection(*element); - if (ValueList const* const items = selection.asList()) { - for (Value const& item : *items) { - keys.push_back(keyOf(item)); - } - } - return keys; - }); - // A user's change: the table's own selection takes it when no key binds one, then `onSelectionChange` runs with - // `event` the new selection, in the table's scope, in the same batch. The backend holds one page: a `Replace` - // is the whole new selection, and an `Extend` keeps the selected keys of the rows on other pages, before the - // reported ones. A key whose row `rows` no longer has drops on any user change. - options.onSelectionChange = [this, ctx, element, view, keyFn, commands = node.event("onSelectionChange")]( - std::vector const& keys, SelectionChange change) { - ValueList items; - if (change == SelectionChange::Extend && view != nullptr) { - items = runtime().untracked([&] { return selectedOffPage(view->get(), tableSelection(*element), keyFn); }); - } - // A heading is never selected. A virtualized backend knows the keys of rows it has not realized but not - // which of them are headings, so its Ctrl+A or range can name one. - for (Key const& key : keys) { - if (std::string const* const text = std::get_if(&key); - text != nullptr && text->starts_with("\x1Fgroup:")) { - continue; - } - items.push_back(valueOfKey(key)); - } - Value const selected{std::move(items)}; - runtime().batch([&] { - if (element->bound == nullptr) { - session.asUser([&] { - session.noteWrite(); - element->selection.set(selected); - }); - } - runEvent(commands, ctx, selected); - }); - }; - // The header marks the sort's first key; a sort that names no sortable column marks none. - auto const columnIndex = [&node, derivedCount](std::string_view columnId) -> std::optional { - auto const parts = node.partList("columns"); - auto const found = - std::ranges::find_if(parts, [columnId](DocNodePtr const& part) { return part->id == columnId; }); - if (found == parts.end()) { - return std::nullopt; - } - return derivedCount + static_cast(std::distance(parts.begin(), found)); - }; - options.sort = slotProp>([element, &node, columnIndex] -> std::optional { - std::optional> const keys = sortKeysOf(node, tableSort(*element)); - if (!keys || keys->empty()) { - return std::nullopt; - } - std::optional const index = columnIndex(keys->front().column->id); - if (!index) { - return std::nullopt; - } - return TableSort{ - .column = *index, - .direction = keys->front().descending ? SortDirection::Descending : SortDirection::Ascending, - }; - }); - // A header click makes its column the single key: descending when it already is the first key ascending, - // ascending otherwise. The table's own sort takes it when no key binds one, then `onSortChange` runs with - // `event` the new sort. - options.onSort = [this, ctx, element, &node, derivedCount, - commands = node.event("onSortChange")](std::size_t index) { - auto const parts = node.partList("columns"); - if (index < derivedCount || index - derivedCount >= parts.size() || - !parts.subspan(index - derivedCount).front()->flag("sortable")) { - return; - } - std::string const& columnId = parts.subspan(index - derivedCount).front()->id; - Value const current = runtime().untracked([&] { return tableSort(*element); }); - std::optional> const keys = sortKeysOf(node, current); - bool const descending = - keys && !keys->empty() && keys->front().column->id == columnId && !keys->front().descending; - ValueRecord key; - key.insert_or_assign("column", Value{columnId}); - key.insert_or_assign("direction", Value{std::string{descending ? "desc" : "asc"}}); - Value const next{ValueList{Value{std::move(key)}}}; - runtime().batch([&] { - if (element->sortBound == nullptr) { - session.asUser([&] { - session.noteWrite(); - element->sort.set(next); - }); - } - runEvent(commands, ctx, next); - }); - }; - options.onActivate = [this, ctx, element, registry, commands = node.event("onActivate")](Key const& key) { - Value const activated = valueOfKey(key); - session.asUser([&] { - session.noteWrite(); - element->activeKey.set(activated); - }); - auto const found = registry->find(canonicalJson(activated)); - std::shared_ptr const scope = found == registry->end() ? nullptr : found->second.lock(); - LowerCtx const rowCtx{.scope = scope ? scope : ctx.scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; - runEvent(commands, rowCtx, activated); - }; - commonOf(node, ctx, element, options.common); - std::span const empty = node.nodes("empty"); - if (empty.empty()) { - return ui::table(std::move(columns), std::move(rows), std::move(keyFn), std::move(cellsOf), - std::move(options)); - } - // With `empty`, a column holds the table and the content shown in its place while `rows` is an empty list; a - // `null` (a query not answered yet) shows the table. The column is placed as the table would be: it takes the - // node's visibility and layout, and every other common property stays on the table, so its test id and the - // element id `focus` finds name the table. - auto const listed = [scope = ctx.scope, bindings = ctx.bindings, rowsExpr] { - ValueList const* const items = evalIn(*scope, bindings.get(), rowsExpr).asList(); - return items == nullptr || !items->empty(); - }; - Column wrapper; - wrapper.common.visible = std::move(options.common.visible); - wrapper.common.layout = options.common.layout; - options.common.visible = slotProp(listed); - Column content{.children = {lowerAll(empty, ctx)}}; - content.common.visible = slotProp([listed] { return !listed(); }); - wrapper.children.push_back(ui::table(std::move(columns), std::move(rows), std::move(keyFn), - std::move(cellsOf), std::move(options))); - wrapper.children.push_back(ui::column(std::move(content))); - return ui::column(std::move(wrapper)); -} - -TableRowView ScreenCore::headingRow(DocNode const& node, LowerCtx const& ctx, reactive::Signal const& row, - std::string key) { - auto const heading = node.partList("group").front()->nodes("heading"); - std::vector content; - content.reserve(heading.size()); - for (DocNodePtr const& child : heading) { - content.push_back(child.get()); - } - auto const scope = rowScope(node, ctx, row, content, std::move(key)); - LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; - // The cell owns the heading's scope, for as long as the row's node lives, as a data row's first cell does. - auto const owner = - std::make_shared> const>(lowerAll(heading, rowCtx), scope); - return TableRowView{.cells = {Node{owner, owner->first.get()}}, .tone = std::nullopt, .heading = true}; -} - -Node ScreenCore::lowerChart(DocNode const& node, LowerCtx const& ctx, ElementState* element) { - Chart spec; - spec.data = slotProp( - [this, &node, scope = ctx.scope, bindings = ctx.bindings] { return chartData(node, *scope, bindings.get()); }); - commonOf(node, ctx, element, spec.common); - return ui::chart(std::move(spec)); -} - -std::optional ScreenCore::chartMagnitude(Value const& value, std::string const& path, - std::optional& unit) { - std::optional const number = numeric(value); - if (!number) { - report(path, "a chart value is a number or a quantity; this one is left out"); - return std::nullopt; - } - std::string const own = number->unit != nullptr ? *number->unit : std::string{}; - if (!unit) { - unit = own; - return number->value; - } - if (*unit == own) { - return number->value; - } - std::optional converted; - if (!own.empty() && !unit->empty()) { - converted = convertUnit(number->value, own, *unit, session.formatting().units); - } - if (!converted) { - report(path, "a chart value does not convert to the unit of the chart's first value; it is left out"); - } - return converted; -} - -std::optional ScreenCore::chartToneOf(Value const& value, std::string const& path) { - static constexpr std::array, 5> kTones = { - { - {"neutral", Tone::Neutral}, - {"info", Tone::Info}, - {"ok", Tone::Ok}, - {"warn", Tone::Warn}, - {"err", Tone::Err}, - }, - }; - if (value.isNull()) { - return std::nullopt; - } - if (std::string const* const text = value.asString()) { - for (auto const& [name, tone] : kTones) { - if (name == *text) { - return tone; - } - } - } - report(path, "a chart tone is neutral, info, ok, warn or err; this one marks nothing"); - return std::nullopt; -} - -std::optional ScreenCore::chartPosition(Value const& value, std::string const& path, - detail::ChartAxisKinds& kinds) { - if (value.isNull()) { - return std::nullopt; - } - if (std::optional const number = numeric(value)) { - kinds.numbers = true; - return number->value; - } - if (std::optional const instant = - dateInstantOf(value, session.formatting().utcOffsetMinutes).instant) { - kinds.instants = true; - return math::Rational{instant->value.time_since_epoch().count(), math::DecimalPlaces{0}}; - } - report(path, "a chart's `x` is a number, a date or an instant; this point is left out"); - return std::nullopt; -} - -std::vector ScreenCore::chartPoints(DocNode const& series, RtScope const& scope, - Bindings const* bindings, std::optional& unit, - detail::ChartAxisKinds& kinds) { - // A chart is a picture of a few hundred values; a larger set is a table's. - static constexpr std::size_t kMaxPoints = 1000; - FormatContext const& format = scope.formatting(); - ExprPtr const pointsExpr = series.prop("points"); - Value const listed = evalIn(scope, bindings, pointsExpr); - ValueList const* const list = listed.asList(); - if (list == nullptr) { - // `null` is a query still loading, and draws as empty without a word. - if (!listed.isNull()) { - report(pointsExpr->path, "`points` is a list; the series draws as empty"); - } - return {}; - } - std::size_t const first = list->size() > kMaxPoints ? list->size() - kMaxPoints : 0; - if (first > 0) { - report(pointsExpr->path, "a series draws its last 1000 points"); - } - ExprPtr const yExpr = series.prop("y"); - ExprPtr const xExpr = series.prop("x"); - ExprPtr const labelExpr = series.prop("xLabel"); - ExprPtr const toneExpr = series.prop("tone"); - ExprPtr const noteExpr = series.prop("note"); - std::vector points; - for (std::size_t index = first; index < list->size(); ++index) { - ScopeEnv const env{scope, bindings, &list->at(index)}; - detail::ChartRawPoint point{.index = index}; - if (xExpr) { - point.x = chartPosition(evaluate(*xExpr, env), xExpr->path, kinds); - if (!point.x) { - continue; - } - } - Value const value = evaluate(*yExpr, env); - if (!value.isNull()) { - point.y = chartMagnitude(value, yExpr->path, unit); - if (!point.y) { - continue; - } - } - point.xLabel = labelExpr ? textOf(evaluate(*labelExpr, env), format) : std::string{}; - point.note = noteExpr ? textOf(evaluate(*noteExpr, env), format) : std::string{}; - point.tone = toneExpr ? chartToneOf(evaluate(*toneExpr, env), toneExpr->path) : std::nullopt; - points.push_back(std::move(point)); - } - return points; -} - -namespace { - -/// @brief A chart's exact value at @p places, as the active locale writes it. -/// @param value The value. -/// @param places The places, at most 18. -/// @param format The formatting facts. -/// @return The text; the exact JSON when the rounded value does not fit. -[[nodiscard]] std::string chartNumberText(math::Rational const& value, std::uint32_t places, - FormatContext const& format) { - std::optional rounded = - math::checkedRoundToDecimalPlaces(value, math::DecimalPlaces{places}, math::RoundingMode::HalfEven); - if (!rounded) { - return textOf(Value{Decimal{value}}, format); - } - rounded->decimalPlaces = math::DecimalPlaces{places}; - return textOf(Value{Decimal{*rounded}}, format); -} - -/// @brief A reference line's stroke by its document name. -/// @param name `solid`, `dashed`, `dotted`, or empty for solid; the loader refuses any other. -/// @return The stroke. -[[nodiscard]] ChartLineStyle chartLineStyle(std::string_view name) { - if (name == "dashed") { - return ChartLineStyle::Dashed; - } - return name == "dotted" ? ChartLineStyle::Dotted : ChartLineStyle::Solid; -} - -/// @brief Where a point sits along a value axis that a document may have fixed, and on which side it is clipped. -/// @param value The point's value. -/// @param range The axis. -/// @return The value drawn, the axis end for a value outside, and the side it lies beyond. -[[nodiscard]] std::pair chartClipped(math::Rational const& value, ChartRange const& range) { - if (value < range.low) { - return {range.low, ChartClip::Below}; - } - if (value > range.high) { - return {range.high, ChartClip::Above}; - } - return {value, ChartClip::None}; -} -} // namespace - -std::vector ScreenCore::chartLines(DocNode const& node, RtScope const& scope, - Bindings const* bindings, std::optional& unit) { - FormatContext const& format = scope.formatting(); - std::vector lines; - for (DocNodePtr const& part : node.partList("lines")) { - ExprPtr const valueExpr = part->prop("value"); - Value const value = evalIn(scope, bindings, valueExpr); - std::optional const magnitude = - value.isNull() ? std::nullopt : chartMagnitude(value, valueExpr->path, unit); - if (!magnitude) { - continue; - } - detail::ChartRawLine line{.value = *magnitude, .label = std::nullopt}; - if (ExprPtr const label = part->prop("label")) { - line.label = textOf(evalIn(scope, bindings, label), format); - } - if (ExprPtr const tone = part->prop("tone")) { - line.tone = chartToneOf(evalIn(scope, bindings, tone), tone->path).value_or(Tone::Neutral); - } - line.style = detail::chartLineStyle(part->name("style")); - lines.push_back(std::move(line)); - } - return lines; -} - -ChartRange ScreenCore::chartFixedRange(DocNode const& node, RtScope const& scope, Bindings const* bindings, - std::optional& unit, ChartRange const& range) { - ChartRange fixed = range; - for (auto const& [key, end] : {std::pair{"yMin", &fixed.low}, std::pair{"yMax", &fixed.high}}) { - if (ExprPtr const expr = node.prop(key)) { - Value const value = evalIn(scope, bindings, expr); - if (!value.isNull()) { - *end = chartMagnitude(value, expr->path, unit).value_or(*end); - } - } - } - if (fixed.high > fixed.low) { - return fixed; - } - report(pointerAppend(node.path, "yMin"), "`yMin` is not below `yMax`; the chart takes its range from its values"); - return range; -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity): one branch per way a series can be drawn or clipped. -void ScreenCore::chartSeries(ChartData& data, DocNode const& node, RtScope const& scope, Bindings const* bindings, - std::vector>& series, bool positioned, - ChartRange const& range) { - auto const positionOf = [positioned](detail::ChartRawPoint const& point) { - return positioned && point.x ? *point.x - : math::Rational{static_cast(point.index), math::DecimalPlaces{0}}; - }; - std::vector positions; - for (auto const& points : series) { - std::ranges::transform(points, std::back_inserter(positions), positionOf); - } - // The room one position gives its bars: the least distance between two of their positions, gaps included, so a - // bar never grows over the label of an empty position between two. - std::vector barPositions; - { - std::size_t seriesIndex = 0; - for (DocNodePtr const& part : node.partList("series")) { - if (part->name("style") == "bars") { - std::ranges::transform(series.at(seriesIndex), std::back_inserter(barPositions), positionOf); - } - ++seriesIndex; - } - } - std::ranges::sort(barPositions); - std::optional slot; - for (std::size_t next = 1; next < barPositions.size(); ++next) { - auto const distance = math::checkedSub(barPositions.at(next), barPositions.at(next - 1)); - if (distance && distance->numerator > 0 && (!slot || *distance < *slot)) { - slot = *distance; - } - } - if (!barPositions.empty()) { - data.barSlot = realOf(slot.value_or(math::Rational{1, math::DecimalPlaces{0}})); - } - // A bar is centred on its position and half a slot wide each side, so the axis holds that much beyond the - // outermost position. - if (!barPositions.empty() && !positions.empty()) { - math::Rational const half = math::checkedDiv(slot.value_or(math::Rational{1, math::DecimalPlaces{0}}), - math::Rational{2, math::DecimalPlaces{0}}) - .value_or(math::Rational{0, math::DecimalPlaces{0}}); - auto const [lowest, highest] = std::ranges::minmax(positions); - auto const below = math::checkedSub(lowest, half); - auto const above = math::checkedAdd(highest, half); - if (below && above) { - positions.push_back(*below); - positions.push_back(*above); - } - } - if (std::optional const across = chartRange(positions, 0)) { - data.xMin = realOf(across->low); - data.xMax = realOf(across->high); - } - std::size_t index = 0; - for (DocNodePtr const& part : node.partList("series")) { - ChartSeries drawn; - if (part->name("style") == "bars") { - drawn.style = ChartStyle::Bars; - } - if (ExprPtr const label = part->prop("label")) { - drawn.label = textOf(evalIn(scope, bindings, label), scope.formatting()); - } - drawn.joined = drawn.style == ChartStyle::Line && (!part->flags.contains("joined") || part->flag("joined")); - for (detail::ChartRawPoint& point : series.at(index)) { - ChartPoint out{ - .x = realOf(positionOf(point)), - .y = std::nullopt, - .clip = ChartClip::None, - .xLabel = std::move(point.xLabel), - .tone = point.tone, - .note = std::move(point.note), - }; - if (point.y) { - auto const [shown, clip] = detail::chartClipped(*point.y, range); - out.y = realOf(shown); - out.clip = clip; - } - drawn.points.push_back(std::move(out)); - } - data.series.push_back(std::move(drawn)); - ++index; - } -} - -ChartData ScreenCore::chartData(DocNode const& node, RtScope const& scope, Bindings const* bindings) { - FormatContext const& format = scope.formatting(); - ChartData data; - data.summary = textOf(evalIn(scope, bindings, node.prop("summary")), format); - if (ExprPtr const label = node.prop("yLabel")) { - data.yLabel = textOf(evalIn(scope, bindings, label), format); - } - std::optional unit; - detail::ChartAxisKinds kinds; - std::vector> series; - for (DocNodePtr const& part : node.partList("series")) { - series.push_back(chartPoints(*part, scope, bindings, unit, kinds)); - } - std::vector const lines = chartLines(node, scope, bindings, unit); - // The values the axis must hold, and the places they are shown at. - std::vector values; - for (auto const& points : series) { - for (detail::ChartRawPoint const& point : points) { - if (point.y) { - values.push_back(*point.y); - } - } - } - std::ranges::transform(lines, std::back_inserter(values), &detail::ChartRawLine::value); - // A bar grows from 0, so the axis holds 0; the baseline's side is padded only when something lies beyond it, so - // that the baseline is the plot's edge when nothing does. - std::vector axisValues = values; - ChartPadding padding; - bool barsHaveValues = false; - { - std::size_t seriesIndex = 0; - for (DocNodePtr const& part : node.partList("series")) { - barsHaveValues = - barsHaveValues || (part->name("style") == "bars" && - std::ranges::any_of(series.at(seriesIndex), [](detail::ChartRawPoint const& point) { - return point.y.has_value(); - })); - ++seriesIndex; - } - } - if (barsHaveValues) { - axisValues.emplace_back(0, math::DecimalPlaces{0}); - padding.low = std::ranges::any_of(values, [](math::Rational const& value) { return value.numerator < 0; }); - padding.high = std::ranges::any_of(values, [](math::Rational const& value) { return value.numerator > 0; }); - } - std::uint32_t widest = 0; - for (math::Rational const& value : values) { - widest = std::max(widest, value.decimalPlaces.value); - } - ExprPtr const placesExpr = node.prop("yPlaces"); - std::int64_t const* const fixedPlaces = placesExpr ? placesExpr->literal.asInt() : nullptr; - std::uint32_t const places = fixedPlaces != nullptr ? static_cast(*fixedPlaces) : widest; - std::optional const computed = chartRange(axisValues, places, padding); - if (!computed) { - report(node.path, "the chart's values overflow its arithmetic; it draws nothing"); - return data; - } - ChartRange const range = chartFixedRange(node, scope, bindings, unit, *computed); - data.yMin = realOf(range.low); - data.yMax = realOf(range.high); - // Three or more lines are the scale a reader reads the chart against; fewer leave the values without one. - std::optional const ticks = lines.size() < 3 ? chartTicks(range) : std::nullopt; - if (ticks) { - std::uint32_t const tickPlaces = std::max(places, ticks->places); - for (math::Rational const& tick : ticks->values) { - data.yTicks.push_back( - ChartTick{.value = realOf(tick), .text = detail::chartNumberText(tick, tickPlaces, format)}); - } - } - for (detail::ChartRawLine const& line : lines) { - data.lines.push_back(ChartLine{ - .value = realOf(line.value), - .label = line.label.value_or(detail::chartNumberText(line.value, places, format)), - .tone = line.tone, - .style = line.style, - }); - } - if (kinds.numbers && kinds.instants) { - report(pointerAppend(node.path, "series"), - "a chart's `x` values are all numbers or all dates and instants; the points are spaced by index"); - } - chartSeries(data, node, scope, bindings, series, kinds.numbers != kinds.instants, range); - return data; -} - -std::optional ScreenCore::rowToneOf(Value const& value, std::string const& path, bool& noted) { - if (value.isNull()) { - return std::nullopt; - } - if (std::optional const tone = toneNamed(value)) { - return tone; - } - if (!noted) { - noted = true; - report(path, "rowTone is " + canonicalJson(value) + "; a tone is neutral, info, ok, warn or err"); - } - return std::nullopt; -} - -std::vector ScreenCore::rowSpansOf(Value const& value, std::vector const& columns, - std::string const& path, bool& noted) { - std::vector spans; - if (value.isNull()) { - return spans; - } - ValueList const* const items = value.asList(); - bool bad = items == nullptr; - for (Value const& item : items != nullptr ? *items : ValueList{}) { - Value const* const column = item.field("column"); - Value const* const rows = item.field("rows"); - std::string const* const columnId = column != nullptr ? column->asString() : nullptr; - std::int64_t const* const count = rows != nullptr ? rows->asInt() : nullptr; - auto const found = columnId != nullptr ? std::ranges::find(columns, *columnId) : columns.end(); - if (found == columns.end() || count == nullptr || *count < 1) { - bad = true; - continue; - } - spans.push_back(RowSpan{ - .column = static_cast(found - columns.begin()), - .rows = static_cast(*count), - }); - } - if (bad && !noted) { - noted = true; - report(path, - "rowSpans is " + canonicalJson(value) + "; a span is {column: a column's id, rows: an integer from 1}"); - } - return spans; -} - -void ScreenCore::ownQueriesOf(ExprPtr const& expr, RtScope const& scope, BoundaryRuntime& boundary, - std::set>& seen) { - if (!expr) { - return; - } - bool const control = expr->kind == ExprKind::Query || expr->kind == ExprKind::Pending || - expr->kind == ExprKind::Error || expr->kind == ExprKind::ErrorKind || - expr->kind == ExprKind::Refusal; - if (control || expr->kind == ExprKind::Ref) { - NameRef const* const found = scope.find(expr->name); - if (found != nullptr && found->category == NameCategory::Query && seen.insert(expr->name).second) { - boundary.queries.push_back(found->query); - } - if (expr->kind == ExprKind::Ref && found != nullptr && found->category == NameCategory::Let && - seen.insert("let:" + expr->name).second) { - ownQueriesOf(found->letExpr, scope, boundary, seen); - } - } - for (ExprPtr const& arg : expr->args) { - ownQueriesOf(arg, scope, boundary, seen); - } - for (auto const& [name, field] : expr->fields) { - static_cast(name); - ownQueriesOf(field, scope, boundary, seen); - } -} - -void ScreenCore::ownQueries(DocNode const& node, RtScope const& scope, BoundaryRuntime& boundary, - std::set>& seen) { - if (node.kind == "boundary") { - return; - } - for (auto const& [key, expr] : node.props) { - static_cast(key); - ownQueriesOf(expr, scope, boundary, seen); - } - for (auto const& [key, nodes] : node.children) { - static_cast(key); - for (DocNodePtr const& child : nodes) { - ownQueries(*child, scope, boundary, seen); - } - } - for (auto const& [key, parts] : node.parts) { - static_cast(key); - for (DocNodePtr const& part : parts) { - ownQueries(*part, scope, boundary, seen); - } - } -} - -Node ScreenCore::lowerBoundary(DocNode const& node, LowerCtx const& ctx) { - auto const boundary = std::make_shared(); - std::set> seen; - for (DocNodePtr const& child : node.nodes("children")) { - ownQueries(*child, *ctx.scope, *boundary, seen); - } - auto const bindings = std::make_shared(*ctx.bindings); - bindings->push_back(Binding{ - .name = "boundary", - .read = - [boundary] { - for (QueryRuntime const* const query : boundary->queries) { - Value const error = query->error(); - if (!error.isNull() && query->value().isNull()) { - return Value{ValueRecord{{"error", error}}}; - } - } - return Value{ValueRecord{{"error", Value{}}}}; - }, - }); - LowerCtx const errorCtx{.scope = ctx.scope, .bindings = bindings, .boundary = boundary}; - LowerCtx const childCtx{.scope = ctx.scope, .bindings = ctx.bindings, .boundary = boundary}; - auto const group = [this](std::span nodes, LowerCtx const& where) -> Node { - return nodes.empty() ? ui::spacer() : lowerAll(nodes, where); - }; - Switch spec; - spec.cases.push_back(SwitchCase{.key = Key{std::int64_t{0}}, .node = group(node.nodes("loading"), childCtx)}); - spec.cases.push_back(SwitchCase{.key = Key{std::int64_t{1}}, .node = group(node.nodes("error"), errorCtx)}); - spec.cases.push_back(SwitchCase{.key = Key{std::int64_t{2}}, .node = group(node.nodes("children"), childCtx)}); - spec.selector = slotProp([boundary] { - bool loading = false; - for (QueryRuntime const* const query : boundary->queries) { - if (!query->settled()) { - loading = true; - } else if (query->value().isNull() && !query->error().isNull()) { - return Key{std::int64_t{1}}; - } - } - return Key{std::int64_t{loading ? 0 : 2}}; - }); - commonOf(node, ctx, nullptr, spec.common); - return ui::switchOf(std::move(spec)); -} - -Node ScreenCore::lowerCustom(DocNode const& node, LowerCtx const& ctx) { - std::string const name{node.name("name")}; - // A loaded document's custom node names a declared component, and every component has a fallback. - Component const& component = _doc->components.at(name); - std::vector> props; - for (DocNodePtr const& record : node.partList("props")) { - for (auto const& [key, expr] : record->props) { - props.emplace_back(key, expr); - } - } - auto const bindings = std::make_shared(); - bindings->push_back(Binding{ - .name = "props", - .read = - [scope = ctx.scope, outer = ctx.bindings, props = std::move(props)] { - ValueRecord record; - for (auto const& [key, expr] : props) { - record.insert_or_assign(key, evalIn(*scope, outer.get(), expr)); - } - return Value{std::move(record)}; - }, - }); - auto const scope = std::make_shared(*this, nullptr, nullptr, ctx.scope->nodes.depth() + 1); - scope->formatSource = ctx.scope; - scope->usePrefix = focusKeyOf(node.path, *ctx.scope) + ">"; - DocNode const& fallback = *component.fallback; - declare(*scope, nullptr, {&fallback}, {}); - Node lowered = lower(fallback, LowerCtx{.scope = scope, .bindings = bindings, .boundary = nullptr}); - Custom spec{ - .name = name, - .fallback = std::move(lowered), - .props = {}, - .minVersion = - static_cast(std::clamp(component.version, 0, std::numeric_limits::max())), - .onEvent = {}, - }; - // Every declared prop is given, a missing one as its type's empty value: a component lacking one is refused. - for (auto const& [prop, type] : component.props) { - ExprPtr expr; - for (DocNodePtr const& record : node.partList("props")) { - if (ExprPtr const given = record->prop(prop)) { - expr = given; - } - } - if (type == "bool") { - spec.props.push_back(CustomProp{.name = prop, .value = bindProp(ctx, expr, false, boolOf)}); - } else if (type == "number") { - spec.props.push_back(CustomProp{ - .name = prop, - .value = bindProp( - ctx, expr, 0.0, [](Value const& value, FormatContext const&) { return componentNumber(value); }), - }); - } else { - spec.props.push_back(CustomProp{ - .name = prop, - .value = bindProp(ctx, expr, std::string{}, - [type](Value const& value, FormatContext const& format) { - return componentText(value, type, format); - }), - }); - } - } - spec.onEvent = [this, ctx, site = &node, declared = &component](std::string const& event, - std::string const& payload) { - Commands const* const commands = site->event("on." + event); - if (commands == nullptr) { - return; - } - auto const type = declared->events.find(event); - runEvent(commands, ctx, componentPayload(payload, type == declared->events.end() ? nullptr : &type->second)); - }; - return ui::custom(std::move(spec)); -} - -namespace { - -/// @brief One child of an arranged container, as the user's choice places it. -struct ArrangedChild { - /// @brief The child's id. - std::string id; - /// @brief Whether the choice hides it. - bool hidden = false; -}; - -/// @brief A container's children in the order a stored `arrange` choice gives, each marked shown or hidden. -/// -/// A child the choice does not name keeps its declared place after the named ones, shown, and an entry that names no -/// child, names one twice or is not a `{"id", "hidden"}` record is skipped, so a new document version survives an old -/// choice (spec 5 §12b). A choice that is not a list leaves the declared order. Only `"hidden": true` hides. -/// @param stored The point's current choice. -/// @param declared The container's children, in document order. -/// @return Every child, in order. -[[nodiscard]] std::vector arrangedChildren(Value const& stored, - std::span declared) { - auto const isDeclared = [declared](std::string const& childId) { - return std::ranges::find(declared, childId, &DocNode::id) != declared.end(); - }; - std::vector out; - std::set> placed; - if (ValueList const* const entries = stored.asList()) { - for (Value const& entry : *entries) { - Value const* const named = entry.field("id"); - std::string const* const name = named == nullptr ? nullptr : named->asString(); - if (name == nullptr || !isDeclared(*name) || !placed.insert(*name).second) { - continue; - } - Value const* const hidden = entry.field("hidden"); - bool const* const flag = hidden == nullptr ? nullptr : hidden->asBool(); - out.push_back(ArrangedChild{.id = *name, .hidden = flag != nullptr && *flag}); - } - } - for (DocNode const* const child : declared) { - if (!placed.contains(child->id)) { - out.push_back(ArrangedChild{.id = child->id}); - } - } - return out; -} - -/// @brief The ids of the children an `arrange` choice shows, in its order (`arrangedChildren`, without the hidden). -/// @param stored The point's current choice. -/// @param declared The container's children, in document order. -/// @return The ids to show, in order. -[[nodiscard]] std::vector arrangedOrder(Value const& stored, std::span declared) { - std::vector order; - for (ArrangedChild const& child : arrangedChildren(stored, declared)) { - if (!child.hidden) { - order.emplace_back(child.id); - } - } - return order; -} - -/// @brief An arrangement as the choice an `arrange` point stores. -/// @param children Every child, in order. -/// @return `[{"id", "hidden"}, …]`. -[[nodiscard]] Value arrangementValue(std::vector const& children) { - ValueList entries; - entries.reserve(children.size()); - for (ArrangedChild const& child : children) { - entries.emplace_back(ValueRecord{{"id", Value{child.id}}, {"hidden", Value{child.hidden}}}); - } - return Value{std::move(entries)}; -} - -/// @brief The element of a document tree with @p elementId. -/// @param node The subtree. -/// @param elementId The element's id. -/// @return The element, or `nullptr` when the subtree has none with that id. -// NOLINTNEXTLINE(misc-no-recursion): one level per level of the document tree. -[[nodiscard]] DocNode const* elementNode(DocNode const& node, std::string_view elementId) { - if (node.id == elementId) { - return &node; - } - for (auto const* const groups : {&node.children, &node.parts}) { - for (auto const& [slot, nodes] : *groups) { - static_cast(slot); - for (DocNodePtr const& child : nodes) { - if (DocNode const* const found = elementNode(*child, elementId)) { - return found; - } - } - } - } - return nullptr; -} -} // namespace - -std::string ScreenCore::arrangedBy(std::string const& elementId) const { - if (elementId.empty()) { - return {}; - } - for (auto const& [name, point] : _doc->customize) { - if (point.kind == "arrange" && point.of == elementId) { - return name; - } - } - return {}; -} - -// A keyed list over the children's ids rather than a stack, so a new choice moves the shown widgets, keeping their -// state and focus, and mounts or unmounts only what it shows or hides. A child is lowered in the container's own -// scope: arranging changes where it is, not what it reads. -Node ScreenCore::lowerArranged(DocNode const& node, LowerCtx const& ctx, ElementState* element, - std::string const& point, Axis axis, int gap) { - std::vector declared; - for (DocNodePtr const& child : node.nodes("children")) { - declared.push_back(child.get()); - } - auto order = [this, point, declared] { return arrangedOrder(prefs.get().at(point), declared); }; - auto key = [](Value const& childId) { return keyOf(childId); }; - LowerCtx childCtx = ctx; - childCtx.listGap = axis == Axis::Vertical ? gap : 0; - auto view = [this, childCtx, declared](reactive::Signal const& row) -> Node { - // The order lists only declared ids, so the lookup always finds the child. - auto const found = std::ranges::find(declared, textOf(row.peek(), session.formatting()), &DocNode::id); - return lower(**found, childCtx); - }; - ForEach spec{ - .model = std::make_shared const>(std::move(order), std::move(key), std::move(view)), - .axis = axis, - .gap = gap, - }; - commonOf(node, ctx, element, spec.common); - return makeNode(std::move(spec)); -} - -// One row per child of the arranged container, hidden ones included: a checkbox shows or hides it, and two buttons -// move it a place. Each edit stores the whole arrangement, so the stored list always names every child. -Node ScreenCore::lowerArrangeEditor(DocNode const& node, LowerCtx const& ctx, std::string const& point, - CustomizePoint const& spec, std::function const& choose) { - // The loader checked that `of` names a column or row of this screen. - DocNode const* const container = elementNode(*_doc->view, spec.of); - std::vector declared; - for (DocNodePtr const& child : container->nodes("children")) { - declared.push_back(child.get()); - } - auto const current = [this, point, declared] { return arrangedChildren(prefs.get().at(point), declared); }; - auto const place = [current](std::string const& childId) { - auto const children = current(); - return static_cast(std::ranges::find(children, childId, &ArrangedChild::id) - children.begin()); - }; - // Applies an edit to the arrangement as it stands, read untracked: the edit is a transition, not a binding. - auto const edit = [this, current, choose](std::string const& childId, auto const& change) { - auto children = runtime().untracked(current); - auto const found = std::ranges::find(children, childId, &ArrangedChild::id); - change(children, static_cast(found - children.begin())); - choose(arrangementValue(children)); - }; - auto rows = [current] { - std::vector ids; - for (ArrangedChild const& child : current()) { - ids.emplace_back(child.id); - } - return ids; - }; - auto key = [](Value const& childId) { return keyOf(childId); }; - auto view = [this, current, place, edit](reactive::Signal const& row) -> Node { - std::string const childId = textOf(row.peek(), session.formatting()); - Checkbox shown{.label = childId}; - shown.checked = slotProp([current, childId] { - auto const children = current(); - return !std::ranges::find(children, childId, &ArrangedChild::id)->hidden; - }); - shown.onToggle = [edit, childId](bool checked) { - edit(childId, [checked](std::vector& children, std::size_t index) { - children.at(index).hidden = !checked; - }); - }; - Button moveUp{.label = std::string{"\xE2\x86\x91"}}; - moveUp.onClick = [edit, childId] { - // Clamped rather than refused: at the edge the child swaps with itself, which stores the same order. - edit(childId, [](std::vector& children, std::size_t index) { - std::swap(children.at(index), children.at(std::max(index, std::size_t{1}) - 1)); - }); - }; - moveUp.common.enabled = slotProp([place, childId] { return place(childId) > 0; }); - moveUp.common.a11y.name = "Move " + childId + " up"; - moveUp.common.testId = "arrange-up-" + childId; - Button moveDown{.label = std::string{"\xE2\x86\x93"}}; - moveDown.onClick = [edit, childId] { - edit(childId, [](std::vector& children, std::size_t index) { - std::swap(children.at(index), children.at(std::min(index + 1, children.size() - 1))); - }); - }; - moveDown.common.enabled = - slotProp([current, place, childId] { return place(childId) + 1 < current().size(); }); - moveDown.common.a11y.name = "Move " + childId + " down"; - moveDown.common.testId = "arrange-down-" + childId; - shown.common.testId = "arrange-shown-" + childId; - return ui::row(Row{ - .children = - { - ui::checkbox(std::move(shown)), - ui::button(std::move(moveUp)), - ui::button(std::move(moveDown)), - }, - .gap = 1, - }); - }; - ForEach editor{ - .model = std::make_shared const>(std::move(rows), std::move(key), std::move(view)), - }; - commonOf(node, ctx, nullptr, editor.common); - return makeNode(std::move(editor)); -} - -Node ScreenCore::lowerCustomize(DocNode const& node, LowerCtx const& ctx) { - std::string const point{node.name("point")}; - // A loaded document's customize node names a declared point, and every point has a choice in `prefs`. - CustomizePoint const& spec = _doc->customize.at(point); - auto const choose = [this, point](Value value) { - session.asUser([&] { - ValueRecord next = prefs.peek(); - next.insert_or_assign(point, value); - prefs.set(std::move(next)); - }); - if (host != nullptr) { - host->preferenceChanged(_doc->id, point, value); - } - }; - if (spec.kind == "arrange") { - return lowerArrangeEditor(node, ctx, point, spec, choose); - } - if (spec.kind == "choice") { - Select select; - std::vector options; - options.reserve(spec.options.size()); - for (std::string const& option : spec.options) { - options.push_back(SelectOption{.key = Key{option}, .label = option}); - } - select.options = std::move(options); - select.selected = slotProp>([this, point] -> std::optional { - Value const& chosen = prefs.get().at(point); - return chosen.isNull() ? std::nullopt : std::optional{keyOf(chosen)}; - }); - select.onSelect = [choose](Key const& key) { choose(valueOfKey(key)); }; - commonOf(node, ctx, nullptr, select.common); - return ui::select(std::move(select)); - } - if (spec.kind == "value" && (spec.type.kind == TypeKind::String || spec.type.isAny())) { - TextInput input; - input.value = - slotProp([this, point] { return textOf(prefs.get().at(point), session.formatting()); }); - input.onChange = [choose](std::string text) { choose(Value{std::move(text)}); }; - commonOf(node, ctx, nullptr, input.common); - return ui::textInput(std::move(input)); - } - Text placeholder{.text = point, .role = TextRole::Muted}; - commonOf(node, ctx, nullptr, placeholder.common); - return ui::text(std::move(placeholder)); -} -// NOLINTEND(misc-no-recursion) - -} // namespace detail - -std::vector Screen::headSpans(ExprPtr const& expr) const { - if (expr == nullptr) { - return {}; - } - bool dropped = false; - bool badTone = false; - std::vector spans = - detail::spansOf(detail::evalIn(*_scope, nullptr, expr), _scope->formatting(), dropped, &badTone); - if (dropped) { - _core->report(expr->path, detail::kSpansReason); - } - if (badTone) { - _core->report(expr->path, detail::kSpanToneReason); - } - return spans; -} - -DocNode const* Screen::shownRoot() const { - DocNode const* node = _core->doc().view.get(); - while (node != nullptr && node->kind == "switch") { - Value const value = detail::evalIn(*_scope, nullptr, node->prop("on")); - std::span shown = node->nodes("default"); - for (DocNodePtr const& part : node->partList("cases")) { - if (!(detail::evalIn(*_scope, nullptr, part->prop("when")) == value)) { - continue; - } - if (part->scope.has_value() && detail::declaresNames(*part->scope)) { - return nullptr; - } - shown = part->nodes("children"); - break; - } - node = shown.size() == 1 ? shown.front().get() : nullptr; - } - return node; -} - -bool Screen::pageEdge() const { - DocNode const* const node = shownRoot(); - return node != nullptr && node->flag("pageEdge"); -} - -bool Screen::headJoined() const { - DocNode const* const node = shownRoot(); - return node != nullptr && node->flag("headJoined"); -} - -LeadPlacement Screen::leadPlacement() const { - ExprPtr const& placement = _core->doc().leadPlacement; - if (placement == nullptr) { - return LeadPlacement::Below; - } - Value const value = detail::evalIn(*_scope, nullptr, placement); - if (std::string const* const name = value.asString()) { - if (*name == "inline") { - return LeadPlacement::Inline; - } - if (*name == "end") { - return LeadPlacement::End; - } - if (*name == "below") { - return LeadPlacement::Below; - } - } - if (!value.isNull()) { - _core->report(placement->path, "`leadPlacement` is `below`, `inline` or `end`"); - } - return LeadPlacement::Below; -} - -TextRole Screen::titleRole() const { - ExprPtr const& role = _core->doc().titleRole; - if (role == nullptr) { - return TextRole::Heading; - } - Value const value = detail::evalIn(*_scope, nullptr, role); - if (std::string const* const name = value.asString()) { - if (*name == "headline") { - return TextRole::Headline; - } - if (*name == "heading") { - return TextRole::Heading; - } - } - if (!value.isNull()) { - _core->report(role->path, "`titleRole` is `heading` or `headline`"); - } - return TextRole::Heading; -} - -std::string Screen::headSurface() const { - Value const value = detail::evalIn(*_scope, nullptr, _core->doc().headSurface); - std::string const* const name = value.asString(); - return name == nullptr ? std::string{} : *name; -} - -std::string Screen::pageSurface() const { - Value const value = detail::evalIn(*_scope, nullptr, _core->doc().pageSurface); - std::string const* const name = value.asString(); - return name == nullptr ? std::string{} : *name; -} - -std::vector Screen::subtitleSpans() const { return headSpans(_core->doc().subtitleSpans); } - -std::vector Screen::titleSpans() const { return headSpans(_core->doc().titleSpans); } - -std::vector Screen::eyebrowSpans() const { return headSpans(_core->doc().eyebrowSpans); } - -BorrowedModel Screen::lend(std::string_view alias) const { - detail::NameRef const* const found = _scope->find(alias); - if (found == nullptr || found->category != detail::NameCategory::Model) { - return {}; - } - detail::ModelAlias& model = *found->model; - return BorrowedModel{ - .channel = detail::channelOf(model, *_core), - .token = _core->runtime().untracked([&] { return model.token->get(); }), - }; -} - -std::expected, Refusal> Interpreter::mount(std::shared_ptr doc, - ValueRecord const& params, IViewBackend& backend, - MountOptions const& options) { - auto const refuse = [&](std::string path, std::string reason) { - return std::unexpected(Refusal{.document = doc->id, .path = std::move(path), .reason = std::move(reason)}); - }; - if (!doc->view) { - return refuse("", "the document has no view"); - } - ValueRecord given; - for (auto const& [name, type] : doc->params) { - auto const found = params.find(name); - Value value = found == params.end() ? Value{} : found->second; - if (!type.admits(value)) { - return refuse(pointerAppend("/params", name), value.isNull() - ? "param `" + name + "` is missing" - : "param `" + name + "` is not a " + type.name()); - } - given.insert_or_assign(name, std::move(value)); - } - for (ModelDecl const& model : doc->scope.models) { - if (model.instance == InstanceMode::Borrowed && !options.borrowed.contains(model.name)) { - return refuse(model.path, "alias `" + model.name + "` borrows a model its opener did not lend"); - } - } - reactive::Runtime& runtime = _session->runtime(); - std::unique_ptr screen{new Screen{}}; - screen->_core = std::make_unique(doc, *_session, *_dispatcher, _options, options); - detail::ScreenCore& core = *screen->_core; - if (options.keepStateOf != nullptr) { - core.keptStates = options.keepStateOf->ownState(); - } - screen->_scope = std::make_shared(core, nullptr, nullptr, options.depth); - core.rootScope = screen->_scope; - detail::RtScope& scope = *screen->_scope; - scope.submitted = &core.submitted; - scope.showErrors = doc->showErrors; - for (auto const& [name, value] : given) { - detail::NameRef ref; - ref.category = detail::NameCategory::Param; - ref.param = value; - scope.names.insert_or_assign(name, std::move(ref)); - } - std::vector lists; - for (auto const& [key, commands] : doc->lifecycle) { - static_cast(key); - lists.push_back(&commands); - } - for (auto const& [chord, commands] : doc->keys) { - static_cast(chord); - lists.push_back(&commands); - } - detail::headCommandLists(*doc, lists); - Node root = runtime.untracked([&] { - core.declare(scope, &doc->scope, {doc->view.get()}, lists); - detail::LowerCtx const ctx{ - .scope = screen->_scope, - .bindings = std::make_shared(), - .boundary = nullptr, - }; - Node lowered = core.lower(*doc->view, ctx); - screen->_headStatus = core.lowerBadgeParts(doc->status, ctx); - screen->_headActions = core.lowerActionParts(doc->actions, ctx); - screen->_headMenu = core.lowerHeadMenu(doc->menu, ctx); - screen->_headTools = core.lowerHeadTools(doc->tools, ctx); - if (!doc->keys.empty()) { - std::vector keys; - for (auto const& [chord, commands] : doc->keys) { - keys.push_back(KeyBinding{ - .chord = chord, - .onPress = [&core, ctx, list = &commands] { core.runEvent(list, ctx, Value{}); }, - }); - } - Column column{.children = {std::move(lowered)}}; - column.common.keys = std::move(keys); - lowered = ui::column(std::move(column)); - } - return lowered; - }); - screen->_mounted = std::make_unique(runtime, backend, std::move(root), options.parent, options.depth + 1); - screen->_core->focusElement = [mounted = screen->_mounted.get()](std::string_view element) { - return mounted->focus(element); - }; - screen->runLifecycle("onMount"); - return screen; -} - -namespace { - -// The texts of a tour evaluated in the app scope. -Tour lowerTour(detail::RtScope& scope, TourDecl const& declared) { - auto const textOf = [&scope](ExprPtr const& expr) { - return expr == nullptr ? std::string{} - : detail::textOf(detail::evalIn(scope, nullptr, expr), scope.formatting()); - }; - Tour tour{.id = declared.id, - .screen = declared.screen, - .title = textOf(declared.title), - .summary = textOf(declared.summary), - .steps = {}, - .revision = declared.revision}; - for (TourStepDecl const& step : declared.steps) { - tour.steps.push_back(TourStep{.title = textOf(step.title), - .body = textOf(step.body), - .screen = step.screen, - .params = step.params, - .target = step.target, - .advanceOn = step.advanceOn}); - } - return tour; -} - -// The app document's tours, then the runtime ones. A runtime tour with one of the app document's ids is left out, -// since the server refuses one and an old list may still hold it. -std::vector lowerTours(Document const& doc, detail::RtScope& scope, std::vector const& runtime) { - std::vector out; - out.reserve(doc.tours.size()); - for (TourDecl const& declared : doc.tours) { - out.push_back(lowerTour(scope, declared)); - } - for (TourDecl const& declared : runtime) { - if (std::ranges::none_of(out, [&declared](Tour const& kept) { return kept.id == declared.id; })) { - out.push_back(lowerTour(scope, declared)); - } - } - return out; -} - -} // namespace - -std::expected, Refusal> Interpreter::mountApp(std::shared_ptr doc) { - if (doc->id != "app") { - return std::unexpected( - Refusal{.document = doc->id, .path = "/id", .reason = "the app document's id is `app`"}); - } - if (_session->appScope() != nullptr) { - return std::unexpected( - Refusal{.document = doc->id, .path = {}, .reason = "an app document is already mounted on the session"}); - } - std::unique_ptr root{new AppRoot{}}; - root->_core = std::make_unique(doc, *_session, *_dispatcher, _options, MountOptions{}); - detail::ScreenCore& core = *root->_core; - root->_scope = std::make_shared(core, nullptr, nullptr, 0); - core.rootScope = root->_scope; - std::vector lists; - for (auto const& [key, commands] : doc->lifecycle) { - static_cast(key); - lists.push_back(&commands); - } - _session->runtime().untracked([&] { - core.declare(*root->_scope, &doc->scope, {}, lists); - detail::LowerCtx const ctx{ - .scope = root->_scope, - .bindings = std::make_shared(), - .boundary = nullptr, - }; - std::vector badges = core.lowerBadgeParts(doc->navigation, ctx); - for (std::size_t index = 0; index < badges.size(); ++index) { - root->_navigation.push_back(AppRoot::PlacedBadge{ - .screen = std::string{doc->navigation.at(index)->name("screen")}, - .badge = std::move(badges.at(index)), - }); - } - }); - root->_navigationBadges = std::make_unique>>( - _session->runtime(), [placed = &root->_navigation] { - std::vector shown; - for (AppRoot::PlacedBadge const& entry : *placed) { - if (entry.badge.visible.evaluate()) { - shown.push_back(NavigationBadge{ - .screen = entry.screen, - .text = entry.badge.text.evaluate(), - .tone = entry.badge.tone.evaluate(), - }); - } - } - return shown; - }); - // One computed value for every tour: the texts are few, and a change of locale changes all of them at once. - root->_runtimeTours = std::make_unique const>>>( - _session->runtime(), std::make_shared const>()); - root->_tours = std::make_unique>>( - _session->runtime(), [doc, scope = root->_scope.get(), runtime = root->_runtimeTours.get()] { - return lowerTours(*doc, *scope, *runtime->get()); - }); - // The app document's date patterns are the application's: every screen of the bundle shows and reads dates so. - if (!doc->datePattern.empty() || !doc->dateTimePattern.empty()) { - _session->setDatePatterns(doc->datePattern, doc->dateTimePattern); - } - _session->setAppScope(root->_scope.get()); - if (auto const found = doc->lifecycle.find("onMount"); found != doc->lifecycle.end()) { - root->runCommands(found->second); - } - return root; -} - } // namespace morph::ui diff --git a/src/ui/interpreter_charts.cpp b/src/ui/interpreter_charts.cpp new file mode 100644 index 000000000..1e8758909 --- /dev/null +++ b/src/ui/interpreter_charts.cpp @@ -0,0 +1,989 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Charts, summaries and arranged tables. + +#include "interpreter_grid_detail.hpp" + +namespace morph::ui::detail { + +namespace { + +/// The summary part a summary row's record names: one of the table's `summaries`, or of its group's. +DocNode const* summaryPartOf(DocNode const& table, Value const& record); + +/// @brief A chart's exact value at @p places, as the active locale writes it. +/// @param value The value. +/// @param places The places, at most 18. +/// @param format The formatting facts. +/// @return The text; the exact JSON when the rounded value does not fit. +[[nodiscard]] std::string chartNumberText(math::Rational const& value, std::uint32_t places, + FormatContext const& format) { + std::optional rounded = + math::checkedRoundToDecimalPlaces(value, math::DecimalPlaces{places}, math::RoundingMode::HalfEven); + if (!rounded) { + return textOf(Value{Decimal{value}}, format); + } + rounded->decimalPlaces = math::DecimalPlaces{places}; + return textOf(Value{Decimal{*rounded}}, format); +} + +/// @brief A reference line's stroke by its document name. +/// @param name `solid`, `dashed`, `dotted`, or empty for solid; the loader refuses any other. +/// @return The stroke. +[[nodiscard]] ChartLineStyle chartLineStyle(std::string_view name) { + if (name == "dashed") { + return ChartLineStyle::Dashed; + } + return name == "dotted" ? ChartLineStyle::Dotted : ChartLineStyle::Solid; +} + +/// @brief Where a point sits along a value axis that a document may have fixed, and on which side it is clipped. +/// @param value The point's value. +/// @param range The axis. +/// @return The value drawn, the axis end for a value outside, and the side it lies beyond. +[[nodiscard]] std::pair chartClipped(math::Rational const& value, ChartRange const& range) { + if (value < range.low) { + return {range.low, ChartClip::Below}; + } + if (value > range.high) { + return {range.high, ChartClip::Above}; + } + return {value, ChartClip::None}; +} + +} // namespace + +std::vector ScreenCore::chartLines(DocNode const& node, RtScope const& scope, + Bindings const* bindings, std::optional& unit) { + FormatContext const& format = scope.formatting(); + std::vector lines; + for (DocNodePtr const& part : node.partList("lines")) { + ExprPtr const valueExpr = part->prop("value"); + Value const value = evalIn(scope, bindings, valueExpr); + std::optional const magnitude = + value.isNull() ? std::nullopt : chartMagnitude(value, valueExpr->path, unit); + if (!magnitude) { + continue; + } + detail::ChartRawLine line{.value = *magnitude, .label = std::nullopt}; + if (ExprPtr const label = part->prop("label")) { + line.label = textOf(evalIn(scope, bindings, label), format); + } + if (ExprPtr const tone = part->prop("tone")) { + line.tone = chartToneOf(evalIn(scope, bindings, tone), tone->path).value_or(Tone::Neutral); + } + line.style = detail::chartLineStyle(part->name("style")); + lines.push_back(std::move(line)); + } + return lines; +} + +ChartRange ScreenCore::chartFixedRange(DocNode const& node, RtScope const& scope, Bindings const* bindings, + std::optional& unit, ChartRange const& range) { + ChartRange fixed = range; + for (auto const& [key, end] : {std::pair{"yMin", &fixed.low}, std::pair{"yMax", &fixed.high}}) { + if (ExprPtr const expr = node.prop(key)) { + Value const value = evalIn(scope, bindings, expr); + if (!value.isNull()) { + *end = chartMagnitude(value, expr->path, unit).value_or(*end); + } + } + } + if (fixed.high > fixed.low) { + return fixed; + } + report(pointerAppend(node.path, "yMin"), "`yMin` is not below `yMax`; the chart takes its range from its values"); + return range; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one branch per way a series can be drawn or clipped. +void ScreenCore::chartSeries(ChartData& data, DocNode const& node, RtScope const& scope, Bindings const* bindings, + std::vector>& series, bool positioned, + ChartRange const& range) { + auto const positionOf = [positioned](detail::ChartRawPoint const& point) { + return positioned && point.x ? *point.x + : math::Rational{static_cast(point.index), math::DecimalPlaces{0}}; + }; + std::vector positions; + for (auto const& points : series) { + std::ranges::transform(points, std::back_inserter(positions), positionOf); + } + // The room one position gives its bars: the least distance between two of their positions, gaps included, so a + // bar never grows over the label of an empty position between two. + std::vector barPositions; + { + std::size_t seriesIndex = 0; + for (DocNodePtr const& part : node.partList("series")) { + if (part->name("style") == "bars") { + std::ranges::transform(series.at(seriesIndex), std::back_inserter(barPositions), positionOf); + } + ++seriesIndex; + } + } + std::ranges::sort(barPositions); + std::optional slot; + for (std::size_t next = 1; next < barPositions.size(); ++next) { + auto const distance = math::checkedSub(barPositions.at(next), barPositions.at(next - 1)); + if (distance && distance->numerator > 0 && (!slot || *distance < *slot)) { + slot = *distance; + } + } + if (!barPositions.empty()) { + data.barSlot = realOf(slot.value_or(math::Rational{1, math::DecimalPlaces{0}})); + } + // A bar is centred on its position and half a slot wide each side, so the axis holds that much beyond the + // outermost position. + if (!barPositions.empty() && !positions.empty()) { + math::Rational const half = math::checkedDiv(slot.value_or(math::Rational{1, math::DecimalPlaces{0}}), + math::Rational{2, math::DecimalPlaces{0}}) + .value_or(math::Rational{0, math::DecimalPlaces{0}}); + auto const [lowest, highest] = std::ranges::minmax(positions); + auto const below = math::checkedSub(lowest, half); + auto const above = math::checkedAdd(highest, half); + if (below && above) { + positions.push_back(*below); + positions.push_back(*above); + } + } + if (std::optional const across = chartRange(positions, 0)) { + data.xMin = realOf(across->low); + data.xMax = realOf(across->high); + } + std::size_t index = 0; + for (DocNodePtr const& part : node.partList("series")) { + ChartSeries drawn; + if (part->name("style") == "bars") { + drawn.style = ChartStyle::Bars; + } + if (ExprPtr const label = part->prop("label")) { + drawn.label = textOf(evalIn(scope, bindings, label), scope.formatting()); + } + drawn.joined = drawn.style == ChartStyle::Line && (!part->flags.contains("joined") || part->flag("joined")); + for (detail::ChartRawPoint& point : series.at(index)) { + ChartPoint out{ + .x = realOf(positionOf(point)), + .y = std::nullopt, + .clip = ChartClip::None, + .xLabel = std::move(point.xLabel), + .tone = point.tone, + .note = std::move(point.note), + }; + if (point.y) { + auto const [shown, clip] = detail::chartClipped(*point.y, range); + out.y = realOf(shown); + out.clip = clip; + } + drawn.points.push_back(std::move(out)); + } + data.series.push_back(std::move(drawn)); + ++index; + } +} + +ChartData ScreenCore::chartData(DocNode const& node, RtScope const& scope, Bindings const* bindings) { + FormatContext const& format = scope.formatting(); + ChartData data; + data.summary = textOf(evalIn(scope, bindings, node.prop("summary")), format); + if (ExprPtr const label = node.prop("yLabel")) { + data.yLabel = textOf(evalIn(scope, bindings, label), format); + } + std::optional unit; + detail::ChartAxisKinds kinds; + std::vector> series; + for (DocNodePtr const& part : node.partList("series")) { + series.push_back(chartPoints(*part, scope, bindings, unit, kinds)); + } + std::vector const lines = chartLines(node, scope, bindings, unit); + // The values the axis must hold, and the places they are shown at. + std::vector values; + for (auto const& points : series) { + for (detail::ChartRawPoint const& point : points) { + if (point.y) { + values.push_back(*point.y); + } + } + } + std::ranges::transform(lines, std::back_inserter(values), &detail::ChartRawLine::value); + // A bar grows from 0, so the axis holds 0; the baseline's side is padded only when something lies beyond it, so + // that the baseline is the plot's edge when nothing does. + std::vector axisValues = values; + ChartPadding padding; + bool barsHaveValues = false; + { + std::size_t seriesIndex = 0; + for (DocNodePtr const& part : node.partList("series")) { + barsHaveValues = + barsHaveValues || (part->name("style") == "bars" && + std::ranges::any_of(series.at(seriesIndex), [](detail::ChartRawPoint const& point) { + return point.y.has_value(); + })); + ++seriesIndex; + } + } + if (barsHaveValues) { + axisValues.emplace_back(0, math::DecimalPlaces{0}); + padding.low = std::ranges::any_of(values, [](math::Rational const& value) { return value.numerator < 0; }); + padding.high = std::ranges::any_of(values, [](math::Rational const& value) { return value.numerator > 0; }); + } + std::uint32_t widest = 0; + for (math::Rational const& value : values) { + widest = std::max(widest, value.decimalPlaces.value); + } + ExprPtr const placesExpr = node.prop("yPlaces"); + std::int64_t const* const fixedPlaces = placesExpr ? placesExpr->literal.asInt() : nullptr; + std::uint32_t const places = fixedPlaces != nullptr ? static_cast(*fixedPlaces) : widest; + std::optional const computed = chartRange(axisValues, places, padding); + if (!computed) { + report(node.path, "the chart's values overflow its arithmetic; it draws nothing"); + return data; + } + ChartRange const range = chartFixedRange(node, scope, bindings, unit, *computed); + data.yMin = realOf(range.low); + data.yMax = realOf(range.high); + // Three or more lines are the scale a reader reads the chart against; fewer leave the values without one. + std::optional const ticks = lines.size() < 3 ? chartTicks(range) : std::nullopt; + if (ticks) { + std::uint32_t const tickPlaces = std::max(places, ticks->places); + for (math::Rational const& tick : ticks->values) { + data.yTicks.push_back( + ChartTick{.value = realOf(tick), .text = detail::chartNumberText(tick, tickPlaces, format)}); + } + } + for (detail::ChartRawLine const& line : lines) { + data.lines.push_back(ChartLine{ + .value = realOf(line.value), + .label = line.label.value_or(detail::chartNumberText(line.value, places, format)), + .tone = line.tone, + .style = line.style, + }); + } + if (kinds.numbers && kinds.instants) { + report(pointerAppend(node.path, "series"), + "a chart's `x` values are all numbers or all dates and instants; the points are spaced by index"); + } + chartSeries(data, node, scope, bindings, series, kinds.numbers != kinds.instants, range); + return data; +} + +std::optional ScreenCore::rowToneOf(Value const& value, std::string const& path, bool& noted) { + if (value.isNull()) { + return std::nullopt; + } + if (std::optional const tone = toneNamed(value)) { + return tone; + } + if (!noted) { + noted = true; + report(path, "rowTone is " + canonicalJson(value) + "; a tone is neutral, info, ok, warn or err"); + } + return std::nullopt; +} + +std::vector ScreenCore::rowSpansOf(Value const& value, std::vector const& columns, + std::string const& path, bool& noted) { + std::vector spans; + if (value.isNull()) { + return spans; + } + ValueList const* const items = value.asList(); + bool bad = items == nullptr; + for (Value const& item : items != nullptr ? *items : ValueList{}) { + Value const* const column = item.field("column"); + Value const* const rows = item.field("rows"); + Value const* const across = item.field("columns"); + std::string const* const columnId = column != nullptr ? column->asString() : nullptr; + std::int64_t const one = 1; + std::int64_t const* const count = rows != nullptr ? rows->asInt() : &one; + std::int64_t const* const wide = across != nullptr ? across->asInt() : &one; + auto const found = columnId != nullptr ? std::ranges::find(columns, *columnId) : columns.end(); + if (found == columns.end() || count == nullptr || *count < 1 || wide == nullptr || *wide < 1) { + bad = true; + continue; + } + spans.push_back(RowSpan{ + .column = static_cast(found - columns.begin()), + .rows = static_cast(*count), + .columns = static_cast(*wide), + }); + } + if (bad && !noted) { + noted = true; + report(path, "rowSpans is " + canonicalJson(value) + + "; a span is {column: a column's id, rows: an integer from 1, columns: an integer from 1}"); + } + return spans; +} + +namespace { + +/// A summary cell's text: by the column's places when it has them and the value is a number, else the value's own +/// text; empty for `null` (a `mean` of no rows). +[[nodiscard]] std::string summaryText(Value const& value, std::optional places, + FormatContext const& format) { + if (value.isNull()) { + return {}; + } + bool const number = value.asInt() != nullptr || value.asDecimal() != nullptr || value.asQuantity() != nullptr; + if (places && number) { + table::ColumnDisplay display; + display.decimals = places; + table::TableColumn const kind = columnFor(value, display); + return formatCell(cellOfRecord(&value, kind, nullptr), kind, format); + } + return textOf(value, format); +} + +} // namespace + +std::vector> gridRuns(GridTable& held) { + std::vector> runs; + held.runOrder.clear(); + GridRows const& view = held.grid.source->view(); + FormRowsSource const& source = view.source(); + std::span const columns = source.columns(); + if (columns.empty() || columns.back().id != kGroupRunColumn) { + return runs; + } + std::size_t const runColumn = columns.size() - 1; + std::shared_ptr const snapshot = source.snapshot(); + std::unordered_map runOf; + for (std::size_t row = 0; row < snapshot->rowCount(); ++row) { + table::Cell const cell = snapshot->cell(row, runColumn); + if (std::int64_t const* const run = std::get_if(&cell)) { + runOf.insert_or_assign(snapshot->rowId(row), static_cast(*run)); + } + } + std::map seen; + std::optional current; + std::int64_t const total = view.total().rows; + for (std::int64_t index = 0; index < total; ++index) { + std::optional const ref = view.row(index); + auto const found = ref ? runOf.find(ref->key) : runOf.end(); + std::size_t const run = found == runOf.end() ? 0 : found->second; + if (current != run || runs.empty()) { + current = run; + runs.emplace_back(index, 0); + held.runOrder.emplace_back(run, seen[run]++); + } + ++runs.back().second; + } + return runs; +} + +RowRecord gridHeading(GridTable& held, std::size_t ordinal) { + if (ordinal >= held.runOrder.size()) { + return RowRecord{.key = Key{std::string{"\x1Fgroup:"} + std::to_string(ordinal)}, .row = Value{}}; + } + auto const [run, occurrence] = held.runOrder.at(ordinal); + std::span const records = held.grid.source->view().source().runRecords(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): guarded by `run < records.size()` in the same expression + Value record = run < records.size() ? records[run] : Value{}; + Value const* const key = record.field(kGroupHeadingField); + std::string text = key != nullptr && key->asString() != nullptr ? *key->asString() : std::string{"\x1Fgroup"}; + if (occurrence > 0) { + text += "/" + std::to_string(occurrence); + } + return RowRecord{.key = Key{std::move(text)}, .row = std::move(record)}; +} + +// The rows a grid with summaries or a group is mounted over: the decorator's, a data row's cell as the grid draws it, +// a summary row's cell its part's expression for the column read with `rows` the records of the data rows in its +// scope and `column` the column's id, shown at the column's places, and a heading row its group's heading. Every +// column's cells are built per row, so a cell built for a data row is never rebound to a summary row. + +std::vector> rowsRuns(RowsTable& table) { + std::vector> runs; + table.runHeadings.clear(); + std::int64_t const total = table.rows->total().rows; + for (std::int64_t index = 0; index < total; ++index) { + std::optional const ref = table.rows->row(index); + Value const* const heading = ref ? ref->row.field(kGroupHeadingField) : nullptr; + if (heading != nullptr && heading->asString() != nullptr) { + runs.emplace_back(index, 0); + table.runHeadings.push_back(*heading->asString()); + } + if (!runs.empty()) { + ++runs.back().second; + } + } + return runs; +} + +ValueList rowsSummaryScope(RowsTable const& table, Value const& record) { + TableView const& view = table.view->get(); + Value const* const run = record.field(kSummaryRunField); + if (run == nullptr || run->asInt() == nullptr) { + // NOLINTNEXTLINE(modernize-return-braced-init-list): the explicit type states that the rows are copied from the iterator range into a ValueList + return ValueList(view.rows.begin(), view.rows.end()); + } + auto const ordinal = static_cast(std::max(*run->asInt(), 0)); + if (ordinal >= table.runHeadings.size()) { + return {}; + } + std::string const& heading = table.runHeadings.at(ordinal); + std::optional runIndex; + for (std::size_t at = 0; at < view.runs.size(); ++at) { + Value const* const key = view.runs.at(at).field(kGroupHeadingField); + if (key != nullptr && key->asString() != nullptr && *key->asString() == heading) { + runIndex = at; + } + } + ValueList rows; + for (std::size_t at = 0; runIndex && at < view.rows.size() && at < view.runOf.size(); ++at) { + if (view.runOf.at(at) == *runIndex) { + rows.push_back(view.rows.at(at)); + } + } + return rows; +} + +namespace { + +DocNode const* summaryPartOf(DocNode const& table, Value const& record) { + Value const* const key = record.field(kSummaryField); + if (key == nullptr || key->asString() == nullptr) { + return nullptr; + } + std::span parts = table.partList("summaries"); + if (record.field(kSummaryRunField) != nullptr) { + std::span const groups = table.partList("group"); + parts = groups.empty() ? std::span{} : groups.front()->partList("summaries"); + } + for (DocNodePtr const& part : parts) { + if (part->name("key") == *key->asString()) { + return part.get(); + } + } + return nullptr; +} + +} // namespace + +std::string summaryTestId(Value const& record, std::string const& column) { + Value const* const key = record.field(kSummaryField); + Value const* const run = record.field(kSummaryRunField); + std::int64_t const* const ordinal = run != nullptr ? run->asInt() : nullptr; + return "summary_" + (ordinal != nullptr ? std::to_string(*ordinal) + "_" : std::string{}) + + (key != nullptr && key->asString() != nullptr ? *key->asString() : std::string{}) + "_" + column; +} + +// NOLINTNEXTLINE(readability-convert-member-functions-to-static): a ScreenCore member so the summary lookup stays beside the other value readers that use the core's state +std::optional ScreenCore::summaryValue(DocNode const& table, Value const& record, std::string const& column, + LowerCtx const& ctx, ValueList rows) { + DocNode const* const part = summaryPartOf(table, record); + if (part == nullptr) { + return std::nullopt; + } + ExprPtr expr; + for (DocNodePtr const& cells : part->partList("cells")) { + if (ExprPtr const cell = cells->prop(column)) { + expr = cell; + } + } + if (!expr) { + return std::nullopt; + } + Bindings scoped = ctx.bindings != nullptr ? *ctx.bindings : Bindings{}; + scoped.push_back(Binding{.name = "rows", .read = [rows = std::move(rows)] { return Value{rows}; }}); + scoped.push_back(Binding{.name = "column", .read = [column] { return Value{column}; }}); + return evalIn(*ctx.scope, &scoped, expr); +} + +TableRowLook ScreenCore::summaryLook(DocNode const& table, LowerCtx const& ctx, Value const& record) { + TableRowLook look; + look.summary = true; + // The part's label names the row; a row with none is named by its key. + if (DocNode const* const part = summaryPartOf(table, record)) { + if (ExprPtr const label = part->prop("label")) { + look.label = Prop{textOf(once(ctx, label), ctx.scope->formatting())}; + } + } + return look; +} + +std::string ScreenCore::gridSummaryText(DocNode const& part, LowerCtx const& ctx, GridTable& held, Value const& record, + std::string const& column) { + Value const* const first = record.field(kSummaryFirstField); + Value const* const count = record.field(kSummaryCountField); + ValueList rows = + summaryScopeRows(held.grid.source->view(), first != nullptr && first->asInt() != nullptr ? *first->asInt() : 0, + count != nullptr && count->asInt() != nullptr ? *count->asInt() : 0); + std::optional const value = summaryValue(part, record, column, ctx, std::move(rows)); + if (!value) { + return {}; + } + auto const places = held.places.find(column); + return summaryText(*value, places == held.places.end() ? std::nullopt : places->second, ctx.scope->formatting()); +} + +// The rows a grid with summaries or a group is mounted over: the decorator's, a data row's cell as the grid draws it, +// a summary row's cell its part's expression for the column (`gridSummaryText`), and a heading row its group's +// heading. Every column's cells are built per row, so a cell built for a data row is never rebound to a summary row. +TableSource ScreenCore::summarySource(DocNode const& part, LowerCtx const& ctx, GridTable& held, + std::vector const& columns) { + auto const ids = std::make_shared>(); + for (TableColumn const& column : columns) { + ids->push_back(column.id); + } + GridTable* const grid = &held; + TableSource made; + made.rows = held.summaries; + made.rowScopedCells.assign(columns.size(), true); + made.cellView = [this, ctx, &part, grid, ids](std::size_t column, reactive::Signal const& row) -> Node { + std::string const columnId = column < ids->size() ? ids->at(column) : std::string{}; + Value const& record = row.peek(); + if (record.field(kSummaryField) == nullptr) { + return grid->grid.source->cellContent(columnId, row); + } + Text text; + text.common.testId = summaryTestId(record, columnId); + text.text = slotProp([this, ctx, &part, grid, columnId, record = &row] { + return gridSummaryText(part, ctx, *grid, record->get(), columnId); + }); + return ui::text(std::move(text)); + }; + made.rowView = [this, ctx, &part](reactive::Signal const& row) -> TableRowLook { + Value const& record = row.peek(); + if (record.field(kSummaryField) != nullptr) { + return summaryLook(part, ctx, record); + } + if (Value const* const heading = record.field(kGroupHeadingField); heading != nullptr && heading->asString()) { + return headingRow(part, ctx, row, *heading->asString()); + } + return {}; + }; + return made; +} + +// NOLINTBEGIN(misc-no-recursion): an expression nests its arguments and fields, and a node its children; the walks +// follow them. +void ScreenCore::ownQueriesOf(ExprPtr const& expr, RtScope const& scope, BoundaryRuntime& boundary, + std::set>& seen) { + if (!expr) { + return; + } + bool const control = expr->kind == ExprKind::Query || expr->kind == ExprKind::Pending || + expr->kind == ExprKind::Error || expr->kind == ExprKind::ErrorKind || + expr->kind == ExprKind::Refusal; + if (control || expr->kind == ExprKind::Ref) { + NameRef const* const found = scope.find(expr->name); + if (found != nullptr && found->category == NameCategory::Query && seen.insert(expr->name).second) { + boundary.queries.push_back(found->query); + } + if (expr->kind == ExprKind::Ref && found != nullptr && found->category == NameCategory::Let && + seen.insert("let:" + expr->name).second) { + ownQueriesOf(found->letExpr, scope, boundary, seen); + } + } + for (ExprPtr const& arg : expr->args) { + ownQueriesOf(arg, scope, boundary, seen); + } + for (auto const& [name, field] : expr->fields) { + static_cast(name); + ownQueriesOf(field, scope, boundary, seen); + } +} + +void ScreenCore::ownQueries(DocNode const& node, RtScope const& scope, BoundaryRuntime& boundary, + std::set>& seen) { + if (node.kind == "boundary") { + return; + } + for (auto const& [key, expr] : node.props) { + static_cast(key); + ownQueriesOf(expr, scope, boundary, seen); + } + for (auto const& [key, nodes] : node.children) { + static_cast(key); + for (DocNodePtr const& child : nodes) { + ownQueries(*child, scope, boundary, seen); + } + } + for (auto const& [key, parts] : node.parts) { + static_cast(key); + for (DocNodePtr const& part : parts) { + ownQueries(*part, scope, boundary, seen); + } + } +} +// NOLINTEND(misc-no-recursion) + +Node ScreenCore::lowerBoundary(DocNode const& node, LowerCtx const& ctx) { + auto const boundary = std::make_shared(); + std::set> seen; + for (DocNodePtr const& child : node.nodes("children")) { + ownQueries(*child, *ctx.scope, *boundary, seen); + } + auto const bindings = std::make_shared(*ctx.bindings); + bindings->push_back(Binding{ + .name = "boundary", + .read = + [boundary] { + for (QueryRuntime const* const query : boundary->queries) { + Value const error = query->error(); + if (!error.isNull() && query->value().isNull()) { + return Value{ValueRecord{{"error", error}}}; + } + } + return Value{ValueRecord{{"error", Value{}}}}; + }, + }); + LowerCtx const errorCtx{.scope = ctx.scope, .bindings = bindings, .boundary = boundary}; + LowerCtx const childCtx{.scope = ctx.scope, .bindings = ctx.bindings, .boundary = boundary}; + auto const group = [this](std::span nodes, LowerCtx const& where) -> Node { + return nodes.empty() ? ui::spacer() : lowerAll(nodes, where); + }; + Switch spec; + spec.cases.push_back(SwitchCase{.key = Key{std::int64_t{0}}, .node = group(node.nodes("loading"), childCtx)}); + spec.cases.push_back(SwitchCase{.key = Key{std::int64_t{1}}, .node = group(node.nodes("error"), errorCtx)}); + spec.cases.push_back(SwitchCase{.key = Key{std::int64_t{2}}, .node = group(node.nodes("children"), childCtx)}); + spec.selector = slotProp([boundary] { + bool loading = false; + for (QueryRuntime const* const query : boundary->queries) { + if (!query->settled()) { + loading = true; + } else if (query->value().isNull() && !query->error().isNull()) { + return Key{std::int64_t{1}}; + } + } + return Key{std::int64_t{loading ? 0 : 2}}; + }); + commonOf(node, ctx, nullptr, spec.common); + return ui::switchOf(std::move(spec)); +} + +Node ScreenCore::lowerCustom(DocNode const& node, LowerCtx const& ctx) { + std::string const name{node.name("name")}; + // A loaded document's custom node names a declared component, and every component has a fallback. + Component const& component = _doc->components.at(name); + std::vector> props; + for (DocNodePtr const& record : node.partList("props")) { + for (auto const& [key, expr] : record->props) { + props.emplace_back(key, expr); + } + } + auto const bindings = std::make_shared(); + bindings->push_back(Binding{ + .name = "props", + .read = + [scope = ctx.scope, outer = ctx.bindings, props = std::move(props)] { + ValueRecord record; + for (auto const& [key, expr] : props) { + record.insert_or_assign(key, evalIn(*scope, outer.get(), expr)); + } + return Value{std::move(record)}; + }, + }); + auto const scope = std::make_shared(*this, nullptr, nullptr, ctx.scope->nodes.depth() + 1); + scope->formatSource = ctx.scope; + scope->usePrefix = focusKeyOf(node.path, *ctx.scope) + ">"; + DocNode const& fallback = *component.fallback; + declare(*scope, nullptr, {&fallback}, {}); + Node lowered = lower(fallback, LowerCtx{.scope = scope, .bindings = bindings, .boundary = nullptr}); + Custom spec{ + .name = name, + .fallback = std::move(lowered), + .props = {}, + .minVersion = + static_cast(std::clamp(component.version, 0, std::numeric_limits::max())), + .onEvent = {}, + }; + // Every declared prop is given, a missing one as its type's empty value: a component lacking one is refused. + for (auto const& [prop, type] : component.props) { + ExprPtr expr; + for (DocNodePtr const& record : node.partList("props")) { + if (ExprPtr const given = record->prop(prop)) { + expr = given; + } + } + if (type == "bool") { + spec.props.push_back(CustomProp{.name = prop, .value = bindProp(ctx, expr, false, boolOf)}); + } else if (type == "number") { + spec.props.push_back(CustomProp{ + .name = prop, + .value = bindProp( + ctx, expr, 0.0, [](Value const& value, FormatContext const&) { return componentNumber(value); }), + }); + } else { + spec.props.push_back(CustomProp{ + .name = prop, + .value = bindProp(ctx, expr, std::string{}, + [type](Value const& value, FormatContext const& format) { + return componentText(value, type, format); + }), + }); + } + } + spec.onEvent = [this, ctx, site = &node, declared = &component](std::string const& event, + std::string const& payload) { + Commands const* const commands = site->event("on." + event); + if (commands == nullptr) { + return; + } + auto const type = declared->events.find(event); + runEvent(commands, ctx, componentPayload(payload, type == declared->events.end() ? nullptr : &type->second)); + }; + return ui::custom(std::move(spec)); +} + +namespace { + +/// @brief One child of an arranged container, as the user's choice places it. +struct ArrangedChild { + /// @brief The child's id. + std::string id; + /// @brief Whether the choice hides it. + bool hidden = false; +}; + +/// @brief A container's children in the order a stored `arrange` choice gives, each marked shown or hidden. +/// +/// A child the choice does not name keeps its declared place after the named ones, shown, and an entry that names no +/// child, names one twice or is not a `{"id", "hidden"}` record is skipped, so a new document version survives an old +/// choice (spec 5 §12b). A choice that is not a list leaves the declared order. Only `"hidden": true` hides. +/// @param stored The point's current choice. +/// @param declared The container's children, in document order. +/// @return Every child, in order. +[[nodiscard]] std::vector arrangedChildren(Value const& stored, + std::span declared) { + auto const isDeclared = [declared](std::string const& childId) { + return std::ranges::find(declared, childId, &DocNode::id) != declared.end(); + }; + std::vector out; + std::set> placed; + if (ValueList const* const entries = stored.asList()) { + for (Value const& entry : *entries) { + Value const* const named = entry.field("id"); + std::string const* const name = named == nullptr ? nullptr : named->asString(); + if (name == nullptr || !isDeclared(*name) || !placed.insert(*name).second) { + continue; + } + Value const* const hidden = entry.field("hidden"); + bool const* const flag = hidden == nullptr ? nullptr : hidden->asBool(); + out.push_back(ArrangedChild{.id = *name, .hidden = flag != nullptr && *flag}); + } + } + for (DocNode const* const child : declared) { + if (!placed.contains(child->id)) { + out.push_back(ArrangedChild{.id = child->id}); + } + } + return out; +} + +/// @brief The ids of the children an `arrange` choice shows, in its order (`arrangedChildren`, without the hidden). +/// @param stored The point's current choice. +/// @param declared The container's children, in document order. +/// @return The ids to show, in order. +[[nodiscard]] std::vector arrangedOrder(Value const& stored, std::span declared) { + std::vector order; + for (ArrangedChild const& child : arrangedChildren(stored, declared)) { + if (!child.hidden) { + order.emplace_back(child.id); + } + } + return order; +} + +/// @brief An arrangement as the choice an `arrange` point stores. +/// @param children Every child, in order. +/// @return `[{"id", "hidden"}, …]`. +[[nodiscard]] Value arrangementValue(std::vector const& children) { + ValueList entries; + entries.reserve(children.size()); + for (ArrangedChild const& child : children) { + entries.emplace_back(ValueRecord{{"id", Value{child.id}}, {"hidden", Value{child.hidden}}}); + } + return Value{std::move(entries)}; +} + +/// @brief The element of a document tree with @p elementId. +/// @param node The subtree. +/// @param elementId The element's id. +/// @return The element, or `nullptr` when the subtree has none with that id. +// NOLINTNEXTLINE(misc-no-recursion): one level per level of the document tree. +[[nodiscard]] DocNode const* elementNode(DocNode const& node, std::string_view elementId) { + if (node.id == elementId) { + return &node; + } + for (auto const* const groups : {&node.children, &node.parts}) { + for (auto const& [slot, nodes] : *groups) { + static_cast(slot); + for (DocNodePtr const& child : nodes) { + if (DocNode const* const found = elementNode(*child, elementId)) { + return found; + } + } + } + } + return nullptr; +} + +} // namespace + +std::string ScreenCore::arrangedBy(std::string const& elementId) const { + if (elementId.empty()) { + return {}; + } + for (auto const& [name, point] : _doc->customize) { + if (point.kind == "arrange" && point.of == elementId) { + return name; + } + } + return {}; +} + +// A keyed list over the children's ids rather than a stack, so a new choice moves the shown widgets, keeping their +// state and focus, and mounts or unmounts only what it shows or hides. A child is lowered in the container's own +// scope: arranging changes where it is, not what it reads. +Node ScreenCore::lowerArranged(DocNode const& node, LowerCtx const& ctx, ElementState* element, + std::string const& point, Axis axis, int gap) { + std::vector declared; + for (DocNodePtr const& child : node.nodes("children")) { + declared.push_back(child.get()); + } + auto order = [this, point, declared] { return arrangedOrder(prefs.get().at(point), declared); }; + auto key = [](Value const& childId) { return keyOf(childId); }; + LowerCtx childCtx = ctx; + childCtx.listGap = axis == Axis::Vertical ? gap : 0; + auto view = [this, childCtx, declared](reactive::Signal const& row) -> Node { + // The order lists only declared ids, so the lookup always finds the child. + auto const found = std::ranges::find(declared, textOf(row.peek(), session.formatting()), &DocNode::id); + return lower(**found, childCtx); + }; + ForEach spec{ + .model = std::make_shared const>(std::move(order), std::move(key), std::move(view)), + .axis = axis, + .gap = gap, + }; + commonOf(node, ctx, element, spec.common); + return makeNode(std::move(spec)); +} + +// One row per child of the arranged container, hidden ones included: a checkbox shows or hides it, and two buttons +// move it a place. Each edit stores the whole arrangement, so the stored list always names every child. +Node ScreenCore::lowerArrangeEditor(DocNode const& node, LowerCtx const& ctx, std::string const& point, + CustomizePoint const& spec, std::function const& choose) { + // The loader checked that `of` names a column or row of this screen. + DocNode const* const container = elementNode(*_doc->view, spec.of); + std::vector declared; + for (DocNodePtr const& child : container->nodes("children")) { + declared.push_back(child.get()); + } + auto const current = [this, point, declared] { return arrangedChildren(prefs.get().at(point), declared); }; + auto const place = [current](std::string const& childId) { + auto const children = current(); + return static_cast(std::ranges::find(children, childId, &ArrangedChild::id) - children.begin()); + }; + // Applies an edit to the arrangement as it stands, read untracked: the edit is a transition, not a binding. + auto const edit = [this, current, choose](std::string const& childId, auto const& change) { + auto children = runtime().untracked(current); + auto const found = std::ranges::find(children, childId, &ArrangedChild::id); + change(children, static_cast(found - children.begin())); + choose(arrangementValue(children)); + }; + auto rows = [current] { + std::vector ids; + for (ArrangedChild const& child : current()) { + ids.emplace_back(child.id); + } + return ids; + }; + auto key = [](Value const& childId) { return keyOf(childId); }; + auto view = [this, current, place, edit](reactive::Signal const& row) -> Node { + std::string const childId = textOf(row.peek(), session.formatting()); + Checkbox shown{.label = childId}; + shown.checked = slotProp([current, childId] { + auto const children = current(); + return !std::ranges::find(children, childId, &ArrangedChild::id)->hidden; + }); + shown.onToggle = [edit, childId](bool checked) { + edit(childId, [checked](std::vector& children, std::size_t index) { + children.at(index).hidden = !checked; + }); + }; + Button moveUp{.label = std::string{"\xE2\x86\x91"}}; + moveUp.onClick = [edit, childId] { + // Clamped rather than refused: at the edge the child swaps with itself, which stores the same order. + edit(childId, [](std::vector& children, std::size_t index) { + std::swap(children.at(index), children.at(std::max(index, std::size_t{1}) - 1)); + }); + }; + moveUp.common.enabled = slotProp([place, childId] { return place(childId) > 0; }); + moveUp.common.a11y.name = "Move " + childId + " up"; + moveUp.common.testId = "arrange-up-" + childId; + Button moveDown{.label = std::string{"\xE2\x86\x93"}}; + moveDown.onClick = [edit, childId] { + edit(childId, [](std::vector& children, std::size_t index) { + std::swap(children.at(index), children.at(std::min(index + 1, children.size() - 1))); + }); + }; + moveDown.common.enabled = + slotProp([current, place, childId] { return place(childId) + 1 < current().size(); }); + moveDown.common.a11y.name = "Move " + childId + " down"; + moveDown.common.testId = "arrange-down-" + childId; + shown.common.testId = "arrange-shown-" + childId; + return ui::row(Row{ + .children = + { + ui::checkbox(std::move(shown)), + ui::button(std::move(moveUp)), + ui::button(std::move(moveDown)), + }, + .gap = 1, + }); + }; + ForEach editor{ + .model = std::make_shared const>(std::move(rows), std::move(key), std::move(view)), + }; + commonOf(node, ctx, nullptr, editor.common); + return makeNode(std::move(editor)); +} + +Node ScreenCore::lowerCustomize(DocNode const& node, LowerCtx const& ctx) { + std::string const point{node.name("point")}; + // A loaded document's customize node names a declared point, and every point has a choice in `prefs`. + CustomizePoint const& spec = _doc->customize.at(point); + auto const choose = [this, point](Value value) { + session.asUser([&] { + ValueRecord next = prefs.peek(); + next.insert_or_assign(point, value); + prefs.set(std::move(next)); + }); + if (host != nullptr) { + host->preferenceChanged(_doc->id, point, value); + } + }; + if (spec.kind == "arrange") { + return lowerArrangeEditor(node, ctx, point, spec, choose); + } + if (spec.kind == "choice") { + Select select; + std::vector options; + options.reserve(spec.options.size()); + for (std::string const& option : spec.options) { + options.push_back(SelectOption{.key = Key{option}, .label = option}); + } + select.options = std::move(options); + select.selected = slotProp>([this, point] -> std::optional { + Value const& chosen = prefs.get().at(point); + return chosen.isNull() ? std::nullopt : std::optional{keyOf(chosen)}; + }); + select.onSelect = [choose](Key const& key) { choose(valueOfKey(key)); }; + commonOf(node, ctx, nullptr, select.common); + return ui::select(std::move(select)); + } + if (spec.kind == "value" && (spec.type.kind == TypeKind::String || spec.type.isAny())) { + TextInput input; + input.value = + slotProp([this, point] { return textOf(prefs.get().at(point), session.formatting()); }); + input.onChange = [choose](std::string text) { choose(Value{std::move(text)}); }; + commonOf(node, ctx, nullptr, input.common); + return ui::textInput(std::move(input)); + } + Text placeholder{.text = point, .role = TextRole::Muted}; + commonOf(node, ctx, nullptr, placeholder.common); + return ui::text(std::move(placeholder)); +} + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_collections.cpp b/src/ui/interpreter_collections.cpp new file mode 100644 index 000000000..01bb3fefa --- /dev/null +++ b/src/ui/interpreter_collections.cpp @@ -0,0 +1,964 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Tables over a document's collections and rows. + +#include "interpreter_grid_detail.hpp" + +namespace morph::ui::detail { + +[[nodiscard]] Node besideDialogs(Common& placed, Node dialogs, std::function const& table) { + if (dialogs == nullptr) { + return table(); + } + std::vector beside; + beside.push_back(std::move(dialogs)); + return besideTable(placed, std::move(beside), table); +} + +void markFilterable(TableConfig const& config, std::vector& columns, TableOptions const& options) { + if (!options.onFilter || !config.filterTarget) { + return; + } + for (std::size_t at = 0; at < columns.size() && at < config.columns.size(); ++at) { + columns.at(at).filterable = config.filterTarget(config.columns.at(at).id).has_value(); + } +} + +namespace { + +/// The rows a collection's table shows its mounts: its engine's, every change of the view told to the mount and +/// then to the table, whose status line and release read the engine after it. +class HeardRows final : public TableRows { +public: + HeardRows(std::shared_ptr engine, std::function heard) + : _engine{std::move(engine)}, _heard{std::move(heard)} { + _engine->onChange([this](table::ViewChange const& change) { + if (_handler) { + _handler(change); + } + _heard(); + }); + } + + HeardRows(HeardRows const&) = delete; + HeardRows& operator=(HeardRows const&) = delete; + HeardRows(HeardRows&&) = delete; + HeardRows& operator=(HeardRows&&) = delete; + ~HeardRows() override { _engine->onChange({}); } + + [[nodiscard]] TableTotal total() const override { return _engine->total(); } + [[nodiscard]] std::optional row(std::int64_t index) const override { return _engine->row(index); } + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override { + return _engine->unloadedLevels(index); + } + void visible(std::int64_t first, std::int64_t count, std::span columns) override { + _engine->visible(first, count, columns); + } + async::Completion, table::TableError>> keysOf( + std::int64_t first, std::int64_t count) override { + return _engine->keysOf(first, count); + } + void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) override { + _engine->locateRow(std::move(key), std::move(stop), std::move(done)); + } + async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) override { + return _engine->fetchRows(std::move(keys), std::move(columns)); + } + std::expected setSort(SortChain sort) override { + return _engine->setSort(std::move(sort)); + } + std::expected setFilter(table::FilterSpec filter) override { + return _engine->setFilter(std::move(filter)); + } + async::Completion> distinctValues( + table::DistinctRequest request) override { + return _engine->distinctValues(std::move(request)); + } + [[nodiscard]] TableCountsView counts() const override { return _engine->counts(); } + void onChange(std::function handler) override { _handler = std::move(handler); } + [[nodiscard]] RowStates& states() override { return _engine->states(); } + [[nodiscard]] RowStates const& states() const override { return _engine->states(); } + void moveKey(table::RowId const& from, table::RowId const& target) override { _engine->moveKey(from, target); } + +private: + std::shared_ptr _engine; + std::function _heard; + std::function _handler; +}; + +} // namespace + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): builds a rows table: the engine, the columns, the sort, the filter and the state wiring in order, each taking the engine and config before +std::unique_ptr ScreenCore::makeRowsTable(ElementState& element, std::shared_ptr bindings, + bool persisted) { + DocNode const& node = *element.node; + RtScope& scope = *element.scope; + auto made = std::make_unique(runtime()); + RowsTable& table = *made; + table.core = this; + table.element = &element; + table.node = &node; + table.where = &scope; + table.bindings = bindings; + if (node.flags.contains("status")) { + table.status = node.flag("status"); + } + for (DocNodePtr const& part : node.partList("columns")) { + ValueColumn column{.id = part->id, .kind = columnKindNamed(part->name("kind")), .sortBy = {}}; + if (ExprPtr const sortBy = part->prop("sortBy")) { + column.sortBy = [&scope, bindings, sortBy](Value const& row) { + return evaluate(*sortBy, ScopeEnv{scope, bindings.get(), &row}); + }; + } + table.columns.push_back(std::move(column)); + } + table.keyOfRow = [&scope, bindings, keyExpr = node.prop("key")](Value const& row) -> Key { + if (!keyExpr) { + Value const rowKey = rowId(row); + return keyOf(rowKey.isNull() ? row : rowKey); + } + return keyOf(evaluate(*keyExpr, ScopeEnv{scope, bindings.get(), &row})); + }; + auto const groups = node.partList("group"); + ExprPtr const delta = groups.empty() ? nullptr : groups.front()->prop("by"); + auto const byOf = [&scope, bindings, delta](Value const& row) { + return evaluate(*delta, ScopeEnv{scope, bindings.get(), &row}); + }; + if (delta) { + table.grouped = true; + table.byOf = byOf; + } + table.units = scope.formatting().units; + table.elementOwn = persisted; + // The columns its layout arranges, in the order the lowering gives them: the derived `columns`, then the parts. + // A column with no id cannot be named by a stored layout: it is named by its place, and locked there. + TableConfig& config = table.config; + config.element = &element; + auto const [allowed, menus] = configurableOf(node); + config.allowed = allowed; + config.menus = menus; + runtime().untracked([&] { + FormatContext const& format = scope.formatting(); + auto const add = [&config](std::string columnId, std::string label, bool locked, bool sortable, + table::ColumnKind kind) { + if (columnId.empty()) { + columnId = "#" + std::to_string(config.columns.size()); + locked = true; + } + config.columns.push_back( + LayoutColumn{.id = std::move(columnId), .label = std::move(label), .locked = locked, .kind = kind}); + config.sortable.push_back(sortable); + }; + if (ExprPtr const derived = node.prop("columns")) { + Value const list = evalIn(scope, bindings.get(), derived); + if (ValueList const* const items = list.asList()) { + for (Value const& item : *items) { + Value const* const field = item.field("id"); + Value const* const label = item.field("label"); + std::string columnId = field == nullptr ? std::string{} : textOf(*field, format); + std::string text = label != nullptr ? textOf(*label, format) : columnId; + add(std::move(columnId), std::move(text), false, false, table::ColumnKind::Text); + } + } + } + for (DocNodePtr const& part : node.partList("columns")) { + ExprPtr const label = part->prop("label"); + add(part->id, label ? textOf(evalIn(scope, bindings.get(), label), format) : part->id, + part->flag("locked"), part->flag("sortable"), + columnKindNamed(part->name("kind")).value_or(table::ColumnKind::Text)); + } + }); + std::size_t sortBound = 8; + if (ExprPtr const bound = node.prop("maxSortKeys"); bound && bound->kind == ExprKind::Literal) { + if (std::int64_t const* const keys = bound->literal.asInt(); keys != nullptr && *keys >= 1) { + sortBound = static_cast(*keys); + } + } + config.maxSortKeys = [sortBound] { return sortBound; }; + // The groups the node declares, read once: their ids, labels and columns are literals the loader checked. + for (DocNodePtr const& part : node.partList("groups")) { + table::ColumnGroupInfo group{.id = part->id, .label = part->id, .columns = {}}; + if (ExprPtr const label = part->prop("label")) { + group.label = + runtime().untracked([&] { return textOf(evalIn(scope, bindings.get(), label), scope.formatting()); }); + } + if (ExprPtr const members = part->prop("columns"); members && members->kind == ExprKind::Literal) { + if (ValueList const* const ids = members->literal.asList()) { + for (Value const& columnId : *ids) { + if (std::string const* const name = columnId.asString()) { + group.columns.push_back(*name); + } + } + } + } + table.groups.push_back(std::move(group)); + } + // The filters the user set from the header: the engine's, held here, and the columns they read kept in use. + config.filters = [&table] { + static_cast(table.version.get()); + return table.filter; + }; + config.setFilters = [this, &table](table::FilterSpec const& filter) { + useColumns(table, usedColumns(table, table.sort, filter)); + if (auto const set = table.engine->setFilter(filter); !set) { + useColumns(table, usedColumns(table, table.sort, table.filter)); + rowsTableMessage(table, "The filter is refused: " + set.error().message); + return false; + } + table.filter = filter; + table.bump(); + return true; + }; + config.rows = [&table]() -> TableRows* { return table.engine.get(); }; + config.declaredGroups = [&table] { return table.groups; }; + config.listing = [&table](std::vector const& columns) { + table.listedColumns = columns; + useColumns(table, usedColumns(table, table.sort, table.filter)); + }; + config.message = [this, &table](std::string text) { rowsTableMessage(table, std::move(text)); }; + config.touch = [this, &table] { + table.touched = true; + rowsTableMessage(table, {}); + }; + config.save = [&table](table::StateDocument const& document, StateParts parts) { + if (table.stateKey) { + table.states->changed(*table.stateKey, document, parts); + } + }; + // What a stored state or a saved view is fitted to: the node's column parts, of the kinds their cells infer. + config.description = [&table]() -> std::optional { + DocNode const& declared = *table.node; + table::TableDescription description; + description.id = declared.id; + std::span const infos = table.source->columns(); + auto const parts = declared.partList("columns"); + for (std::size_t at = 0; at < parts.size() && at < infos.size(); ++at) { + table::TableColumn column; + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `at` runs below `parts.size()`, and `infos` was built in step with `parts` + column.info = infos[at]; + column.label = parts[at]->id; + column.sortable = parts[at]->flag("sortable"); + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + column.filterable = true; + description.columns.push_back(std::move(column)); + } + description.groups = table.groups; + return description; + }; + // The columns a state or a view reads are put in use beside those in use now; the gestures that apply it put + // exactly the columns they read in use after. + config.prepare = [&table](table::StateDocument const& document) { + std::vector next = table.used; + for (std::string& columnId : + usedColumns(table, document.sort.value_or(SortChain{}), document.filters.value_or(table::FilterSpec{}))) { + if (!std::ranges::contains(next, columnId)) { + next.push_back(std::move(columnId)); + } + } + useColumns(table, std::move(next)); + }; + // A bound layout is controlled, as a bound sort is: any expression but a literal `null` binds it. + if (ExprPtr const layout = node.prop("layout"); + layout && (layout->kind != ExprKind::Literal || !layout->literal.isNull())) { + config.bound = + &scope.nodes.computed([&scope, bindings, layout] { return evalIn(scope, bindings.get(), layout); }); + } + // Shows the page of @p view: each group's heading entry before the first of its rows the page holds, and the + // engine's own operations when the page is the whole ungrouped view and they made it, a reset otherwise. + auto const show = [&table](TableView const& view, table::ViewChange const* change) { + std::vector entries; + entries.reserve(view.last - view.first); + table::Engine const& engine = table.engine->engine(); + for (std::size_t index = view.first; index < view.last; ++index) { + if (!view.runOf.empty() && (index == view.first || view.runOf.at(index) != view.runOf.at(index - 1))) { + Value const& heading = view.runs.at(view.runOf.at(index)); + Value const* const key = heading.field(kGroupHeadingField); + entries.push_back(PageRows::Entry{ + .key = + table::RowId{key != nullptr && key->asString() != nullptr ? *key->asString() : std::string{}}, + .row = heading}); + } + entries.push_back(PageRows::Entry{.key = engine.rowIdAt(index), .row = view.rows.at(index)}); + } + bool const whole = view.runOf.empty() && view.first == 0 && view.last == view.rows.size(); + table::ViewChange reset; + reset.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}); + bool const passed = whole && change != nullptr && !change->ops.empty(); + table.shown = + RowsTable::Shown{.version = table.version.peek(), .first = view.first, .last = view.last, .any = true}; + table.rows->show(std::move(entries), passed ? *change : reset); + }; + table.showPage = show; + table.heard = [this, &table](table::ViewChange const& change) { + table.bump(); + if (table.engine->restoring()) { + // The page stays empty while the rows are held back; the mount draws the engine's rows as placeholders. + // NOLINTNEXTLINE(readability-ambiguous-smartptr-reset-call): `reset()` here is the TableRows interface's own, which empties the page; it is not the smart pointer's + table.rows->reset(); + } else { + // Shown now, from the view the change made, so the change reaches the mount as it is. + runtime().untracked([&] { table.showPage(table.view->get(), &change); }); + } + rowsTableChanged(table); + }; + startRowsEngine(table, runtime()); + if (persisted) { + std::string qualifier = _doc->id; + bool persists = true; + if (ExprPtr const persist = node.prop("persist"); persist && persist->kind == ExprKind::Literal) { + if (bool const* const flag = persist->literal.asBool()) { + persists = *flag; + } else if (std::string const* const name = persist->literal.asString()) { + qualifier = *name; + } + } + table.states = session.tableStates(); + // A table with no `id` has no key to keep its arrangement under; the loader refuses a `persist` it writes. + if (persists && table.states != nullptr && !node.id.empty()) { + table.stateKey = table::TableStateKey{.application = session.options().application, + .model = {}, + .table = node.id, + .qualifier = std::move(qualifier), + .part = "state"}; + } + } + table.view = + std::make_unique>(runtime(), [this, &table] { return tableView(table); }); + // The page the mount shows again when the page moves, or the view changed under it other than through the + // engine (the rows held back, `rows` with no change of the engine's view); a page the engine's change showed is + // not shown twice. + table.effects.push_back(std::make_unique(runtime(), [this, &table] { + TableView const& shown = table.view->get(); + runtime().untracked([&] { + if (table.shown.any && table.shown.version == table.version.peek() && table.shown.first == shown.first && + table.shown.last == shown.last) { + return; + } + table.showPage(shown, nullptr); + }); + })); + if (table.stateKey) { + table.waiting = true; + table.listed = true; + modelTables.push_back(&element); + table.engine->setRestoring(true); + } + // The rows, matched by key: a changed row is repaired, not sorted again. A list over the client's bound is + // said once, for as long as the table lives. + std::size_t const parts = node.partList("columns").size(); + table.effects.push_back(std::make_unique( + runtime(), [this, &table, &scope, bindings, rowsExpr = node.prop("rows"), parts] { + Value const value = evalIn(scope, bindings.get(), rowsExpr); + runtime().untracked([&] { + ValueList rows; + if (ValueList const* const items = value.asList()) { + rows = *items; + } + // A quantity in a unit the screen's table does not list is its own canonical unit: the source and + // the engine are made again over a registry that has it. + bool brought = false; + for (Value const& row : rows) { + ValueRecord const* const fields = row.asRecord(); + if (fields == nullptr) { + continue; + } + for (auto const& [name, field] : *fields) { + static_cast(name); + if (auto const measure = detail::measureOf(field); + measure && !table.units.contains(*measure->unit) && + table.unitsSeen.insert(*measure->unit).second) { + brought = true; + } + } + } + if (brought) { + startRowsEngine(table, runtime()); + } + if (!table.boundReported && (rows.size() > kClientRows || rows.size() * parts > kClientCells)) { + table.boundReported = true; + std::string const& columnId = table.node->id; + report(table.node->path, "table " + (columnId.empty() ? table.node->path : columnId) + " holds " + + groupedCount(rows.size()) + + " rows; a table over rows is ordered on the client up to " + + groupedCount(kClientRows) + " rows or " + groupedCount(kClientCells) + + " cells — serve it as a model's table"); + } + table.source->assign(std::move(rows)); + }); + })); + // The sort the table shows: the bound one, or the table's own, which a header click and a stored state set. + table.effects.push_back(std::make_unique(runtime(), [this, &table, &element] { + Value const sort = tableSort(element); + runtime().untracked([&] { sortRowsTable(table, sort); }); + })); + // The source reads `by` untracked; what `by` reads besides the row regroups the rows when it changes. + if (delta) { + table.effects.push_back(std::make_unique( + runtime(), [this, &table, &scope, bindings, byOf, rowsExpr = node.prop("rows"), + first = std::make_shared(true)] { + Value const list = runtime().untracked([&] { return evalIn(scope, bindings.get(), rowsExpr); }); + if (ValueList const* const items = list.asList()) { + for (Value const& row : *items) { + static_cast(byOf(row)); + } + } + if (std::exchange(*first, false)) { + return; + } + runtime().untracked([&] { table.source->setGroup(byOf, scope.formatting().units); }); + })); + } + if (!table.stateKey) { + return made; + } + // The rows wait for the stored state, at most `tableStateTimeout`; a state that comes later is applied unless + // the user changed the table meanwhile. + if (reactive::Scheduler* const scheduler = session.options().scheduler) { + table.loadTimer = scheduler->after(session.options().tableStateTimeout, + table.scope.token().guard([&table] { table.release(); })); + } + table.views = std::make_unique(*table.states, *table.stateKey, runtime().owner()); + table.config.views = table.views.get(); + loadStateAndViews(*table.states, *table.stateKey, *table.views, table.scope, + [this, &table](std::optional const& json, std::string const& failure) { + storedRowsState(table, json, failure); + }); + return made; +} + +void ScreenCore::sortRowsTable(RowsTable& table, Value const& sort) { + DocNode const& node = *table.node; + std::optional> const keys = sortKeysOf(node, sort); + SortChain chain; + if (!keys) { + report( + pointerAppend(node.path, "sort"), + "sort is " + canonicalJson(sort) + + R"(; a table's sort is a list of {"column": , "direction": "asc" or "desc"})"); + } else { + for (SortKey const& key : *keys) { + chain.push_back(table::SortKey{ + .column = key.column->id, + .dir = key.descending ? table::SortDirection::Descending : table::SortDirection::Ascending}); + } + } + // The columns the new keys read are in use before the old ones leave, so a column both read keeps its cells. + useColumns(table, usedColumns(table, chain, table.filter)); + SortChain ordered; + if (table.grouped) { + ordered.push_back( + table::SortKey{.column = std::string{kGroupRunColumn}, .dir = table::SortDirection::Ascending}); + } + ordered.insert(ordered.end(), chain.begin(), chain.end()); + if (auto const set = table.engine->setSort(std::move(ordered)); !set) { + report(pointerAppend(node.path, "sort"), "the sort is refused: " + set.error().message); + return; + } + table.sort = std::move(chain); + rowsTableChanged(table); +} + +void ScreenCore::rowsTableChanged(RowsTable& table) { + if (!table.invalidReported) { + for (table::SortKey const& key : table.sort) { + if (table.source->invalidCells(key.column) == 0) { + continue; + } + table.invalidReported = true; + report(pointerAppend(table.node->path, "sort"), + "a value of the column `" + key.column + + "` is not of the column's kind; it sorts last, in either direction"); + break; + } + } + if (table.releasing && !table.engine->engine().pending()) { + table.releasing = false; + table.release(); + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): applies a stored state: layout, sort, filters and groups each fit to the description and report their own refusal, in that order +void ScreenCore::storedRowsState(RowsTable& table, std::optional const& json, + std::string const& failure) { + DocNode const& node = *table.node; + ElementState& element = *table.element; + bool const late = !table.waiting; + if (!failure.empty()) { + report(node.path, "the stored state of table `" + node.id + "` could not be loaded: " + failure); + table.release(); + return; + } + std::optional stored; + if (json) { + auto read = table::readState(*json); + if (!read) { + report(node.path, "the stored state of table `" + node.id + "` is not used: " + read.error()); + table.release(); + return; + } + stored = std::move(*read); + } + // The default view stands in for a state never stored, and its sort and filters for the stored ones when the + // user starts from it. + std::optional start = + table.views != nullptr ? stateAtMount(std::move(stored), table.views->own()) : std::move(stored); + if (!start) { + table.release(); + return; + } + if (late && table.touched) { + return; + } + // Fitted to what the node declares: its column parts, of the kinds their cells infer once they are in use. + table.config.prepare(*start); + table::FitReport fitted; + table::StateDocument const document = + table::fitState(std::move(*start), table.config.description().value_or(table::TableDescription{}), fitted); + // A table started from the default view, with nothing stored, holds it as its state: the next change saves on + // top of it rather than over nothing. + if (!json && table.states != nullptr && table.stateKey) { + table.states->start(*table.stateKey, document); + } + if (element.sortBound == nullptr && document.sort) { + element.sort.set(sortValueOf(*document.sort)); + } + // The filters go to the engine in a task of their own: it takes in the kinds of the columns just put in use when + // it flushes the change that put them there, and compiles a filter against the kinds it has taken in. + if (document.filters && !document.filters->empty()) { + runtime().owner().post(table.scope.token().guard([&table, filters = *document.filters] { + useColumns(table, usedColumns(table, table.sort, filters)); + if (table.engine->setFilter(filters)) { + table.filter = filters; + table.bump(); + } else { + useColumns(table, usedColumns(table, table.sort, table.filter)); + } + })); + } + // A bound layout is the document's: the stored one is neither applied nor saved over it. + if (table.config.bound == nullptr && document.layout) { + table.config.held = *document.layout; + table.config.version.set(table.config.version.peek() + 1); + } + if (document.view) { + table.config.savedView = document.view; + table.config.viewShared = false; + } + tablePoints(element); + if (!late) { + // The rows come through once the engine's view is in the stored order: after the work the new sort posted. + bool const timed = session.options().scheduler != nullptr; + runtime().owner().post(table.scope.token().guard([&table, timed] { + if (!table.waiting) { + return; + } + if (table.engine->engine().pending() && timed) { + table.releasing = true; + return; + } + table.release(); + })); + } +} + +namespace { + +/// @brief The text a collection addresses a row by: an integer key's digits, a text key as it is. +/// @param key The row's key, as the engine keys it. +/// @return The text. +[[nodiscard]] std::string collectionKeyText(table::RowId const& key) { + if (std::int64_t const* const whole = std::get_if(&key)) { + return std::to_string(*whole); + } + return std::get(key); +} + +/// @brief The member of a collection row's record that holds its key text; a view document's field never begins +/// with U+001F. +inline constexpr std::string_view kCollectionKeyField = "\x1Fkey"; + +/// @brief Where a collection's rows are, by key, for the records its engine builds: made again from the session's +/// rows whenever the source's current snapshot changes. That snapshot is held, so no later one can take its +/// address while the index is kept for it. +struct CollectionRecords { + std::shared_ptr snapshot; + std::unordered_map at; +}; + +} // namespace + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): wires a collection's table to its model: rows, state, runs and actions in the order each needs the one before +void ScreenCore::wireCollectionTable(ElementState& element, std::string modelType) { + forms::CollectionSession& collection = *element.collection; + element.rowsTable = std::make_unique(runtime()); + RowsTable& table = *element.rowsTable; + table.core = this; + table.element = &element; + table.node = element.node; + table.where = &*element.scope; + // Every column of the view document is laid out, those it hides hidden, and every one sorts and filters. + TableConfig& config = table.config; + config.element = &element; + for (forms::CollectionColumn const& column : collection.model().columns()) { + config.columns.push_back( + LayoutColumn{.id = column.field, .label = column.label, .locked = false, .kind = column.kind}); + config.sortable.push_back(true); + if (column.hidden) { + config.declaredHidden.push_back(column.field); + } + } + config.maxSortKeys = [] { return std::size_t{8}; }; + config.filters = [&table] { + static_cast(table.version.get()); + return table.filter; + }; + config.setFilters = [this, &table](table::FilterSpec const& filter) { + if (auto const set = table.engine->setFilter(filter); !set) { + rowsTableMessage(table, "The filter is refused: " + set.error().message); + return false; + } + table.filter = filter; + table.bump(); + return true; + }; + config.rows = [&table]() -> TableRows* { return table.engine.get(); }; + // The session's source holds every cell of every column: a values list puts none in use. + config.listing = [](std::vector const& columns) { static_cast(columns); }; + config.message = [this, &table](std::string text) { rowsTableMessage(table, std::move(text)); }; + config.touch = [this, &table] { + table.touched = true; + rowsTableMessage(table, {}); + }; + config.save = [&table](table::StateDocument const& document, StateParts parts) { + if (table.stateKey) { + table.states->changed(*table.stateKey, document, parts); + } + }; + // What a stored state or a saved view is fitted to: the view document's columns, each of which sorts and filters. + config.description = [&collection]() -> std::optional { + table::TableDescription description; + description.id = std::string{collection.model().query()}; + for (table::ColumnInfo const& info : collection.source()->columns()) { + table::TableColumn column; + column.info = info; + column.label = info.id; + column.sortable = true; + column.filterable = true; + description.columns.push_back(std::move(column)); + } + return description; + }; + // A row's record is its key text and every column's cell as the session formats it, read from the row of that + // key: the engine may read a snapshot older than the session's rows, and a row it no longer has reads empty. + auto const records = std::make_shared(); + RecordOf recordOf = [reactiveRuntime = &runtime(), session = &collection, records]( + table::RowSnapshot const& snapshot, std::size_t sourceRow) { + table::RowId key = snapshot.rowId(sourceRow); + ValueRecord record; + record.insert_or_assign(std::string{kCollectionKeyField}, Value{collectionKeyText(key)}); + reactiveRuntime->untracked([&] { + std::vector const& rows = session->rows(); + // The index is of the session's rows, whichever snapshot the engine reads: it is made again when the + // source's current snapshot changes, which the session's rows changing makes it do. + if (std::shared_ptr current = session->source()->snapshot(); + records->snapshot != current) { + records->snapshot = std::move(current); + records->at.clear(); + for (std::size_t at = 0; at < rows.size(); ++at) { + records->at.emplace(rows.at(at).id, at); + } + } + auto const found = records->at.find(key); + if (found == records->at.end() || found->second >= rows.size() || rows.at(found->second).id != key) { + return; + } + auto const dom = forms::detail::engine::parseJson(rows.at(found->second).json); + if (!dom) { + return; + } + for (forms::CollectionColumn const& column : session->model().columns()) { + record.insert_or_assign(column.field, Value{forms::detail::engine::cellText(*dom, column)}); + } + }); + return RowRecord{.key = std::move(key), .row = Value{std::move(record)}}; + }; + // Text orders as it does in every other table of the screen. + table::EngineOptions options; + options.owner = &runtime().owner(); + options.worker = nullptr; + options.frameBudget = std::chrono::milliseconds{4}; + options.services.collator = std::make_shared(); + table.engine = std::make_shared(collection.source(), std::move(recordOf), std::move(options)); + element.tableRows = std::make_shared(table.engine, [&table] { + table.bump(); + if (table.releasing && !table.engine->engine().pending()) { + table.releasing = false; + table.release(); + } + }); + // The sort the table shows: its own, which a header click and a stored state set. + table.effects.push_back(std::make_unique(runtime(), [this, &table, &element] { + Value const sort = tableSort(element); + runtime().untracked([&] { + SortChain chain; + for (table::SortKey& key : sortChainOf(sort)) { + if (std::ranges::contains(table.config.columns, key.column, &LayoutColumn::id)) { + chain.push_back(std::move(key)); + } + } + if (table.engine->setSort(chain)) { + table.sort = std::move(chain); + } + }); + })); + // Kept under the collection's action, on this screen, for the model it lists. + table.states = session.tableStates(); + if (table.states == nullptr) { + return; + } + table.stateKey = table::TableStateKey{.application = session.options().application, + .model = std::move(modelType), + .table = std::string{collection.model().query()}, + .qualifier = _doc->id, + .part = "state"}; + table.waiting = true; + table.listed = true; + modelTables.push_back(&element); + table.engine->setRestoring(true); + // The rows wait for the stored state, at most `tableStateTimeout`; a state that comes later is applied unless + // the user changed the table meanwhile. + if (reactive::Scheduler* const scheduler = session.options().scheduler) { + table.loadTimer = scheduler->after(session.options().tableStateTimeout, + table.scope.token().guard([&table] { table.release(); })); + } + table.views = std::make_unique(*table.states, *table.stateKey, runtime().owner()); + table.config.views = table.views.get(); + loadStateAndViews(*table.states, *table.stateKey, *table.views, table.scope, + [this, &table](std::optional const& json, std::string const& failure) { + storedCollectionState(table, json, failure); + }); +} + +void ScreenCore::storedCollectionState(RowsTable& table, std::optional const& json, + std::string const& failure) { + DocNode const& node = *table.node; + ElementState& element = *table.element; + std::string const action{node.name("action")}; + bool const late = !table.waiting; + if (!failure.empty()) { + report(node.path, "the stored state of collection `" + action + "` could not be loaded: " + failure); + table.release(); + return; + } + std::optional stored; + if (json) { + auto read = table::readState(*json); + if (!read) { + report(node.path, "the stored state of collection `" + action + "` is not used: " + read.error()); + table.release(); + return; + } + stored = std::move(*read); + } + // The default view stands in for a state never stored, and its sort and filters for the stored ones when the + // user starts from it. + std::optional start = + table.views != nullptr ? stateAtMount(std::move(stored), table.views->own()) : std::move(stored); + if (!start) { + table.release(); + return; + } + if (late && table.touched) { + return; + } + // Fitted to the view document's columns, each of which sorts and filters. + table::FitReport fitted; + table::StateDocument const document = + table::fitState(std::move(*start), table.config.description().value_or(table::TableDescription{}), fitted); + // A table started from the default view, with nothing stored, holds it as its state: the next change saves on + // top of it rather than over nothing. + if (!json && table.states != nullptr && table.stateKey) { + table.states->start(*table.stateKey, document); + } + if (element.sortBound == nullptr && document.sort) { + element.sort.set(sortValueOf(*document.sort)); + } + if (document.filters && !document.filters->empty() && table.engine->setFilter(*document.filters)) { + table.filter = *document.filters; + table.bump(); + } + if (document.layout) { + table.config.held = *document.layout; + table.config.version.set(table.config.version.peek() + 1); + } + if (document.view) { + table.config.savedView = document.view; + table.config.viewShared = false; + } + if (late) { + return; + } + // The rows come through once the engine's view is in the stored order: after the work the new sort posted. + bool const timed = session.options().scheduler != nullptr; + runtime().owner().post(table.scope.token().guard([&table, timed] { + if (!table.waiting) { + return; + } + if (table.engine->engine().pending() && timed) { + table.releasing = true; + return; + } + table.release(); + })); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): lowers a collection's rows table: columns, engine, selection, filters and options in document order +Node ScreenCore::lowerCollectionRows(ElementState& element, LowerCtx const& ctx, + std::function const& buttons) { + RowsTable& table = *element.rowsTable; + forms::CollectionSession& collection = *element.collection; + TableConfig& config = table.config; + // Every column of the layout, then the row's buttons, which are no column of it. + std::vector fields; + std::vector columns; + for (LayoutColumn const& column : config.columns) { + fields.push_back(column.id); + columns.push_back(TableColumn{.id = column.id, .label = column.label, .sortable = true}); + } + std::size_t const laidOut = columns.size(); + // The buttons' column is sized to its widest cell like any content column: a button's frame and padding are + // pixels, not character cells, so no count of units can say how wide a proportional font draws them. + if (buttons) { + columns.push_back(TableColumn{.label = std::string{}, .width = Sizing::content()}); + } + config.beginMount(); + config.filterTarget = [&table, &collection](std::string const& columnId) -> std::optional { + std::vector const& arranged = table.config.columns; + auto const found = std::ranges::find(arranged, columnId, &LayoutColumn::id); + std::span const infos = collection.source()->columns(); + auto const info = std::ranges::find(infos, columnId, &table::ColumnInfo::id); + if (found == arranged.end() || info == infos.end()) { + return std::nullopt; + } + FilterTarget target; + target.column = columnId; + target.label = found->label; + target.shown = table::TableColumn{.info = *info, .display = table::ColumnDisplay{}}; + target.listed = true; + return target; + }; + // A copy reads the engine's view, which holds every row, each cell as the session formats it. + config.gather = [&table](std::vector keys, std::vector const& ids, CopyDone const& done) { + CopyGathered gathered; + std::vector read; + for (std::string const& columnId : ids) { + auto const found = std::ranges::find(table.config.columns, columnId, &LayoutColumn::id); + if (found != table.config.columns.end()) { + gathered.headers.push_back(found->label); + read.push_back(columnId); + } + } + std::unordered_set wanted{keys.begin(), keys.end()}; + EngineRows const& rows = *table.engine; + std::int64_t const total = rows.total().rows; + for (std::int64_t at = 0; at < total && !wanted.empty(); ++at) { + std::optional const ref = rows.row(at); + if (!ref || wanted.erase(ref->key) == 0) { + continue; + } + CopyRow copied{.viewRow = at, .cells = {}}; + for (std::string const& columnId : read) { + Value const* const text = ref->row.field(columnId); + copied.cells.emplace_back(text != nullptr && text->asString() != nullptr ? *text->asString() + : std::string{}); + } + gathered.rows.push_back(std::move(copied)); + } + done(std::move(gathered)); + }; + // Each cell shows one row, so its test id names that row's key; the trailing cell holds the row's buttons. + TableSource source; + source.rows = element.tableRows; + source.alwaysWindowed = false; + source.rowScopedCells.assign(columns.size(), true); + source.cellView = [this, buttons, fields](std::size_t column, reactive::Signal const& row) -> Node { + Value const* const keyed = row.peek().field(kCollectionKeyField); + std::string const key = keyed != nullptr && keyed->asString() != nullptr ? *keyed->asString() : std::string{}; + if (column >= fields.size()) { + return buttons ? buttons(key) : ui::text(Text{}); + } + Text cell{.text = slotProp([&row, field = fields.at(column)] { + Value const* const text = row.get().field(field); + return text != nullptr && text->asString() != nullptr ? *text->asString() : std::string{}; + })}; + cell.common.testId = "cell_" + fields.at(column) + "_" + key; + return ui::text(std::move(cell)); + }; + // The engine keys a row by its integer key's value, the session by the key's text: the selection and the + // activation the session's options make are translated between the two. + TableOptions options = forms::detail::engine::rowsTableOptions(collection); + forms::CollectionSession const* const view = &collection; + if (options.onActivate) { + options.onActivate = [inner = std::move(options.onActivate)](Key const& key) { + inner(Key{collectionKeyText(key)}); + }; + } + if (options.onSelectionChange) { + options.onSelectionChange = [inner = std::move(options.onSelectionChange)](std::vector const& keys, + SelectionChange change) { + std::vector texts; + texts.reserve(keys.size()); + for (Key const& key : keys) { + texts.emplace_back(collectionKeyText(key)); + } + inner(texts, change); + }; + } + if (options.selection.isBound()) { + options.selection = slotProp>([read = options.selection.binding(), view] { + std::vector keys; + std::vector const& rows = view->rows(); + for (Key const& key : read()) { + std::string const* const text = std::get_if(&key); + auto const found = + text == nullptr ? rows.end() : std::ranges::find(rows, *text, &forms::CollectionRow::key); + if (found != rows.end()) { + keys.push_back(found->id); + } + } + return keys; + }); + } + // The status line takes space while it has something to say: a refusal, or what a copy did. + options.status = slotProp([&table, view, scope = ctx.scope] { + static_cast(table.version.get()); + TableStatus status; + bool const selected = + view->model().kind() == forms::CollectionKind::MasterDetail && view->openRow().has_value(); + status.counts = countsText(table.engine->counts(), selected ? 1 : 0, scope->formatting()); + status.message = table.status == false ? std::string{} : table.message.get(); + status.shown = table.status.value_or(!status.state.empty() || !status.message.empty()); + return status; + }); + Node dialogs = configureTable(config, ctx, options, nullptr); + markFilterable(config, columns, options); + // An arrangement that lists the columns it shows lists the buttons last. + if (buttons) { + // Held by pointer: the slot's closure is moved into the property, and moving a property that holds a + // `std::function` makes GCC 15 at -O3 report that function as uninitialized. + auto const inner = std::make_shared const>(std::move(options.arrangement)); + options.arrangement = slotProp([inner, laidOut] { + TableArrangement arranged = inner->evaluate(); + if (!arranged.visible.empty()) { + arranged.visible.push_back(laidOut); + } + return arranged; + }); + } + return besideDialogs(options.common, std::move(dialogs), + [&] { return ui::table(std::move(columns), std::move(source), std::move(options)); }); +} + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_components.cpp b/src/ui/interpreter_components.cpp new file mode 100644 index 000000000..8ca2bbd3e --- /dev/null +++ b/src/ui/interpreter_components.cpp @@ -0,0 +1,836 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Transfers, component properties and the value helpers lowering shares. + +#include "interpreter_detail.hpp" + +namespace morph::ui::detail { + +namespace { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a download and an upload, each settled. +/// @brief A transfer's share of its screen's pending count. +/// +/// A transfer is pending from the host accepting it to its settle: its completion carries on the command list that +/// started it, which the close protocol and save-and-close wait for. The count is taken once the host accepts, so a +/// refused transfer never counts, and a host that settles before it returns leaves nothing taken. It is given back +/// once, also when the transfer settles after its scope is gone, but not after the screen itself is gone, since the +/// count went with it. +class TransferHold { +public: + /// @brief A hold that counts nothing yet. + /// @param core The screen whose count it moves. + /// @param alive Expires with the screen. + TransferHold(ScreenCore& core, std::weak_ptr alive) : _core{&core}, _alive{std::move(alive)} {} + + /// @brief Counts the transfer, unless it has already settled. + void take() { + if (_state == State::NotTaken) { + _state = State::Taken; + _core->addPending(1); + } + } + + /// @brief Gives the count back, if one was taken and the screen is still there; the transfer counts no more. + void release() { + if (_state == State::Taken && !_alive.expired()) { + _core->addPending(-1); + } + _state = State::Released; + } + +private: + enum class State : std::uint8_t { NotTaken, Taken, Released }; + + ScreenCore* _core; + std::weak_ptr _alive; + State _state = State::NotTaken; +}; + +} // namespace + +[[nodiscard]] std::string base64Encode(std::string_view bytes) { + static constexpr std::string_view kAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::string out; + out.reserve(((bytes.size() + 2) / 3) * 4); + for (std::size_t index = 0; index < bytes.size(); index += 3) { + std::size_t const left = std::min(3, bytes.size() - index); + std::uint32_t group = 0; + for (std::size_t offset = 0; offset < 3; ++offset) { + group <<= 8U; + if (offset < left) { + group |= static_cast(bytes.at(index + offset)); + } + } + for (std::size_t digit = 0; digit < 4; ++digit) { + out.push_back(digit <= left ? kAlphabet.at((group >> (18U - (6U * digit))) & 0x3FU) : '='); + } + } + return out; +} + +[[nodiscard]] std::optional base64Decode(std::string_view text) { + while (!text.empty() && text.back() == '=') { + text.remove_suffix(1); + } + if (text.size() % 4 == 1) { + return std::nullopt; + } + auto const digitOf = [](char chr) -> int { + if (chr >= 'A' && chr <= 'Z') { + return chr - 'A'; + } + if (chr >= 'a' && chr <= 'z') { + return chr - 'a' + 26; + } + if (chr >= '0' && chr <= '9') { + return chr - '0' + 52; + } + if (chr == '+') { + return 62; + } + return chr == '/' ? 63 : -1; + }; + std::string out; + out.reserve((text.size() * 3) / 4); + std::uint32_t group = 0; + int bits = 0; + for (char const chr : text) { + int const digit = digitOf(chr); + if (digit < 0) { + return std::nullopt; + } + group = (group << 6U) | static_cast(digit); + bits += 6; + if (bits >= 8) { + bits -= 8; + out.push_back(static_cast((group >> static_cast(bits)) & 0xFFU)); + } + } + return out; +} + +[[nodiscard]] std::size_t base64Size(std::string_view text) { + while (!text.empty() && text.back() == '=') { + text.remove_suffix(1); + } + return (text.size() * 3) / 4; +} + +[[nodiscard]] std::string sizeText(std::size_t bytes) { + constexpr std::size_t kKiB = 1024; + if (bytes < kKiB) { + return std::to_string(bytes) + " bytes"; + } + bool const mebi = bytes >= kKiB * kKiB; + std::size_t const unit = mebi ? kKiB * kKiB : kKiB; + // One decimal place, rounded half up, and none when it is zero. + std::size_t const tenths = ((bytes * 10) + (unit / 2)) / unit; + std::string text = std::to_string(tenths / 10); + if (tenths % 10 != 0) { + text += "." + std::to_string(tenths % 10); + } + return text + (mebi ? " MiB" : " KiB"); +} + +[[nodiscard]] std::expected inlineBytes(Value const& value) { + if (std::string const* const text = value.asString()) { + if (std::optional bytes = base64Decode(*text)) { + return *std::move(bytes); + } + return std::unexpected(std::string{"the text is not base64"}); + } + if (ValueList const* const list = value.asList()) { + std::string bytes; + bytes.reserve(list->size()); + for (Value const& item : *list) { + std::int64_t const* const byte = item.asInt(); + if (byte == nullptr || *byte < 0 || *byte > 255) { + return std::unexpected(std::string{"a byte list holds integers 0 to 255"}); + } + bytes.push_back(static_cast(static_cast(*byte))); + } + return bytes; + } + return std::unexpected(std::string{"inline bytes are base64 text or a list of bytes"}); +} + +void ScreenCore::runTransfer(Command const& command, CommandCtx const& ctx, Done done) { + Value const file = evalIn(*ctx.scope, ctx.bindings.get(), command.value); + if (command.kind == CommandKind::Download) { + runDownload(command, ctx, file, std::move(done)); + } else { + runUpload(command, ctx, file, std::move(done)); + } +} + +void ScreenCore::runDownload(Command const& command, CommandCtx const& ctx, Value const& file, Done done) { + Value const name = evalIn(*ctx.scope, ctx.bindings.get(), command.extra); + auto const hold = std::make_shared(*this, _alive); + auto const settled = [this, weak = std::weak_ptr{ctx.scope}, target = command.target, + preview = command.option == "preview", done, + hold](std::expected const& reply) { + auto const held = weak.lock(); + if (!held) { + hold->release(); + return; + } + runtime().batch([&] { + bool const succeeded = reply.has_value(); + NameRef const* const found = succeeded && preview ? held->find(target) : nullptr; + if (found != nullptr && found->category == NameCategory::State) { + initState(*found->state->scope, *found->state); + session.noteWrite(); + found->state->value->set(*reply); + } + done(succeeded); + hold->release(); + }); + }; + if (command.bytes) { + std::optional const inlined = inlineDownload(command, ctx, file, name); + if (!inlined) { + done(false); + return; + } + if (host == nullptr || !host->saveFile(*inlined, command.option, settled)) { + unsupported(command, "`download`"); + done(false); + return; + } + hold->take(); + return; + } + if (host == nullptr || !host->download(file, command.option, name, settled)) { + unsupported(command, "`download`"); + done(false); + return; + } + hold->take(); +} + +// Inline bytes are checked before the host is asked: content over the cap, or that does not decode, never reaches it. +std::optional ScreenCore::inlineDownload( + Command const& command, CommandCtx const& ctx, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the command's `file` and `name`, in its order. + Value const& file, Value const& name) { + std::size_t const cap = session.options().maxInlineFileBytes; + std::size_t size = 0; + if (std::string const* const text = file.asString()) { + size = base64Size(*text); + } else if (ValueList const* const list = file.asList()) { + size = list->size(); + } + std::expected bytes = size > cap ? std::unexpected(std::string{}) : inlineBytes(file); + if (size > cap || (bytes && bytes->size() > cap)) { + report(command.path, "download: " + sizeText(bytes ? bytes->size() : size) + " is over the " + sizeText(cap) + + " inline cap; serve it through the file store"); + return std::nullopt; + } + if (!bytes) { + report(command.path, "download: " + bytes.error()); + return std::nullopt; + } + return InlineFile{ + .name = textOf(name, ctx.scope->formatting()), + .mediaType = command.mediaType + ? textOf(evalIn(*ctx.scope, ctx.bindings.get(), command.mediaType), ctx.scope->formatting()) + : std::string{}, + .bytes = *std::move(bytes), + }; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one branch per outcome an upload can have. +void ScreenCore::runUpload(Command const& command, CommandCtx const& ctx, Value const& file, Done done) { + RtScope const& scope = *ctx.scope; + std::weak_ptr const weak = ctx.scope; + auto const hold = std::make_shared(*this, _alive); + NameRef const* const transferName = command.transfer.empty() ? nullptr : scope.find(command.transfer); + TransferState* const transfer = + transferName != nullptr && transferName->category == NameCategory::Transfer ? transferName->transfer : nullptr; + auto const progress = [weak, transfer](Value fraction) { + if (weak.lock() && transfer != nullptr) { + transfer->progress.set(std::move(fraction)); + } + }; + // Settles with the members the mutation's body gets beside its own (the reference or the inline file), or the + // failure. + auto const settled = [this, weak, kept = detached(ctx), transfer, command = &command, done, + hold](std::expected reply) { + auto const held = weak.lock(); + if (!held) { + hold->release(); + return; + } + runtime().batch([&] { + if (transfer != nullptr) { + transfer->pending.set(false); + transfer->error.set(reply ? Value{} : Value{reply.error()}); + } + if (!reply) { + done(false); + hold->release(); + return; + } + NameRef const* const found = held->find(command->target); + // The mutation's body cannot name the reference (a body is checked where the mutation is declared), + // so the reference is added to it under `as`, `file` by default. + MutationRuntime& mutation = *found->mutation; + Value const base = evalIn(*held, kept.bindings.get(), mutation.decl().body); + ValueRecord fields = base.asRecord() == nullptr ? ValueRecord{} : *base.asRecord(); + for (auto& [member, value] : *reply) { + fields.insert_or_assign(member, std::move(value)); + } + // The run takes its own count before this one is given back, so pending never reads zero in between. + mutation.run(Value{std::move(fields)}, std::make_shared(*kept.bindings), + [done](bool succeeded, Value const&) { done(succeeded); }); + hold->release(); + }); + }; + if (host == nullptr) { + unsupported(command, "`upload`"); + done(false); + return; + } + if (transfer != nullptr) { + transfer->pending.set(true); + transfer->progress.set(Value{std::int64_t{0}}); + transfer->error.set(Value{}); + } + NameRef const* const target = scope.find(command.target); + UploadRequest request{.file = file, .modelType = {}, .action = {}}; + if (target != nullptr && target->category == NameCategory::Mutation && target->mutation != nullptr) { + request.modelType = target->mutation->typeId(); + request.action = target->mutation->decl().action; + } + std::string const member = command.binding.empty() ? std::string{"file"} : command.binding; + bool started = false; + if (command.bytes) { + std::size_t const cap = session.options().maxInlineFileBytes; + started = host->readFile( + file, cap, + [this, settled, progress, cap, member, command = &command](std::expected read) { + if (!read) { + settled(std::unexpected(read.error())); + return; + } + if (read->bytes.size() > cap) { + // The host should have refused it; the cap holds whether or not it did. + std::string why = "upload: " + sizeText(read->bytes.size()) + " is over the " + sizeText(cap) + + " inline cap; send it through the file store"; + report(command->path, why); + settled(std::unexpected(std::move(why))); + return; + } + progress(Value{std::int64_t{1}}); + ValueRecord added; + added.insert_or_assign(member, Value{base64Encode(read->bytes)}); + if (!command->nameAs.empty()) { + added.insert_or_assign(command->nameAs, Value{read->name}); + } + if (!command->typeAs.empty()) { + added.insert_or_assign(command->typeAs, Value{read->mediaType}); + } + settled(std::move(added)); + }); + } else { + started = host->uploadFor(request, progress, [settled, member](std::expected reference) { + if (!reference) { + settled(std::unexpected(reference.error())); + return; + } + ValueRecord added; + added.insert_or_assign(member, *std::move(reference)); + settled(std::move(added)); + }); + } + if (!started) { + if (transfer != nullptr) { + transfer->pending.set(false); + transfer->progress.set(Value{}); + } + unsupported(command, "`upload`"); + done(false); + return; + } + hold->take(); +} + +// --- Lowering -------------------------------------------------------------------------------------------------- + +[[nodiscard]] bool boolOf(Value const& value, FormatContext const& format) { + static_cast(format); + bool const* const flag = value.asBool(); + return flag != nullptr && *flag; +} + +[[nodiscard]] std::string stringOf(Value const& value, FormatContext const& format) { return textOf(value, format); } + +[[nodiscard]] std::string componentText(Value const& value, std::string_view type, FormatContext const& format) { + if (type == "json") { + return canonicalJson(value); + } + if (type == "int" || type == "exact") { + if (std::int64_t const* const whole = value.asInt()) { + return std::to_string(*whole); + } + // A value that cannot be rounded at its own places is written as its exact JSON, never clamped. + if (Decimal const* const number = value.asDecimal()) { + return detail::decimalText(number->value, static_cast(number->value.decimalPlaces.value)) + .value_or(canonicalJson(value)); + } + if (Quantity const* const quantity = value.asQuantity()) { + auto const text = + detail::decimalText(quantity->value, static_cast(quantity->value.decimalPlaces.value)); + return text ? *text + " " + quantity->unit : canonicalJson(value); + } + } + return textOf(value, format); +} + +[[nodiscard]] double realOf(math::Rational const& value) noexcept { + return static_cast(value.numerator) / static_cast(value.denominator); +} + +[[nodiscard]] double componentNumber(Value const& value) { + if (std::int64_t const* const whole = value.asInt()) { + return static_cast(*whole); + } + if (Decimal const* const number = value.asDecimal()) { + return realOf(number->value); + } + if (Quantity const* const quantity = value.asQuantity()) { + return realOf(quantity->value); + } + return 0.0; +} + +[[nodiscard]] Value componentPayload(std::string const& payload, Type const* type) { + std::string_view const text{payload}; + if (text.starts_with("i:")) { + std::int64_t whole = 0; + std::string_view const digits = text.substr(2); + char const* const last = std::to_address(digits.end()); + auto const [end, error] = std::from_chars(std::to_address(digits.begin()), last, whole); + if (error == std::errc{} && end == last) { + return Value{whole}; + } + } + if (text.starts_with("s:")) { + return Value{std::string{text.substr(2)}}; + } + if (auto json = parseJson(text); json && type != nullptr) { + if (auto value = valueFromJson(*json, *type)) { + return std::move(*value); + } + } + return Value{payload}; +} + +[[nodiscard]] std::int64_t intOf(Value const& value, std::int64_t fallback) { + if (std::int64_t const* const number = value.asInt()) { + return *number; + } + if (Decimal const* const number = value.asDecimal()) { + // Integer division truncates toward zero, and reads the exact value rather than one rounded to its places. + return number->value.numerator / number->value.denominator; + } + return fallback; +} + +[[nodiscard]] std::optional roleNamed(std::string_view name) { + if (name == "normal") { + return TextRole::Normal; + } + if (name == "muted") { + return TextRole::Muted; + } + if (name == "heading" || name == "title") { + return TextRole::Heading; + } + if (name == "section") { + return TextRole::Section; + } + if (name == "error") { + return TextRole::Error; + } + if (name == "success") { + return TextRole::Success; + } + if (name == "mono") { + return TextRole::Mono; + } + if (name == "display") { + return TextRole::Display; + } + if (name == "small") { + return TextRole::Small; + } + if (name == "overline") { + return TextRole::Overline; + } + if (name == "caption") { + return TextRole::Caption; + } + if (name == "label") { + return TextRole::Label; + } + if (name == "headline") { + return TextRole::Headline; + } + return std::nullopt; +} + +[[nodiscard]] TextRole roleOf(Value const& value, FormatContext const& format) { + return roleNamed(textOf(value, format)).value_or(TextRole::Normal); +} + +[[nodiscard]] Tone toneOf(Value const& value, FormatContext const& format) { + std::string const text = textOf(value, format); + if (text == "info") { + return Tone::Info; + } + if (text == "ok" || text == "success") { + return Tone::Ok; + } + if (text == "warn" || text == "warning") { + return Tone::Warn; + } + if (text == "err" || text == "error") { + return Tone::Err; + } + return Tone::Neutral; +} + +[[nodiscard]] std::optional toneNamed(Value const& value) { + if (value.isNull()) { + return Tone::Neutral; + } + static constexpr std::array, 5> kTones = { + { + {"neutral", Tone::Neutral}, + {"info", Tone::Info}, + {"ok", Tone::Ok}, + {"warn", Tone::Warn}, + {"err", Tone::Err}, + }, + }; + if (std::string const* const text = value.asString()) { + // A loop, not std::ranges::find: an array's iterator is a pointer on some standard libraries and not on + // others, so `auto` there reads differently to each. + for (auto const& [name, tone] : kTones) { + if (name == *text) { + return tone; + } + } + } + return std::nullopt; +} + +[[nodiscard]] std::vector spansOf(Value const& value, FormatContext const& format, bool& dropped, + bool* badTone) { + std::vector spans; + if (value.isNull()) { + return spans; + } + ValueList const* const runs = value.asList(); + if (runs == nullptr) { + dropped = true; + return spans; + } + auto const flag = [](Value const* field) { + bool const* const set = field != nullptr ? field->asBool() : nullptr; + return set != nullptr && *set; + }; + for (Value const& run : *runs) { + if (run.asRecord() == nullptr) { + if (run.isNull() || run.asList() != nullptr) { + dropped = true; + } else { + spans.push_back(TextSpan{.text = textOf(run, format)}); + } + continue; + } + Value const* const text = run.field("text"); + if (text == nullptr) { + dropped = true; + continue; + } + Tone tone = Tone::Neutral; + if (Value const* const named = run.field("tone")) { + if (std::optional const known = toneNamed(*named)) { + tone = *known; + } else if (badTone != nullptr) { + *badTone = true; + } + } + spans.push_back(TextSpan{ + .text = textOf(*text, format), + .strong = flag(run.field("strong")), + .mono = flag(run.field("mono")), + .tone = tone, + .action = flag(run.field("action")), + }); + } + return spans; +} + +[[nodiscard]] bool declaresNames(ScopeDecl const& scope) noexcept { + return !(scope.models.empty() && scope.state.empty() && scope.lets.empty() && scope.queries.empty() && + scope.mutations.empty() && scope.watches.empty() && scope.checks.empty()); +} + +[[nodiscard]] std::optional> splitterSizesOf(Value const& value) { + ValueList const* const items = value.asList(); + if (items == nullptr) { + return std::nullopt; + } + std::vector sizes; + sizes.reserve(items->size()); + for (Value const& item : *items) { + if (item.asInt() == nullptr && item.asDecimal() == nullptr) { + return std::nullopt; + } + sizes.push_back(static_cast(intOf(item, 0))); + } + return sizes; +} + +[[nodiscard]] Sizing sizingOf(Value const& value) { + if (Value const* const fixed = value.field("fixed")) { + return Sizing::fixed(static_cast(intOf(*fixed, 0))); + } + if (Value const* const percent = value.field("percent")) { + return Sizing::percent(static_cast(intOf(*percent, 1))); + } + if (Value const* const stretch = value.field("stretch")) { + return Sizing::stretch(static_cast(intOf(*stretch, 1))); + } + return Sizing::content(); +} + +[[nodiscard]] bool isSizing(Value const& value) { + if (std::string const* const text = value.asString()) { + return *text == "content"; + } + ValueRecord const* const record = value.asRecord(); + if (record == nullptr || record->size() != 1 || record->begin()->second.asInt() == nullptr) { + return false; + } + if (record->contains("percent")) { + std::int64_t const share = *record->begin()->second.asInt(); + return share >= 1 && share <= 100; + } + return record->contains("fixed") || record->contains("stretch"); +} + +[[nodiscard]] Align alignOf(std::string_view name) { + if (name == "start") { + return Align::Start; + } + if (name == "center") { + return Align::Center; + } + if (name == "end") { + return Align::End; + } + return Align::Stretch; +} + +[[nodiscard]] std::optional cellPlaceNamed(std::string_view name) { + if (name == "start") { + return Align::Start; + } + if (name == "center") { + return Align::Center; + } + if (name == "end") { + return Align::End; + } + return std::nullopt; +} + +[[nodiscard]] Justify justifyOf(std::string_view name) { + if (name == "center") { + return Justify::Center; + } + if (name == "end") { + return Justify::End; + } + if (name == "between") { + return Justify::Between; + } + return Justify::Start; +} + +[[nodiscard]] Axis axisOf(Value const& value) { + std::string const* const text = value.asString(); + return text != nullptr && *text == "horizontal" ? Axis::Horizontal : Axis::Vertical; +} + +[[nodiscard]] StepState stepStateOf(std::string_view name) { + if (name == "active") { + return StepState::Active; + } + if (name == "done") { + return StepState::Done; + } + return name == "failed" ? StepState::Failed : StepState::Pending; +} + +[[nodiscard]] std::vector selectOptions(Value const& options, FormatContext const& format) { + std::vector out; + if (ValueList const* const items = options.asList()) { + for (Value const& option : *items) { + Value const key = optionKey(option); + Value const* const label = option.field("label"); + out.push_back(SelectOption{.key = keyOf(key), .label = textOf(label != nullptr ? *label : key, format)}); + } + } + return out; +} + +[[nodiscard]] LayoutHints layoutHintsOf(Node const& node) { + if (!node) { + return {}; + } + return std::visit( + [](auto const& spec) -> LayoutHints { + if constexpr (requires { spec.common.layout; }) { + return spec.common.layout; + } else { + return {}; + } + }, + node->kind); +} + +[[nodiscard]] Node withWidth(Node const& node, Sizing width) { + if (!node) { + return node; + } + auto copy = std::make_shared(*node); + std::visit( + [&width](auto& spec) { + if constexpr (requires { spec.common.layout; }) { + spec.common.layout.width = width; + } + }, + copy->kind); + return copy; +} + +[[nodiscard]] Sizing holderSizing(std::span sizings) { + int weight = 0; + for (Sizing const& sizing : sizings) { + if (sizing.kind == Sizing::Kind::Stretch) { + weight = std::max(weight, sizing.amount); + } + } + return weight > 0 ? Sizing::stretch(weight) : Sizing::content(); +} + +namespace { + +/// @brief The column that holds a node list. It stretches along an axis when one of its children does, so the +/// content means what its nodes would mean written inline in the holder's parent. +/// @param children The content. +/// @param gap The spacing step between children. +/// @return The column; bounds and `alignSelf` stay unset, because they belong to a child. +[[nodiscard]] Column listColumn(std::vector children, int gap = 0) { + std::vector widths; + std::vector heights; + for (Node const& child : children) { + LayoutHints const hints = layoutHintsOf(child); + widths.push_back(hints.width); + heights.push_back(hints.height); + } + // A lone child's share of its row is the holder's, and the child fills the holder, so the share is taken once. + if (children.size() == 1 && widths.front().kind == Sizing::Kind::Percent) { + Sizing const share = widths.front(); + children.front() = withWidth(children.front(), Sizing::stretch(1)); + Column column{.children = std::move(children), .gap = gap}; + column.common.layout.width = share; + column.common.layout.height = holderSizing(heights); + return column; + } + Column column{.children = std::move(children), .gap = gap}; + column.common.layout.width = holderSizing(widths); + column.common.layout.height = holderSizing(heights); + return column; +} + +} // namespace + +[[nodiscard]] Node lazy(std::function build, LayoutHints const& hints) { + Common common; + common.layout = hints; + return ui::forEach([] { return std::vector{0}; }, [](int const&) { return Key{std::int64_t{0}}; }, + [build = std::move(build)](reactive::Signal const&) { return build(); }, + Axis::Vertical, 0, common); +} + +[[nodiscard]] Node holding(std::vector children, std::shared_ptr scope, std::vector keys, + int gap) { + Column column = listColumn(std::move(children), gap); + column.common.visible = Prop{[held = std::move(scope)] { return held != nullptr; }}; + column.common.keys = std::move(keys); + return ui::column(std::move(column)); +} + +// NOLINTBEGIN(misc-no-recursion): an expression nests its arguments and fields, and a document nests its nodes; the +// walks follow them. +[[nodiscard]] bool readsAny(ExprPtr const& expr, std::set> const& names) { + if (!expr) { + return false; + } + if (!expr->name.empty() && names.contains(expr->name)) { + return true; + } + return std::ranges::any_of(expr->args, [&](ExprPtr const& arg) { return readsAny(arg, names); }) || + std::ranges::any_of(expr->fields, [&](auto const& field) { return readsAny(field.second, names); }); +} + +void collectIds(DocNode const& node, std::set>& out) { + if (!node.id.empty()) { + out.insert(node.id); + } + for (auto const* group : {&node.children, &node.parts}) { + for (auto const& [key, list] : *group) { + for (DocNodePtr const& child : list) { + collectIds(*child, out); + } + } + } +} +// NOLINTEND(misc-no-recursion) + +// NOLINTNEXTLINE(misc-no-recursion): lowering a node lowers its children, which come back through here. +Node ScreenCore::lowerAll(std::span nodes, LowerCtx const& ctx, int gap) { + LowerCtx listCtx = ctx; + listCtx.listGap = gap; + if (nodes.size() == 1) { + return lower(*nodes.front(), listCtx); + } + std::vector children; + children.reserve(nodes.size()); + for (DocNodePtr const& child : nodes) { + children.push_back(lower(*child, listCtx)); + } + // Several nodes share a holder, and a share of a row is not a share of a holder: each is reported and takes its + // content size. + for (auto&& [child, written] : std::views::zip(children, nodes)) { + if (layoutHintsOf(child).width.kind == Sizing::Kind::Percent) { + report(written->path, + "a percent among several nodes is a share of their holder; " + std::string{kPercentPlaces}); + child = withWidth(child, Sizing::content()); + } + } + Column holder = listColumn(std::move(children), gap); + // The column is the mount's, not the document's: a child that bleeds reaches past the padding of the container + // the document names, so the column passes that padding on instead of hiding it. + holder.holder = true; + return ui::column(std::move(holder)); +} + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_detail.hpp b/src/ui/interpreter_detail.hpp new file mode 100644 index 000000000..b6ca50b1a --- /dev/null +++ b/src/ui/interpreter_detail.hpp @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: Apache-2.0 + +// What the interpreter's translation units share, free of the table and grid headers. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui::detail { + +/// One row a copy writes: its view index, and its cells' texts by the columns copied, none for an unloaded cell. +struct CopyRow { + std::int64_t viewRow = 0; + std::vector> cells; +}; + +/// What a copy writes: each column's header text, and the rows found, in any order. +struct CopyGathered { + std::vector headers; + std::vector rows; +}; + +/// Called once with what a copy gathered, or with the message that says why it could not. +using CopyDone = std::function)>; + +/// What the view name dialog names a view for. +enum class ViewNaming : std::uint8_t { + Save, ///< "Save view…": a name the user already has replaces that view. + Rename, ///< "Rename view…": the view the arrangement was taken from. + Publish, ///< "Publish view…": a name the shared views already have replaces that one. +}; + +/// The view name dialog: whether it is open, what for, and the name typed. +struct ViewDialog { + bool open = false; + ViewNaming purpose = ViewNaming::Save; + std::string name; + + bool operator==(ViewDialog const&) const = default; +}; + +/// A cell of a row the table holds, as a cell menu reads it. +struct HeldCell { + /// The row's record. + Value record; + /// The cell, as its column reads it. + table::Cell cell; + /// The column, as it shows its cells. + table::TableColumn shown; + /// What a `Measure` cell is shown through. + DisplayUnits units; + /// What `units` points into. + std::shared_ptr keep; +}; + +/// A table with the dialogs its menu opens mounted beside it (`ui::besideTable`); without dialogs, the table alone. +/// @param placed The table's common properties; its layout becomes the one inside the column. +/// @param dialogs The dialogs; null for none. +/// @param table Makes the table, after @p placed is changed. +[[nodiscard]] Node besideDialogs(Common& placed, Node dialogs, std::function const& table); + +/// @brief A value as a view key: an `int` or a string as itself, anything else as its JSON text. +/// @param value The value. +/// @return The key. +[[nodiscard]] Key keyOf(Value const& value); + +// A cell range as a document reads it: `{"anchor": {"key", "column"}, "focus": {"key", "column"}}`, `null` for none. +[[nodiscard]] Value cellRangeValue(std::optional const& range); + +// A document's cell range: two corners, each a key and a column id; anything else is none. +[[nodiscard]] std::optional cellRangeOf(Value const& value); + +/// @brief A list of strings out of a value: a string, a list of strings, or nothing. +/// @param value The value. +/// @return The strings. +[[nodiscard]] std::vector stringsOf(Value const& value); + +/// @brief A list of strings as a value. +/// @param texts The strings. +/// @return The list. +[[nodiscard]] Value listOfStrings(std::vector const& texts); + +/// @brief A command context without its scope: what a callback the host keeps may hold, so that the host never +/// keeps a scope alive past its screen. The callback holds the scope weakly and puts it back. +/// @param ctx The context. +/// @return The context, its scope dropped. +[[nodiscard]] CommandCtx detached(CommandCtx const& ctx); + +/// @brief Collects the command lists of a screen's head: its actions', its menu entries' and its tools'. +/// @param doc The screen's document. +/// @param lists Where they go, in document order. +void headCommandLists(Document const& doc, std::vector& lists); + +/// @brief A kind's key spec, from the kind table. +/// @param kind The kind spec. +/// @param key The key. +/// @return The spec, or `nullptr` when the kind has no such key of its own. +[[nodiscard]] KeySpec const* keySpec(KindSpec const& kind, std::string_view key); + +/// @brief Whether a node kind keeps per-element state even without an id: the inputs, dialogs, tables and the forms +/// engine's screens. +/// @param kind The kind. +/// @return It. +[[nodiscard]] bool statefulKind(std::string_view kind); + +/// @brief A value with the field at @p path replaced, creating records along the way. +/// @param base The value written into. +/// @param path The field path. +/// @param value The new value at the path. +/// @return The new value. +// NOLINTNEXTLINE(misc-no-recursion): one level per path segment +[[nodiscard]] Value withPath(Value const& base, std::span path, Value value); + +/// @brief A row's identity for `patch` and `optimistic`: its `id` field. +/// @param row The row. +/// @return The `id` field, or `null`. +[[nodiscard]] Value rowId(Value const& row); + +/// @brief The channel an alias is bound to for its current token, binding it when the token changed. +/// @param alias The alias. +/// @param core The screen. +/// @return The channel, or `nullptr` while the alias is unbound. +[[nodiscard]] std::shared_ptr channelOf(ModelAlias& alias, ScreenCore& core); + +// --- Declaring scopes ------------------------------------------------------------------------------------------ + +/// @brief The element a node of a scope keeps its state in. +/// @param scope The scope that declares it. +/// @param node The node. +/// @return The element, or `nullptr` for a node that keeps none. +[[nodiscard]] ElementState* elementFor(RtScope const& scope, DocNode const& node); + +/// @brief What a date input reads from a value: the instant it shows, and whether the value names one at all. +struct DateReading { + /// @brief The instant shown; empty for an empty field. + std::optional instant; + /// @brief Whether the value names a date, an instant or nothing; `false` for text that names no date. + bool readable = true; +}; + +/// @brief Reads what a date input shows for @p value, in a display zone @p offsetMinutes from UTC. +/// +/// The value is read as the date functions read it (`readDateValue`): a timestamp is its instant; a `yyyy-MM-dd` +/// string is midnight of that date in the display zone; a string `DateTime::fromIso8601` reads is its instant; `null` +/// and `""` are empty. Any other value is empty and unreadable. +/// @param value The value. +/// @param offsetMinutes The display zone's offset from UTC, in minutes. +/// @return The instant, or nothing, and whether the value was readable. +[[nodiscard]] DateReading dateInstantOf(Value const& value, std::int32_t offsetMinutes); + +/// @brief A date input's date text for @p instant in a display zone @p offsetMinutes from UTC. +/// @param instant The instant. +/// @param offsetMinutes The display zone's offset from UTC, in minutes. +/// @return `yyyy-MM-dd`. +[[nodiscard]] std::string dateTextOf(time::DateTime const& instant, std::int32_t offsetMinutes); + +/// @brief A value as the places a number is entered with. +/// @param value The value. +/// @param format The formatting facts. +/// @return The places, 0 to the most a decimal holds; -1 for a value that is not a non-negative integer. +[[nodiscard]] int placesOf(Value const& value, FormatContext const& format); + +/// @brief The key of a select option: a record's `key`, `id` or `value` field, or the option itself. +/// @param option The option. +/// @return The key. +[[nodiscard]] Value optionKey(Value const& option); + +/// @brief A table's sort as its element value reads it: the bound `sort` when the key binds one, else the table's +/// own. +/// @param element The table's element. +/// @return The sort. Tracked. +[[nodiscard]] Value tableSort(ElementState const& element); + +/// @brief The selected keys of the rows a table holds on pages other than the one shown, in their order: what an +/// `Extend` report keeps, since the backend holds the shown page alone. +/// @param view The table's rows and page. +/// @param selection The selection, a list of keys. +/// @param rowKey A row's key. +/// @return The keys. +[[nodiscard]] ValueList selectedOffPage(TableView const& view, Value const& selection, + std::function const& rowKey); + +[[nodiscard]] Value tableSelection(ElementState const& element); + +// --- Lowering -------------------------------------------------------------------------------------------------- + +/// @brief A value as a `bool` property: `true` only for `true`. +/// @param value The value. +/// @param format Unused. +/// @return It. +[[nodiscard]] bool boolOf(Value const& value, FormatContext const& format); + +/// @brief A value as a text property. +/// @param value The value. +/// @param format The formatting facts. +/// @return Its text. +[[nodiscard]] std::string stringOf(Value const& value, FormatContext const& format); + +/// @brief An exact rational as the nearest double, unrounded. +/// +/// `Rational::toDouble` rounds to the value's own places, which is a display reading: `29 / 100` keeps its operands' +/// 0 places and would read as 0. The view tree wants the magnitude, so the lowering reads it here. +/// @param value The rational. +/// @return Its numerator divided by its denominator. +[[nodiscard]] double realOf(math::Rational const& value) noexcept; + +/// @brief A text role by name. +/// @param name `normal`, `muted`, `heading` (or `title`), `section`, `error`, `success`, `mono`, `display`, `small`, +/// `overline`, `caption`, `label`, `headline`. +/// @return The role; `nullopt` for any other name. +[[nodiscard]] std::optional roleNamed(std::string_view name); + +/// @brief What a role that names none is told: the names `roleNamed` reads. +inline constexpr std::string_view kRoleNames = + "a role is normal, muted, heading, section, error, success, mono, display, small, overline, caption, label or " + "headline"; + +/// @brief A text role by name, as `roleNamed` reads it. +/// @param value The name. +/// @param format Unused. +/// @return The role; `Normal` for any other name. +[[nodiscard]] TextRole roleOf(Value const& value, FormatContext const& format); + +/// @brief A tone by name. +/// @param value `neutral`, `info`, `ok` (or `success`), `warn` (or `warning`), `err` (or `error`). +/// @param format Unused. +/// @return The tone; `Neutral` for anything else. +[[nodiscard]] Tone toneOf(Value const& value, FormatContext const& format); + +/// @brief Whether a scope declares any name, so a node in it reads names the screen's own scope lacks. +/// @param scope The scope. +/// @return True when it declares a model, state, let, query, mutation, watch or check. +[[nodiscard]] bool declaresNames(ScopeDecl const& scope) noexcept; + +/// @brief What a span list with a run it drops is told. +inline constexpr std::string_view kSpansReason = + "spans is a list of runs, each a value or a record with `text`; a list, a null or a record without `text` is " + "dropped"; + +/// @brief What a tone of no known name is told. +inline constexpr std::string_view kToneNames = "a tone is neutral, info, ok, warn or err, or null for none"; + +/// @brief What a span list with a run of a tone of no known name is told. +inline constexpr std::string_view kSpanToneReason = + "a run's tone is neutral, info, ok, warn or err, or null for none; a run of another tone is drawn untoned"; + +/// @brief A splitter's `sizes`: a list of numbers, each read as `intOf` reads it. +/// @param value The value. +/// @return The sizes; `nullopt` for anything but a list whose every item is an `int` or a decimal. +[[nodiscard]] std::optional> splitterSizesOf(Value const& value); + +/// @brief An alignment by name, as the loader checked it: `start`, `center`, `end`, or stretch for none. +/// @param name The name; empty for none. +/// @return The alignment. +[[nodiscard]] Align alignOf(std::string_view name); + +/// @brief A table cell's place by name: across its column (`align`) or down its row (`valign`). +/// @param name `start`, `center` or `end`. +/// @return The place; `nullopt` for any other name, `stretch` included. +[[nodiscard]] std::optional cellPlaceNamed(std::string_view name); + +/// @brief A justification by name, as the loader checked it: `center`, `end`, `between`, or start for none. +/// @param name The name; empty for none. +/// @return The justification. +[[nodiscard]] Justify justifyOf(std::string_view name); + +/// @brief An axis by name: `horizontal`, or vertical for anything else. +/// @param value The value. +/// @return The axis. +[[nodiscard]] Axis axisOf(Value const& value); + +/// @brief A step's state by name: `active`, `done`, `failed`, or pending for anything else. +/// @param name The name. +/// @return The state. +[[nodiscard]] StepState stepStateOf(std::string_view name); + +/// @brief The options of a select, from a list of scalars or of records with a key and a `label`. +/// @param options The list. +/// @param format The formatting facts. +/// @return The options. +[[nodiscard]] std::vector selectOptions(Value const& options, FormatContext const& format); + +/// @brief What a percent sizes, as a refusal or a report says it. +inline constexpr std::string_view kPercentPlaces = + "`percent` sizes a width along a row or a horizontal splitter; nothing here takes a share"; + +/// @brief Why a percent inside a case or an overlay's content is not a share. +inline constexpr std::string_view kPercentInHolder = "size the `switch` or the overlay itself; its content fills it"; + +/// @brief The default spacing step between the children of a document panel or collapsible, the mockups' 8 px. +inline constexpr int kPanelGap = 2; + +/// @brief The default spacing step between the children of a document dialog or drawer, the mockups' 12 px. +inline constexpr int kDialogGap = 3; + +/// @brief A node's size request. +/// @param node The node; may be null. +/// @return Its layout hints, or none for a null node or a kind that has no `Common`. +[[nodiscard]] LayoutHints layoutHintsOf(Node const& node); + +/// @brief A node with its width sizing replaced; a node of a kind with no layout is returned as it is. +/// @param node The node. +/// @param width The sizing. +/// @return The node. +[[nodiscard]] Node withWidth(Node const& node, Sizing width); + +/// @brief The size request of a holder of @p sizings: a stretch by the largest weight where any is a stretch, and +/// content otherwise (a share of a row is not a holder's: `listColumn` passes a lone child's on). +/// @param sizings One dimension's sizing of each child. +/// @return The holder's sizing. +[[nodiscard]] Sizing holderSizing(std::span sizings); + +/// @brief Content whose scope is made when it mounts and released when it unmounts: a one-row `forEach` whose +/// row view builds it. +/// @param build Builds the content, its scope included. +/// @param hints The size request of the content. A slot reads the sizing of its direct child alone, which is this +/// `forEach`, so the content's stretch reaches the slot only through these. +/// @return The node. +[[nodiscard]] Node lazy(std::function build, LayoutHints const& hints = {}); + +/// @brief A column of content that holds its scope for as long as it is mounted: its `visible` is a binding +/// that keeps the scope alive and reads nothing. +/// @param children The content. +/// @param scope The scope. +/// @param keys The chords of the content. +/// @param gap The spacing step between the children. +/// @return The node. +[[nodiscard]] Node holding(std::vector children, std::shared_ptr scope, + std::vector keys = {}, int gap = 0); + +/// @brief Whether an expression reads a name in @p names. +/// @param expr The expression. +/// @param names The names. +/// @return Whether any form of the expression names one. +// NOLINTBEGIN(misc-no-recursion): an expression nests its arguments and fields, and the walk follows them. +[[nodiscard]] bool readsAny(ExprPtr const& expr, std::set> const& names); + +// NOLINTEND(misc-no-recursion) + +/// @brief Collects the element ids of a document subtree. +/// @param node The root. +/// @param out Receives the ids. +// NOLINTNEXTLINE(misc-no-recursion): a node's children and parts are nodes, and the walk follows them. +void collectIds(DocNode const& node, std::set>& out); + +/// @brief Where a declaration is lowered, as a focus key reads it. +struct FocusPlace { + /// @brief The focus key of the component use it is lowered for, and `>`; empty outside a component. + std::string prefix; + /// @brief The keys of the rows that enclose it, outermost first. + std::vector rows; +}; + +/// @brief Where @p scope is: the row keys of its chain and the component use it is lowered for. +/// @param scope The scope. +/// @return It. +[[nodiscard]] FocusPlace focusPlace(RtScope const& scope); + +/// @brief A focus key: a declaration's pointer under its component use's prefix, with one key per enclosing row. +/// @param place Where the declaration is lowered. +/// @param path The declaring node's JSON Pointer. +/// @return The key, unique per declaration, row and component use. +[[nodiscard]] std::string focusKey(FocusPlace const& place, std::string_view path); + +/// @brief The focus key of the element @p path declares, lowered in @p scope. +/// @param path The declaring node's JSON Pointer. +/// @param scope The scope it is lowered in. +/// @return The key. +[[nodiscard]] std::string focusKeyOf(std::string_view path, RtScope const& scope); + +/// @brief A lowering context whose scope is held weakly: what an Effect the scope itself owns may keep, so the scope +/// does not keep itself alive. +struct DetachedLower { + /// @brief The scope, weakly. + std::weak_ptr scope; + /// @brief The names bound there. + std::shared_ptr bindings; + /// @brief The innermost boundary. + std::shared_ptr boundary; +}; + +/// @brief Detaches a lowering context's scope. +/// @param ctx The context. +/// @return The context, its scope held weakly. +[[nodiscard]] DetachedLower detachedLower(LowerCtx const& ctx); + +/// @brief Puts a detached context's scope back. +/// @param held The detached context. +/// @return The context; its scope is null once the scope is gone. +[[nodiscard]] LowerCtx attached(DetachedLower const& held); + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a list of rows and a table. +/// The tooltip of a cell whose value cannot be read as its column's kind. +inline constexpr std::string_view kUnreadable = "The value could not be read"; + +/// Whether a column part gives any of a column's display parts. +[[nodiscard]] bool givesDisplay(DocNode const& part); + +/// What a model-backed table's cell reads beside its column: the document's own tone and tooltip expressions. +struct CellExprs { + ExprPtr tone; + ExprPtr tooltip; + std::string path; +}; + +/// @brief What a table's expressions read of its row: the fields named (`{"row": "id"}`), and whether the row is +/// read whole (`{"row": ""}` passed on as a value). A path read out of the whole row with `get` is neither: +/// it is the row's own read, which a binding names at run time. +struct RowReads { + std::set> ids; + bool whole = false; +}; + +// NOLINTNEXTLINE(misc-no-recursion): one level per nested expression. +void rowReadsOf(Expr const& expr, RowReads& out, bool readFrom = false); + +// NOLINTNEXTLINE(misc-no-recursion): one level per nested command list. +void rowReadsOf(Commands const& commands, RowReads& out); + +// NOLINTNEXTLINE(misc-no-recursion): one level per nested node. +void rowReadsOf(DocNode const& node, RowReads& out); + +/// @brief The status line's words for a level: its id with the first letter raised. +/// @param level The level's id. +/// @return The words. +[[nodiscard]] std::string levelWords(std::string level); + +/// @brief A count of rows with its thousands grouped by commas, as a diagnostic writes it. +/// @param count The count. +/// @return The text. +[[nodiscard]] std::string groupedCount(std::size_t count); + +/// @brief The most rows, and the most cells, a table over `rows` orders on the client without a warning. +inline constexpr std::size_t kClientRows = 20'000; + +inline constexpr std::size_t kClientCells = 1'000'000; + +/// @brief The id of the status line's "Show only matching rows", which drops the retained rows. +inline constexpr std::string_view kShowMatching = "retained.showMatching"; + +/// @brief The ids of the status line's "Select them", which selects the rows an action could not change, and "Clear +/// marks", which drops their marks. +inline constexpr std::string_view kSelectFailed = "failed.select"; + +inline constexpr std::string_view kClearMarks = "failed.clear"; + +/// The description's columns a model-backed table's `Table::columns` are, in order: those its column parts name, or +/// without parts every column but the companions, which travel with their columns and are never one of them. +[[nodiscard]] std::vector arrangedColumns(DocNode const& node, + table::TableDescription const& description); + +std::string summaryTestId(Value const& record, std::string const& column); + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_elements.cpp b/src/ui/interpreter_elements.cpp new file mode 100644 index 000000000..89ec7dfa4 --- /dev/null +++ b/src/ui/interpreter_elements.cpp @@ -0,0 +1,1594 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Collecting a document's elements and their state: errors, table views and input values. + +#include "interpreter_grid_detail.hpp" + +namespace morph::ui::detail { + +[[nodiscard]] Value filtersValueOf(table::FilterSpec const& filters) { + auto const json = parseJson(glz::write_json(filters).value_or("null")); + auto read = json ? valueFromJson(*json) : std::expected{Value{}}; + ValueRecord const* const whole = read ? read->asRecord() : nullptr; + if (whole == nullptr) { + return Value{}; + } + ValueRecord out = *whole; + ValueList groups; + if (auto const found = whole->find("groups"); found != whole->end() && found->second.asList() != nullptr) { + for (Value const& group : *found->second.asList()) { + ValueRecord const* const fields = group.asRecord(); + if (fields == nullptr) { + continue; + } + ValueRecord kept = *fields; + if (auto const columnId = kept.find("group"); + columnId != kept.end() && columnId->second == Value{std::string{}}) { + kept.erase(columnId); + } + if (auto const columns = kept.find("columns"); + columns != kept.end() && columns->second.asList() != nullptr && columns->second.asList()->empty()) { + kept.erase(columns); + } + groups.emplace_back(std::move(kept)); + } + } + out.insert_or_assign("groups", Value{std::move(groups)}); + return Value{std::move(out)}; +} + +namespace { + +/// A table's `layout`, `visibleColumns` or `hiddenCount` element value. Tracked. +[[nodiscard]] Value layoutElementValue(TableConfig const& config, std::string_view name) { + table::ColumnLayout const layout = layoutOver(config.columns, config.declaredHidden, layoutNow(config)); + if (name == "layout") { + return layoutValueOf(layout.value()); + } + std::vector const visible = layout.visible(); + if (name == "hiddenCount") { + return static_cast(layout.order().size() - visible.size()); + } + ValueList ids; + for (std::string const& columnId : visible) { + ids.emplace_back(columnId); + } + return Value{std::move(ids)}; +} + +} // namespace + +// --- Declaring scopes ------------------------------------------------------------------------------------------ + +[[nodiscard]] ElementState* elementFor(RtScope const& scope, DocNode const& node) { + // A scope that declares nothing (a locale scope and the scope of its mounted content) leaves its children's + // elements to the enclosing scope, where `collect` registered them, so the lookup continues there. + for (RtScope const* at = &scope; at != nullptr; at = at->transparent ? at->parent.get() : nullptr) { + for (auto const& element : at->elements) { + if (element->node == &node) { + return element.get(); + } + } + } + return nullptr; +} + +namespace { + +/// @brief The transfers of the `upload` commands in a list, nested lists included. +/// @param commands The list. +/// @param out Where the transfer ids go. +// NOLINTNEXTLINE(misc-no-recursion): one level per nested command list +void transfersOf(Commands const& commands, std::vector& out) { + for (Command const& command : commands) { + if (command.kind == CommandKind::Upload && !command.transfer.empty()) { + out.push_back(command.transfer); + } + transfersOf(command.commands, out); + transfersOf(command.alternative, out); + } +} + +} // namespace + +// NOLINTBEGIN(misc-no-recursion): a document is a tree of nodes and parts, and collecting descends it. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of node and part. +void ScreenCore::collect(DocNode const& node, RtScope& scope, std::vector& commands) { + KindSpec const* const spec = findKind(node.kind, false); + if (!node.id.empty() || statefulKind(node.kind)) { + auto element = std::make_unique(runtime()); + element->node = &node; + element->scope = &scope; + if (!node.id.empty()) { + NameRef name; + name.category = NameCategory::Element; + name.element = element.get(); + scope.names.insert_or_assign(node.id, name); + } + wireErrors(*element); + scope.elements.push_back(std::move(element)); + } + bool const createsScope = spec != nullptr && (spec->flags & kScope) != 0; + for (auto const& [key, list] : node.events) { + KeySpec const* const keyed = spec == nullptr ? nullptr : keySpec(*spec, key); + if (!createsScope || keyed == nullptr || (keyed->flags & kInner) == 0) { + commands.push_back(&list); + } + } + for (auto const& [chord, list] : node.keys) { + static_cast(chord); + commands.push_back(&list); + } + for (auto const& [key, nodes] : node.children) { + KeySpec const* const keyed = spec == nullptr ? nullptr : keySpec(*spec, key); + if (createsScope && keyed != nullptr && (keyed->flags & kInner) != 0) { + continue; + } + for (DocNodePtr const& child : nodes) { + collect(*child, scope, commands); + } + } + for (auto const& [key, parts] : node.parts) { + static_cast(key); + for (DocNodePtr const& part : parts) { + KindSpec const* const partSpec = findKind(part->kind, true); + if (partSpec != nullptr && (partSpec->flags & kScope) != 0) { + continue; + } + for (auto const& [event, list] : part->events) { + static_cast(event); + commands.push_back(&list); + } + for (auto const& [childKey, nodes] : part->children) { + KeySpec const* const keyed = partSpec == nullptr ? nullptr : keySpec(*partSpec, childKey); + if (keyed != nullptr && (keyed->flags & kInner) != 0) { + continue; + } + for (DocNodePtr const& child : nodes) { + collect(*child, scope, commands); + } + } + } + } +} + +// NOLINTEND(misc-no-recursion) + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per kind of declaration. +void ScreenCore::declare(RtScope& scope, ScopeDecl const* decl, std::vector const& content, + std::vector const& commands) { + std::vector lists = commands; + for (DocNode const* const node : content) { + collect(*node, scope, lists); + } + std::vector transferIds; + for (Commands const* const list : lists) { + transfersOf(*list, transferIds); + } + for (std::string const& transferId : transferIds) { + if (scope.names.contains(transferId)) { + continue; + } + scope.transfers.push_back(std::make_unique(runtime())); + NameRef name; + name.category = NameCategory::Transfer; + name.transfer = scope.transfers.back().get(); + scope.names.insert_or_assign(transferId, name); + } + if (decl != nullptr) { + for (ModelDecl const& model : decl->models) { + auto alias = std::make_unique(); + alias->decl = &model; + alias->mode = model.instance; + if (alias->mode == InstanceMode::Default) { + std::optional const info = + session.options().catalog.model ? session.options().catalog.model(model.type) : std::nullopt; + alias->mode = info && info->stateless ? InstanceMode::Shared : InstanceMode::Private; + } + ModelAlias* const raw = alias.get(); + switch (raw->mode) { + case InstanceMode::Keyed: + raw->token = &scope.nodes.computed([&scope, raw] -> std::string { + std::string const key = instanceKeyText(evalIn(scope, nullptr, raw->decl->key)); + return key.empty() ? std::string{} : "shared:" + key; + }); + break; + case InstanceMode::Shared: + raw->token = &scope.nodes.computed([] { return std::string{"shared"}; }); + break; + case InstanceMode::Borrowed: { + auto const found = borrowed.find(model.name); + std::string token = found == borrowed.end() ? std::string{} : found->second.token; + raw->token = &scope.nodes.computed([token = std::move(token)] { return token; }); + break; + } + case InstanceMode::Private: + case InstanceMode::Default: + default: { + std::string token = session.privateToken(); + raw->token = &scope.nodes.computed([token = std::move(token)] { return token; }); + break; + } + } + NameRef name; + name.category = NameCategory::Model; + name.model = raw; + scope.names.insert_or_assign(model.name, name); + scope.models.push_back(std::move(alias)); + } + for (LetDecl const& let : decl->lets) { + NameRef name; + name.category = NameCategory::Let; + name.letExpr = let.value; + name.let = &scope.nodes.computed([&scope, expr = let.value] { return evalIn(scope, nullptr, expr); }); + scope.names.insert_or_assign(let.name, name); + } + for (StateDecl const& state : decl->state) { + auto slot = std::make_unique(); + slot->decl = &state; + slot->scope = &scope; + NameRef name; + name.category = NameCategory::State; + name.state = slot.get(); + scope.names.insert_or_assign(state.name, name); + scope.states.push_back(std::move(slot)); + } + auto const aliasOf = [&scope](std::string const& model) -> ModelAlias* { + NameRef const* const found = scope.find(model); + return found != nullptr && found->category == NameCategory::Model ? found->model : nullptr; + }; + for (QueryDecl const& query : decl->queries) { + scope.queries.push_back(std::make_unique(query, scope, aliasOf(query.model))); + NameRef name; + name.category = NameCategory::Query; + name.query = scope.queries.back().get(); + scope.names.insert_or_assign(query.name, name); + } + for (MutationDecl const& mutation : decl->mutations) { + scope.mutations.push_back(std::make_unique(mutation, scope, aliasOf(mutation.model))); + NameRef name; + name.category = NameCategory::Mutation; + name.mutation = scope.mutations.back().get(); + scope.names.insert_or_assign(mutation.name, name); + } + } + for (auto const& slot : scope.states) { + initState(scope, *slot); + } + for (auto const& element : scope.elements) { + wireElement(*element); + } + if (decl == nullptr) { + return; + } + for (CheckDecl const& check : decl->checks) { + auto made = std::make_unique(); + made->decl = ✓ + made->failing = &scope.nodes.computed([&scope, expr = check.assertion] { + Value const asserted = evalIn(scope, nullptr, expr); + bool const* const flag = asserted.asBool(); + return flag != nullptr && !*flag; + }); + made->message = &scope.nodes.computed( + [&scope, expr = check.message] { return textOf(evalIn(scope, nullptr, expr), scope.formatting()); }); + for (std::string const& target : check.targets) { + NameRef const* const found = scope.find(target); + if (found != nullptr && found->category == NameCategory::Element) { + found->element->checks.push_back(made.get()); + made->targets.push_back(found->element); + found->element->checksVersion.set(found->element->checksVersion.peek() + 1); + } + } + scope.checks.push_back(std::move(made)); + } + for (auto const& query : scope.queries) { + query->start(); + } + for (WatchDecl const& watch : decl->watches) { + auto& source = scope.nodes.computed([&scope, expr = watch.on] { return evalIn(scope, nullptr, expr); }); + scope.nodes.effect([this, &scope, &source, watched = &watch, first = true] mutable { + static_cast(source.get()); + if (first) { + first = false; + return; + } + bool const user = session.lastWriteByUser(); + if (watched->source == WatchSource::User && !user) { + return; + } + runtime().untracked([&] { + CommandCtx const ctx{ + .scope = scope.shared_from_this(), + .bindings = std::make_shared(), + .cancelClose = std::make_shared(false), + .boundary = nullptr, + }; + if (user) { + session.asUser([&] { runList(watched->body, ctx, {}); }); + } else { + runList(watched->body, ctx, {}); + } + }); + }); + } +} + +[[nodiscard]] DateReading dateInstantOf(Value const& value, std::int32_t offsetMinutes) { + DateValue const reading = readDateValue(value); + switch (reading.form) { + case DateForm::Absent: + return {}; + case DateForm::Date: + return { + .instant = time::DateTime{std::chrono::sys_days{reading.date} - std::chrono::minutes{offsetMinutes}}, + }; + case DateForm::Timestamp: + case DateForm::InstantText: + return {.instant = reading.instant}; + case DateForm::Unreadable: + default: + return {.instant = std::nullopt, .readable = false}; + } +} + +[[nodiscard]] std::string dateTextOf(time::DateTime const& instant, std::int32_t offsetMinutes) { + auto const local = instant.value + std::chrono::minutes{offsetMinutes}; + std::chrono::year_month_day const date{std::chrono::floor(local)}; + return std::format("{:04}-{:02}-{:02}", static_cast(date.year()), static_cast(date.month()), + static_cast(date.day())); +} + +[[nodiscard]] int placesOf(Value const& value, FormatContext const& format) { + static_cast(format); // Only to fit `bindProp`'s converter signature. + std::int64_t const* const whole = value.asInt(); + if (whole == nullptr || *whole < 0) { + return -1; + } + return static_cast(std::min(*whole, math::kMaxDecimalPlaces)); +} + +namespace { + +/// @brief The fraction digits of a number as typed in the active locale. +/// @param text The typed text. +/// @param format The formatting facts. +/// @return The digits after the decimal separator; 0 for a text that is not a number, which no places rule judges. +[[nodiscard]] std::size_t fractionDigits(std::string_view text, FormatContext const& format) { + std::optional const canonical = render::normalizeLocaleNumber(text, withoutGrouping(format.numeric)); + if (!canonical.has_value()) { + return 0; + } + auto const dot = canonical->find('.'); + return dot == std::string::npos ? 0 : canonical->size() - dot - 1; +} + +/// @brief Whether two values show the same in an input: by text for a text input, by instant for a date input, by +/// value otherwise. +/// @param kind The input's kind. +/// @param lhs One value. +/// @param rhs The other. +/// @param format The formatting facts. +/// @return It. +[[nodiscard]] bool sameShown(std::string_view kind, Value const& lhs, Value const& rhs, FormatContext const& format) { + if (kind == "textInput" || kind == "filePicker") { + return textOf(lhs, format) == textOf(rhs, format); + } + if (kind == "dateTimeInput") { + return dateInstantOf(lhs, format.utcOffsetMinutes).instant == + dateInstantOf(rhs, format.utcOffsetMinutes).instant; + } + return lhs == rhs; +} + +} // namespace + +[[nodiscard]] Value optionKey(Value const& option) { + if (option.asRecord() == nullptr) { + return option; + } + for (std::string_view const field : {"key", "id", "value"}) { + if (Value const* const found = option.field(field)) { + return *found; + } + } + return Value{}; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one rule per source of an error. +void ScreenCore::wireErrors(ElementState& element) { + RtScope& scope = *element.scope; + element.errors = &scope.nodes.computed([this, &element] -> Value { + static_cast(element.checksVersion.get()); + DocNode const& field = *element.node; + RtScope const& owner = *element.scope; + std::vector errors; + // A group's `required` is its legend's mark only: a group has no value, so no `Required` is derived from it. + if (ExprPtr const required = field.kind != "group" ? field.prop("required") : nullptr) { + Value const requiredNow = evalIn(owner, nullptr, required); + bool const* const flag = requiredNow.asBool(); + if (flag != nullptr && *flag && !engaged(inputValue(element))) { + errors.emplace_back("Required"); + } + } + for (std::string& text : stringsOf(evalIn(owner, nullptr, field.prop("errors")))) { + errors.push_back(std::move(text)); + } + if (ExprPtr const places = field.kind == "textInput" ? field.prop("decimals") : nullptr) { + int const allowed = placesOf(evalIn(owner, nullptr, places), session.formatting()); + if (allowed >= 0 && fractionDigits(textOf(inputValue(element), session.formatting()), + session.formatting()) > static_cast(allowed)) { + // The key and fallback of a form field's `too-precise`, so both read alike in any language. + errors.emplace_back(render::resolveText(session.formatting().translations, session.formatting().locale, + std::nullopt, "morph.forms.error.too-precise", + "Too many decimal places")); + } + } + if (!field.id.empty()) { + std::vector const path{"errors", field.id}; + for (auto const& query : owner.queries) { + for (std::string& text : stringsOf(walk(query->value(), path))) { + errors.push_back(std::move(text)); + } + } + for (auto const& mutation : owner.mutations) { + for (std::string& text : stringsOf(walk(mutation->result(), path))) { + errors.push_back(std::move(text)); + } + } + } + for (CheckRuntime const* const check : element.checks) { + if (check->failing->get()) { + errors.push_back(check->message->get()); + } + } + return listOfStrings(errors); + }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of element. +void ScreenCore::wireElement(ElementState& element) { + DocNode const& node = *element.node; + RtScope& scope = *element.scope; + std::string_view const kind = node.kind; + if (kind == "form") { + wireForm(element); + return; + } + if (kind == "collection" || kind == "wizard") { + wireComposite(element); + return; + } + if (kind == "table" && !node.name("model").empty()) { + wireModelTable(element); + return; + } + bool const input = kind == "textInput" || kind == "checkbox" || kind == "select" || kind == "dateTimeInput" || + kind == "slider" || kind == "filePicker"; + if (input) { + std::string_view key = "value"; + if (kind == "checkbox") { + key = "checked"; + } else if (kind == "select") { + key = "selected"; + } + ExprPtr const expr = kind == "filePicker" ? nullptr : node.prop(key); + bool const controlled = expr && (expr->kind != ExprKind::Literal || !expr->literal.isNull()); + if (controlled) { + element.bound = &scope.nodes.computed([&scope, expr] { return evalIn(scope, nullptr, expr); }); + element.draft.set(runtime().untracked([&] { return element.bound->get(); })); + scope.nodes.effect([this, &element, kind] { + Value const bound = element.bound->get(); + runtime().untracked([&] { + if (!element.edited.peek()) { + element.draft.set(bound); + } else if (sameShown(kind, element.draft.peek(), bound, session.formatting())) { + element.edited.set(false); + } + }); + }); + } else if (kind == "checkbox") { + element.draft.set(false); + } + } + if (kind == "select") { + element.rows = + &scope.nodes.computed([&scope, expr = node.prop("options")] { return evalIn(scope, nullptr, expr); }); + if (element.bound == nullptr && node.name("onStale") == "clear") { + scope.nodes.effect([this, &element] { + Value const options = element.rows->get(); + runtime().untracked([&] { + Value const selected = element.draft.peek(); + if (selected.isNull()) { + return; + } + ValueList const* const items = options.asList(); + bool const kept = items != nullptr && std::ranges::any_of(*items, [&](Value const& option) { + return optionKey(option) == selected; + }); + if (!kept) { + session.noteWrite(); + element.draft.set(Value{}); + } + }); + }); + } + } + // A bound sort is controlled as a bound selection is: any expression but a literal `null` binds it. A form grid + // binds its sort as a rows table does. + bool const formGrid = kind == "table" && !node.name("form").empty(); + if (formGrid || (kind == "table" && node.prop("rows"))) { + ExprPtr const sort = node.prop("sort"); + if (sort && (sort->kind != ExprKind::Literal || !sort->literal.isNull())) { + element.sortBound = &scope.nodes.computed([&scope, sort] { return evalIn(scope, nullptr, sort); }); + } + } + if (kind == "table" && node.prop("rows")) { + element.rows = + &scope.nodes.computed([&scope, expr = node.prop("rows")] { return evalIn(scope, nullptr, expr); }); + // A bound selection is controlled, as a select's `selected` is: any expression but a literal `null` binds it. + ExprPtr const selection = node.prop("selection"); + if (selection && (selection->kind != ExprKind::Literal || !selection->literal.isNull())) { + element.bound = &scope.nodes.computed([&scope, selection] { return evalIn(scope, nullptr, selection); }); + } + element.rowsTable = makeRowsTable(element, nullptr, true); + element.view = element.rowsTable->view.get(); + } +} + +[[nodiscard]] Value tableSort(ElementState const& element) { + return element.sortBound != nullptr ? element.sortBound->get() : element.sort.get(); +} + +namespace { + +/// @brief A table's page values: `viewCount` (the rows it orders, every page), `page`, `pageCount`, and +/// `pageFirst` and `pageLast`, the 1-based positions of the page's first and last rows, both 0 when there are +/// none. A table that does not page reads page 0 of 1, over every row. +/// @param element The table's element. +/// @param name The value's name. +/// @return The value. Tracked. +[[nodiscard]] Value tablePageValue(ElementState const& element, std::string_view name) { + if (element.view == nullptr) { + return name == "pageCount" ? std::int64_t{1} : std::int64_t{0}; + } + TableView const& view = element.view->get(); + if (name == "viewCount") { + return static_cast(view.rows.size()); + } + if (name == "page") { + return view.page; + } + if (name == "pageCount") { + return view.pageCount; + } + bool const none = view.first == view.last; + if (name == "pageFirst") { + return none ? std::int64_t{0} : static_cast(view.first + 1); + } + return static_cast(view.last); +} + +/// @brief A model-backed table's own element values, read from its rows: `viewCount` (the reply's total, `null` +/// before the first), `viewCountKind` (`exact` or `atLeast`), `undecided`, `awaiting`, `failed`, `pending` +/// (its description or a fetch in flight) and `error`. +/// @param table The table. +/// @param name The value's name. +/// @return The value; nothing for a value the table shares with a table over `rows`. Tracked. +[[nodiscard]] std::optional modelTableValue(ModelTable const& table, std::string_view name) { + static_cast(table.version.get()); + auto const strings = [](std::vector const& list) { + ValueList out; + for (std::string const& item : list) { + out.emplace_back(item); + } + return Value{std::move(out)}; + }; + TableCountsView const counts = table.rows->counts(); + if (name == "viewCount") { + return counts.view.known ? Value{counts.view.rows} : Value{}; + } + if (name == "viewCountKind") { + if (!counts.view.known) { + return Value{}; + } + return Value{std::string{counts.view.kind == table::TotalKind::AtLeast ? "atLeast" : "exact"}}; + } + if (name == "undecided") { + return Value{counts.undecided}; + } + if (name == "awaiting") { + return strings(counts.awaiting); + } + if (name == "failed") { + return strings(counts.failed); + } + if (name == "pending") { + return Value{counts.pending || (table.describe != nullptr && table.describe->pending())}; + } + if (name == "error") { + if (auto const& error = table.window->error()) { + return Value{error->message}; + } + return table.describe != nullptr ? table.describe->error() : Value{}; + } + return std::nullopt; +} + +} // namespace + +[[nodiscard]] ValueList selectedOffPage(TableView const& view, Value const& selection, + std::function const& rowKey) { + std::unordered_set onPage; + std::unordered_set offPage; + for (std::size_t index = 0; index < view.rows.size(); ++index) { + (index >= view.first && index < view.last ? onPage : offPage).insert(rowKey(view.rows.at(index))); + } + ValueList kept; + if (ValueList const* const selected = selection.asList()) { + for (Value const& item : *selected) { + Key const key = keyOf(item); + if (offPage.contains(key) && !onPage.contains(key)) { + kept.push_back(item); + } + } + } + return kept; +} + +namespace { + +/// @brief The sortable column part of a table with the id @p columnId. +/// @param table The table. +/// @param columnId The column's id. +/// @return The part, or `nullptr` when no sortable column has that id. +[[nodiscard]] DocNode const* sortableColumn(DocNode const& table, std::string_view columnId) { + for (DocNodePtr const& column : table.partList("columns")) { + if (column->id == columnId && column->flag("sortable")) { + return column.get(); + } + } + return nullptr; +} + +} // namespace + +[[nodiscard]] std::optional> sortKeysOf(DocNode const& table, Value const& sort) { + std::vector keys; + if (sort.isNull()) { + return keys; + } + ValueList const* const items = sort.asList(); + if (items == nullptr) { + return std::nullopt; + } + for (Value const& item : *items) { + Value const* const column = item.field("column"); + Value const* const direction = item.field("direction"); + std::string const* const columnId = column == nullptr ? nullptr : column->asString(); + std::string const* const way = direction == nullptr ? nullptr : direction->asString(); + DocNode const* const part = columnId == nullptr ? nullptr : sortableColumn(table, *columnId); + if (part == nullptr || way == nullptr || (*way != "asc" && *way != "desc")) { + return std::nullopt; + } + keys.push_back(SortKey{.column = part, .descending = *way == "desc"}); + } + return keys; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): builds the table's view from the page and the groups in one pass, a heading before the first row of each group +TableView ScreenCore::tableView(RowsTable const& table) { + static_cast(table.version.get()); + DocNode const& node = *table.node; + RtScope const& scope = *table.where; + Bindings const* const bindings = table.bindings.get(); + TableView view; + if (!table.engine->restoring()) { + table::Engine const& engine = table.engine->engine(); + std::size_t const count = engine.viewRowCount(); + view.rows.reserve(count); + for (std::size_t index = 0; index < count; ++index) { + std::optional const ref = table.engine->row(static_cast(index)); + view.rows.push_back(ref ? ref->row : Value{}); + if (table.grouped) { + std::optional const sourceRow = engine.sourceRowOf(index); + view.runOf.push_back(sourceRow ? table.source->runOf(*sourceRow) : 0); + } + } + if (table.grouped && count > 0) { + std::span const runs = table.source->runRecords(); + view.runs.assign(runs.begin(), runs.end()); + } + } + view.last = view.rows.size(); + ExprPtr const sizeExpr = node.prop("pageSize"); + if (!sizeExpr) { + return view; + } + // A `pageSize` of `null` does not page; one that is no positive integer is reported and does not page either. + Value const size = evalIn(scope, bindings, sizeExpr); + std::int64_t const* const perPage = size.asInt(); + if (size.isNull() || perPage == nullptr || *perPage < 1) { + if (!size.isNull()) { + report(pointerAppend(node.path, "pageSize"), + "pageSize is " + canonicalJson(size) + "; a page holds a positive whole number of rows"); + } + return view; + } + // A `page` of `null` is the first; one that is negative or not a whole number is reported and shows the first. + // One past the last is the last: a filter that shrinks the rows under the user is normal, not an error. + std::int64_t asked = 0; + if (ExprPtr const pageExpr = node.prop("page")) { + Value const page = evalIn(scope, bindings, pageExpr); + std::int64_t const* const index = page.asInt(); + if (index != nullptr && *index >= 0) { + asked = *index; + } else if (!page.isNull()) { + report(pointerAppend(node.path, "page"), + "page is " + canonicalJson(page) + "; a page is a whole number from 0"); + } + } + auto const total = static_cast(view.rows.size()); + view.pageCount = std::max(1, (total + *perPage - 1) / *perPage); + view.page = std::min(asked, view.pageCount - 1); + view.first = static_cast(std::min(total, view.page * *perPage)); + view.last = static_cast(std::min(total, (view.page + 1) * *perPage)); + return view; +} + +[[nodiscard]] TableSelection selectionNow(ElementState const& element) { + if (element.modelTable != nullptr) { + if (auto const& view = element.modelTable->viewSelection.get()) { + return *view; + } + } + TableSelection out; + if (Value const itemsValue = tableSelection(element); ValueList const* const items = itemsValue.asList()) { + for (Value const& item : *items) { + out.keys.push_back(keyOf(item)); + } + } + return out; +} + +[[nodiscard]] Value tableSelection(ElementState const& element) { + if (element.bound == nullptr) { + return element.selection.get(); + } + Value const bound = element.bound->get(); + return bound.asList() != nullptr ? bound : Value{ValueList{}}; +} + +[[nodiscard]] Value jsonTextValue(std::string_view text) { + auto const json = parseJson(text); + if (!json) { + return Value{}; + } + auto value = valueFromJson(*json); + return value ? *std::move(value) : Value{}; +} + +namespace { + +/// @brief One field of a form as a record: `value` (the encoded value, `null` while blank or invalid), `draft` (the +/// text), `valid`, `required`, `visible`, `readonly` and `errors`. Tracked. +/// @param field The field. +/// @return The record. +[[nodiscard]] Value formFieldValue(forms::FieldState const& field) { + ValueRecord record; + forms::Encoding const& encoding = field.encoded().get(); + Value value; + if (encoding.has_value() && encoding->has_value()) { + value = (*encoding)->value.isNull() ? jsonTextValue((*encoding)->json) : (*encoding)->value; + } + std::optional const& error = field.error().get(); + record.insert_or_assign("value", std::move(value)); + record.insert_or_assign("draft", Value{field.spec().kind == forms::FieldKind::Object || + field.spec().kind == forms::FieldKind::ObjectArray + ? std::string{} + : field.draft()}); + record.insert_or_assign("valid", Value{!error.has_value()}); + record.insert_or_assign("required", Value{field.required().get()}); + record.insert_or_assign("visible", Value{field.visible().get()}); + record.insert_or_assign("readonly", Value{field.readonly().get()}); + record.insert_or_assign("errors", + error.has_value() ? Value{ValueList{Value{error->message}}} : Value{ValueList{}}); + return Value{std::move(record)}; +} + +/// @brief A form's element values (spec 5 §6): `ready`, `body` (the record the form would submit, `null` while not +/// ready), `submitted` (whether a submission was sent), `pending`, and each field by its wire name. Tracked. +/// @param element The form's element. +/// @param name The value's name. +/// @return The value; `null` for a name the form does not have, or a form without a session. +[[nodiscard]] Value formValue(ElementState const& element, std::string_view name) { + forms::FormSession const* const form = element.form.get(); + if (form == nullptr) { + return Value{}; + } + if (name == "ready") { + return form->ready(); + } + if (name == "body") { + std::optional const body = form->body(); + return body.has_value() ? jsonTextValue(*body) : Value{}; + } + if (name == "submitted") { + return form->submitAttempts() > 0; + } + if (name == "pending") { + return form->pending(); + } + for (auto const& field : form->fields()) { + if (field->spec().name == name) { + return formFieldValue(*field); + } + } + return Value{}; +} + +} // namespace + +Value ScreenCore::inputValue(ElementState const& element) const { + std::string_view const kind = element.node->kind; + if (kind == "checkbox") { + return elementValue(element, "checked"); + } + if (kind == "select") { + return elementValue(element, "selected"); + } + return elementValue(element, "value"); +} + +// NOLINTNEXTLINE(misc-no-recursion,readability-function-cognitive-complexity): one case per element value. +Value ScreenCore::elementValue(ElementState const& element, std::string_view name) const { + DocNode const& node = *element.node; + RtScope const& scope = *element.scope; + std::string_view const kind = node.kind; + auto const flagOf = [&](std::string_view key, bool fallback) -> Value { + ExprPtr const expr = node.prop(key); + if (!expr) { + return fallback; + } + Value const value = evalIn(scope, nullptr, expr); + bool const* const flag = value.asBool(); + return flag != nullptr && *flag; + }; + auto const errors = [&] -> Value { return element.errors->get(); }; + auto const count = [](Value const& list) -> Value { + ValueList const* const items = list.asList(); + return static_cast(items == nullptr ? 0 : items->size()); + }; + if (name == "visible" || name == "enabled") { + return flagOf(name, true); + } + if (name == "errors") { + return errors(); + } + if (name == "valid") { + Value const current = errors(); + ValueList const* const items = current.asList(); + return items == nullptr || items->empty(); + } + if (name == "shownErrors") { + RtScope const& policy = scope.policyScope(); + std::string const mode = policy.showErrors.empty() ? _doc->showErrors : policy.showErrors; + bool const submittedNow = policy.submitted != nullptr && policy.submitted->get(); + if (mode == "always" || (mode == "submit" && submittedNow) || + (mode != "submit" && (submittedNow || element.touched.get() || touchedWithin(element)))) { + return errors(); + } + return Value{ValueList{}}; + } + if (kind == "dialog" || kind == "drawer") { + if (name == "open") { + return node.prop("open") ? flagOf("open", false) : Value{element.open.get()}; + } + if (name == "ready") { + RtScope const* const inner = element.inner.get(); + return inner != nullptr && inner->ready(); + } + if (name == "submitted") { + return element.submitted.get(); + } + return Value{}; + } + if (kind == "table" && (name == "layout" || name == "visibleColumns" || name == "hiddenCount")) { + TableConfig const* const config = + element.rowsTable != nullptr ? &element.rowsTable->config + // NOLINTBEGIN(readability-avoid-nested-conditional-operator): a flat pick through the element's table kinds in the order they are wired + : element.modelTable != nullptr ? &element.modelTable->config + : element.gridTable != nullptr ? &element.gridTable->config + : nullptr; + // NOLINTEND(readability-avoid-nested-conditional-operator) + return config == nullptr ? Value{} : layoutElementValue(*config, name); + } + if (kind == "table" && name == "filters") { + TableConfig const* const config = + element.rowsTable != nullptr ? &element.rowsTable->config + // NOLINTBEGIN(readability-avoid-nested-conditional-operator): a flat pick through the element's table kinds in the order they are wired + : element.modelTable != nullptr ? &element.modelTable->config + : element.gridTable != nullptr ? &element.gridTable->config + : nullptr; + // NOLINTEND(readability-avoid-nested-conditional-operator) + return config == nullptr || !config->filters ? Value{} : filtersValueOf(config->filters()); + } + if (kind == "table" && element.gridTable != nullptr) { + FormGrid const& grid = element.gridTable->grid; + FixedGridSource const* const fixed = element.gridTable->fixed.get(); + if (name == "modifiedCount") { + std::size_t const cells = fixed != nullptr ? fixed->modifiedCount() : grid.source->modifiedCount(); + return Value{static_cast(cells)}; + } + if (name == "modifiedRows") { + std::size_t const cells = fixed != nullptr ? fixed->modifiedRows() : grid.source->modifiedRows(); + return Value{static_cast(cells)}; + } + if (name == "errorCount") { + std::size_t const cells = fixed != nullptr ? fixed->errorCount() : grid.source->errorCount(); + return Value{static_cast(cells)}; + } + if (name == "editing") { + std::optional const cell = grid.grid->editing(); + if (!cell) { + return Value{}; + } + return Value{ValueRecord{{"key", valueOfKey(cell->key)}, {"column", Value{cell->column}}}}; + } + if (name == "selection") { + return cellRangeValue(grid.grid->selection()); + } + } + if (kind == "table" && (name == "modifiedCount" || name == "modifiedRows" || name == "errorCount")) { + return Value{std::int64_t{0}}; + } + if (kind == "table" && name == "busyCount") { + if (element.modelTable == nullptr || element.modelTable->rows == nullptr) { + return Value{std::int64_t{0}}; + } + static_cast(element.modelTable->marksRevision.get()); + return Value{element.modelTable->rows->states().busyCount()}; + } + if (kind == "table" && (name == "selectionSet" || name == "selectedCount" || name == "selectedCountKind")) { + TableSelection const selection = selectionNow(element); + if (name == "selectionSet") { + auto const json = parseJson(selectionJsonOf(selection)); + auto read = json ? valueFromJson(*json) : std::expected{Value{}}; + return read ? std::move(*read) : Value{}; + } + SelectedCount counted{.rows = static_cast(selection.keys.size()), .kind = CountKind::Exact}; + if (element.modelTable != nullptr && element.modelTable->rows != nullptr) { + static_cast(element.modelTable->version.get()); + counted = element.modelTable->rows->selectedCount(selection); + } + if (name == "selectedCount") { + return Value{counted.rows}; + } + return Value{std::string{counted.kind == CountKind::Exact ? "exact" : "approximate"}}; + } + if (kind == "table" && element.modelTable != nullptr && element.modelTable->window != nullptr) { + if (std::optional value = modelTableValue(*element.modelTable, name)) { + return std::move(*value); + } + } + if (kind == "table") { + if (name == "selection") { + return tableSelection(element); + } + if (name == "activeKey") { + return element.activeKey.get(); + } + if (name == "selectedCount") { + return count(tableSelection(element)); + } + if (name == "sort") { + return tableSort(element); + } + if (name == "viewCount" || name == "page" || name == "pageCount" || name == "pageFirst" || + name == "pageLast") { + return tablePageValue(element, name); + } + if (name == "sourceCount") { + return element.rows == nullptr ? Value{std::int64_t{0}} : count(element.rows->get()); + } + ExprPtr const rows = node.prop("rows"); + if ((name == "pending" || name == "error") && rows && rows->kind == ExprKind::Query) { + ScopeEnv const env{scope, nullptr}; + return env.control(name == "pending" ? ExprKind::Pending : ExprKind::Error, rows->name); + } + return name == "pending" ? Value{false} : Value{}; + } + if (kind == "tabs") { + // The shown tab's id: the bound one, else the user's own pick, else the first tab's. + ExprPtr const selected = node.prop("selected"); + if (name != "selected") { + return Value{}; + } + if (selected && (selected->kind != ExprKind::Literal || !selected->literal.isNull())) { + return evalIn(scope, nullptr, selected); + } + if (Value picked = element.draft.get(); !picked.isNull()) { + return picked; + } + auto const tabs = node.partList("tabs"); + return tabs.empty() || tabs.front()->id.empty() ? Value{} : Value{tabs.front()->id}; + } + if (kind == "form") { + return formValue(element, name); + } + if (name == "draft") { + return element.draft.get(); + } + if (name == "dirty") { + return element.edited.get(); + } + if (name == "focused") { + return element.focused.get(); + } + if (name == "touched") { + return element.touched.get(); + } + if (name == "checked" || name == "selected") { + return element.bound != nullptr ? element.bound->get() : element.draft.get(); + } + if (name == "selectedOption") { + Value const selected = elementValue(element, "selected"); + ValueList const* const options = element.rows == nullptr ? nullptr : element.rows->get().asList(); + if (options != nullptr && !selected.isNull()) { + for (Value const& option : *options) { + if (optionKey(option) == selected) { + return option; + } + } + } + return Value{}; + } + if (name == "value") { + if (element.bound != nullptr) { + return element.bound->get(); + } + return element.committed.get(); + } + return Value{}; +} + +bool ScreenCore::touchedWithin(ElementState const& element) { + if (element.node->kind != "group") { + return false; + } + std::string const inside = element.node->path + "/"; + return std::ranges::any_of(element.scope->elements, [&inside](std::unique_ptr const& other) { + return other->node->path.starts_with(inside) && other->touched.get(); + }); +} + +// --- Commands -------------------------------------------------------------------------------------------------- + +// NOLINTBEGIN(misc-no-recursion): command lists nest +void ScreenCore::runList(Commands const& commands, CommandCtx const& ctx, Done done) { + if (!done) { + done = [](bool) {}; + } + if (commands.empty()) { + done(true); + return; + } + struct Join { + std::size_t left = 0; + bool ok = true; + Done done; + }; + if (recording) { + logList(commands); + } + auto const join = std::make_shared(Join{.left = commands.size() + 1, .ok = true, .done = std::move(done)}); + auto const finish = [join](bool succeeded) { + join->ok = join->ok && succeeded; + if (--join->left == 0) { + join->done(join->ok); + } + }; + for (Command const& command : commands) { + runOne(command, ctx, finish); + } + finish(true); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per command of ui/1. +void ScreenCore::runOne(Command const& command, CommandCtx const& ctx, Done done) { + if (!done) { + done = [](bool) {}; + } + RtScope const& scope = *ctx.scope; + auto const eval = [&](ExprPtr const& expr) { return evalIn(scope, ctx.bindings.get(), expr); }; + auto const finish = [&done](bool succeeded) { done(succeeded); }; + switch (command.kind) { + case CommandKind::Set: + runSet(command, ctx, done); + return; + case CommandKind::Reset: + runReset(command, ctx, done); + return; + case CommandKind::Run: + runMutation(command, ctx, std::move(done)); + return; + case CommandKind::Refetch: { + // A loaded document's `refetch` names a query in scope (`loadDocument` checks it), as `run` names a + // mutation and `open` a dialog. + scope.find(command.target)->query->refetch(); + finish(true); + return; + } + case CommandKind::Open: + case CommandKind::Close: { + ElementState* target = nullptr; + if (command.kind == CommandKind::Close && command.target == "self") { + // `self` is the innermost dialog or drawer whose content holds the command, found lexically. A + // component's fallback scope has no parent, so the walk stops at its boundary as its names do. + RtScope const* walk = &scope; + while (walk->owner == nullptr && walk->parent) { + walk = walk->parent.get(); + } + target = walk->owner; + if (target == nullptr && walk != rootScope.lock().get()) { + report(command.path, "`close: self` inside a component names no dialog or drawer"); + finish(false); + return; + } + if (target == nullptr) { + finish((host != nullptr && host->closeSelf(_doc->id, std::nullopt)) || + unsupported(command, "`close: self`")); + return; + } + } else { + target = scope.find(command.target)->element; + } + ElementState& element = *target; + if (element.node->prop("open")) { + report(command.path, "the dialog's `open` is bound to an expression"); + finish(false); + return; + } + bool const opening = command.kind == CommandKind::Open; + if (opening && !element.open.peek()) { + element.submitted.set(false); + } + session.noteWrite(); + element.open.set(opening); + finish(true); + return; + } + case CommandKind::Navigate: { + NavigateRequest const request{ + .screen = command.target, + .route = eval(command.extra), + .params = eval(command.value), + .as = command.option, + .call = false, + }; + if (host == nullptr) { + finish(unsupported(command, "`navigate`")); + return; + } + // A navigation without `onResult` and `onCancel` asks for no answer, so it files no call: the screen it + // opens answers nobody, and its `return` is the application's. + if (command.commands.empty() && command.alternative.empty()) { + finish(host->navigate(request, {}, {}) || unsupported(command, "`navigate`")); + return; + } + std::weak_ptr const weak = ctx.scope; + CommandCtx const kept = detached(ctx); + auto onResult = [this, weak, kept, list = &command.commands](Value const& result) { + if (auto const held = weak.lock()) { + auto const bindings = std::make_shared(*kept.bindings); + bindings->push_back(Binding{.name = "event", .read = [result] { return result; }}); + CommandCtx const next{ + .scope = held, + .bindings = bindings, + .cancelClose = kept.cancelClose, + .boundary = kept.boundary, + }; + runtime().batch([&] { runList(*list, next, {}); }); + } + }; + auto onCancel = [this, weak, kept, list = &command.alternative] { + if (auto const held = weak.lock()) { + CommandCtx next = kept; + next.scope = held; + runtime().batch([&] { runList(*list, next, {}); }); + } + }; + finish(host->navigate(request, std::move(onResult), std::move(onCancel)) || + unsupported(command, "`navigate`")); + return; + } + case CommandKind::Return: + finish(host != nullptr && host->closeSelf(_doc->id, eval(command.value)) + ? true + : unsupported(command, "`return`")); + return; + case CommandKind::Focus: + if (focusTarget(command, scope, ctx.bindings.get())) { + finish(true); + return; + } + report(command.path, "`" + command.target + "` is not mounted"); + finish(false); + return; + case CommandKind::Host: + runHostCommand(command, ctx, done); + return; + case CommandKind::SwitchBackend: { + std::weak_ptr const weak = ctx.scope; + auto committed = [this, weak, target = command.target, path = command.path, + done](std::expected const& outcome) { + if (!weak.lock()) { + return; + } + if (!outcome) { + report(path, "backendSwitchFailed: " + outcome.error()); + done(false); + return; + } + session.backendChanged(target); + done(true); + }; + if (host != nullptr && host->switchBackend(command.target, std::move(committed))) { + return; + } + report(command.path, "backend `" + command.target + "` is not listed"); + finish(false); + return; + } + case CommandKind::ResetPrefs: { + ValueRecord prefsNow = prefs.peek(); + if (command.target == "all") { + prefsNow = prefDefaults; + } else if (auto const found = prefDefaults.find(command.target); found != prefDefaults.end()) { + prefsNow.insert_or_assign(command.target, found->second); + } + prefs.set(std::move(prefsNow)); + if (host != nullptr) { + host->resetPrefs(_doc->id, command.target); + } + finish(true); + return; + } + case CommandKind::SetLocale: + session.setLocale(command.target); + if (host != nullptr) { + host->setLocale(command.target); + } + finish(true); + return; + case CommandKind::SetContext: { + // The shell checks the value against the switcher's options; with no switcher it is unsupported. + Value const requested = eval(command.value); + if (session.requestContext(requested)) { + finish(true); + } else { + report(command.path, + "`setContext` was refused: " + std::string{session.can("context") + ? "the value is not one of the scope's options" + : "no scope switcher is declared"}); + finish(false); + } + return; + } + case CommandKind::Notify: { + std::string const text = textOf(eval(command.value), ctx.scope->formatting()); + finish(host != nullptr && host->notify(text, command.option) ? true : unsupported(command, "`notify`")); + return; + } + case CommandKind::Seq: { + // A step that waits for a reply keeps the rest of the sequence in that reply's handler, which the + // dispatcher may hold past the screen: the sequence holds its scope weakly and stops once it is gone. + CommandCtx const inner = detached(CommandCtx{ + .scope = nullptr, + .bindings = std::make_shared(*ctx.bindings), + .cancelClose = ctx.cancelClose, + .boundary = ctx.boundary, + }); + std::weak_ptr const weak = ctx.scope; + auto const step = std::make_shared>(); + *step = [this, inner, weak, list = &command.commands, done = std::move(done), + weakStep = std::weak_ptr>{step}](std::size_t index) { + auto const held = weak.lock(); + if (index == list->size() || !held) { + done(held != nullptr); + return; + } + auto const self = weakStep.lock(); + CommandCtx current = inner; + current.scope = held; + runOne(list->at(index), current, [self, index, done](bool succeeded) { + if (!succeeded) { + done(false); + return; + } + (*self)(index + 1); + }); + }; + (*step)(0); + return; + } + case CommandKind::All: { + CommandCtx const inner{ + .scope = ctx.scope, + .bindings = std::make_shared(*ctx.bindings), + .cancelClose = ctx.cancelClose, + .boundary = ctx.boundary, + }; + runList(command.commands, inner, std::move(done)); + return; + } + case CommandKind::If: { + Value const condition = eval(command.value); + bool const* const flag = condition.asBool(); + if (flag == nullptr) { + finish(true); + return; + } + runList(*flag ? command.commands : command.alternative, ctx, std::move(done)); + return; + } + case CommandKind::CancelClose: + *ctx.cancelClose = true; + finish(true); + return; + case CommandKind::Retry: + // `retry` is valid only inside a boundary's `error`, which is lowered with its boundary. + for (QueryRuntime* const query : ctx.boundary->queries) { + if (!runtime().untracked([&] { return query->error(); }).isNull()) { + query->refetch(); + } + } + finish(true); + return; + case CommandKind::SignIn: { + NameRef const* const found = scope.find(command.target); + Value const reply = found != nullptr && found->category == NameCategory::Mutation + ? runtime().untracked([&] { return found->mutation->result(); }) + : Value{}; + session.clear(); + finish(host != nullptr && host->signIn(reply) ? true : unsupported(command, "`signIn`")); + return; + } + case CommandKind::SignOut: + session.clear(); + if (host != nullptr) { + host->signOut(); + } + finish(true); + return; + case CommandKind::Upload: + case CommandKind::Download: + default: + runTransfer(command, ctx, std::move(done)); + return; + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): a single run, or a run per list item. +void ScreenCore::runMutation(Command const& command, CommandCtx const& ctx, Done done) const { + RtScope const& scope = *ctx.scope; + MutationRuntime& mutation = *scope.find(command.target)->mutation; + RtScope const& policy = scope.policyScope(); + if (policy.submitted != nullptr) { + policy.submitted->set(true); + } + if (policy.owner != nullptr && !runtime().untracked([&] { return policy.ready(); })) { + done(false); + return; + } + RtScope const& declaring = *[&] -> RtScope const* { + for (RtScope const* candidate = &scope; candidate != nullptr; candidate = candidate->parent.get()) { + if (candidate->names.contains(command.target)) { + return candidate; + } + } + return &scope; + }(); + auto const bodyFor = [&](Bindings const& bindings) { + if (command.value) { + return evalIn(scope, &bindings, command.value); + } + if (mutation.decl().body) { + return evalIn(declaring, &bindings, mutation.decl().body); + } + return Value{ValueRecord{}}; + }; + if (!command.extra) { + Value body = bodyFor(*ctx.bindings); + mutation.run(std::move(body), std::make_shared(*ctx.bindings), + [bindings = ctx.bindings, bindAs = command.binding, done = std::move(done)](bool succeeded, + Value const& reply) { + if (succeeded && !bindAs.empty()) { + bindings->push_back(Binding{.name = bindAs, .read = [reply] { return reply; }}); + } + done(succeeded); + }); + return; + } + Value const each = evalIn(scope, ctx.bindings.get(), command.extra); + ValueList const items = each.asList() == nullptr ? ValueList{} : *each.asList(); + if (items.empty()) { + done(true); + return; + } + struct Each { + std::size_t left = 0; + bool ok = true; + Done done; + }; + auto const state = std::make_shared(Each{.left = items.size(), .ok = true, .done = std::move(done)}); + std::vector bodies; + std::vector> bound; + for (Value const& item : items) { + Bindings bindings = *ctx.bindings; + if (!command.binding.empty()) { + bindings.push_back(Binding{.name = command.binding, .read = [item] { return item; }}); + } + bodies.push_back(bodyFor(bindings)); + bound.push_back(std::make_shared(std::move(bindings))); + } + if (mutation.decl().concurrency != Concurrency::Exclusive) { + for (std::size_t index = 0; index < bodies.size(); ++index) { + mutation.run(bodies.at(index), bound.at(index), [state](bool succeeded, Value const&) { + state->ok = state->ok && succeeded; + if (--state->left == 0) { + state->done(state->ok); + } + }); + } + return; + } + // An exclusive mutation refuses a run while another is in flight, so its elements go one after another. + auto const step = std::make_shared>(); + *step = [&mutation, bodies, bound, state, + weakStep = std::weak_ptr>{step}](std::size_t index) { + if (index == bodies.size()) { + state->done(state->ok); + return; + } + auto const self = weakStep.lock(); + mutation.run(bodies.at(index), bound.at(index), [self, state, index](bool succeeded, Value const&) { + if (!succeeded) { + state->done(false); + return; + } + (*self)(index + 1); + }); + }; + (*step)(0); +} + +// NOLINTEND(misc-no-recursion) +void ScreenCore::writeSlot(StateSlot& slot, std::span within, Value value, Command const& command, + Done const& done) { + slot.scope->core.initState(*slot.scope, slot); + Type const& type = slot.decl->type; + if (within.empty() && !type.isAny() && !type.admits(value)) { + report(command.path, "`set` writes a value that is not a " + type.name()); + done(false); + return; + } + Value next = withPath(slot.value->peek(), within, std::move(value)); + session.noteWrite(); + slot.value->set(std::move(next)); + done(true); +} + +void ScreenCore::runSetApp(Command const& command, std::span rest, Value value, Done const& done) { + if (RtScope const* const app = session.appScope(); app != nullptr && !rest.empty()) { + NameRef const* const named = app->find(rest.front()); + if (named != nullptr && named->category == NameCategory::State) { + writeSlot(*named->state, rest.subspan(1), std::move(value), command, done); + return; + } + report(command.path, "`app." + rest.front() + "` is not state of the app document"); + done(false); + return; + } + std::string name; + for (std::string const& segment : rest) { + name += name.empty() ? segment : "." + segment; + } + done(host != nullptr && host->setAppValue(name, value) ? true : unsupported(command, "`set` of `app`")); +} + +void ScreenCore::runSet(Command const& command, CommandCtx const& ctx, Done const& done) { + RtScope const& scope = *ctx.scope; + auto path = splitPath(command.target); + if (!path || path->empty()) { + done(false); + return; + } + std::string const head = path->front(); + std::span const rest = std::span{*path}.subspan(1); + Value value = evalIn(scope, ctx.bindings.get(), command.value); + if (head == "app") { + runSetApp(command, rest, std::move(value), done); + return; + } + NameRef const* const found = scope.find(head); + if (found != nullptr && found->category == NameCategory::State) { + writeSlot(*found->state, rest, std::move(value), command, done); + return; + } + if (found != nullptr && found->category == NameCategory::Element) { + ElementState& element = *found->element; + session.noteWrite(); + element.draft.set(value); + if (element.bound == nullptr) { + element.committed.set(std::move(value)); + } + done(true); + return; + } + report(command.path, "`set` names nothing writable here"); + done(false); +} + +void ScreenCore::runReset(Command const& command, CommandCtx const& ctx, Done const& done) { + RtScope const& scope = *ctx.scope; + NameRef const* const found = scope.find(command.target); + auto const resetStates = [this](RtScope const& owner) { + for (auto const& slot : owner.states) { + if (slot->value) { + Value init = runtime().untracked([&] { return evalIn(owner, nullptr, slot->decl->init); }); + slot->value->set(std::move(init)); + } + } + for (auto const& element : owner.elements) { + element->draft.set(element->bound != nullptr ? runtime().untracked([&] { return element->bound->get(); }) + : Value{}); + element->committed.set(Value{}); + element->edited.set(false); + element->touched.set(false); + } + }; + bool known = true; + session.noteWrite(); + if (found != nullptr && found->category == NameCategory::State) { + StateSlot& slot = *found->state; + initState(*slot.scope, slot); + slot.value->set(runtime().untracked([&] { return evalIn(*slot.scope, nullptr, slot.decl->init); })); + } else if (found != nullptr && found->category == NameCategory::Element) { + ElementState& element = *found->element; + element.submitted.set(false); + if (RtScope const* const inner = element.inner.peek()) { + resetStates(*inner); + } + } else { + report(command.path, "`reset` names no state or dialog here"); + known = false; + } + done(known); +} + +void ScreenCore::runHostCommand(Command const& command, CommandCtx const& ctx, Done const& done) { + // A command limited to other documents is one this document cannot see: missing, and nothing runs. + if (!session.hostNameIn(command.target, doc().id)) { + report(command.path, "host command `" + command.target + "` is missing"); + done(false); + return; + } + Value const args = evalIn(*ctx.scope, ctx.bindings.get(), command.value); + if (auto const& run = session.hostCommandRunner()) { + HostCommandResult const result = run(command.target, args); + if (result.kind == HostCommandResult::Kind::Missing) { + report(command.path, "host command `" + command.target + "` is missing"); + } else if (result.kind == HostCommandResult::Kind::Refused) { + report(command.path, result.reason); + } + done(result.kind == HostCommandResult::Kind::Ran); + return; + } + bool const known = host != nullptr && host->hostCommand(command.target, args); + if (!known) { + report(command.path, "host command `" + command.target + "` is missing"); + } + done(known); +} + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_fixed_grid.cpp b/src/ui/interpreter_fixed_grid.cpp new file mode 100644 index 000000000..f1a658c2a --- /dev/null +++ b/src/ui/interpreter_fixed_grid.cpp @@ -0,0 +1,803 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Lowering fixed grids. + +#include "interpreter_grid_detail.hpp" + +namespace morph::ui::detail { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one test per way a table can be configured, in the order the document lists them. +[[nodiscard]] std::pair configurableOf(DocNode const& node) { + ExprPtr const expr = node.prop("configurable"); + if (!expr || expr->kind != ExprKind::Literal) { + return {Configure::All, true}; + } + if (bool const* const flag = expr->literal.asBool()) { + return {*flag ? Configure::All : Configure::None, *flag}; + } + Configure allowed = Configure::None; + if (ValueList const* const names = expr->literal.asList()) { + for (Value const& item : *names) { + std::string const* const name = item.asString(); + std::string_view const named = name == nullptr ? std::string_view{} : std::string_view{*name}; + allowed = + allowed | + (named == "reorder" ? Configure::Reorder + // NOLINTBEGIN(readability-avoid-nested-conditional-operator): a flat pick over the configurable names, one per line + : named == "hide" ? Configure::Hide + : named == "pin" ? Configure::Pin + : named == "resize" ? Configure::Resize + : Configure::None); + // NOLINTEND(readability-avoid-nested-conditional-operator) + } + } + return {allowed, true}; +} + +[[nodiscard]] table::ColumnLayout layoutOver(std::span columns, + std::vector const& declaredHidden, + std::optional const& value) { + std::vector ids; + ids.reserve(columns.size()); + for (LayoutColumn const& column : columns) { + ids.push_back(column.id); + } + table::ColumnLayout layout{std::move(ids), declaredHidden}; + if (value) { + layout.apply(*value); + } + return layout; +} + +namespace { + +/// A layout read from a document's value; none for `null`, or for a value that is not a layout. +[[nodiscard]] std::optional layoutFromValue(Value const& value) { + if (value.isNull()) { + return std::nullopt; + } + table::ColumnLayoutValue out; + if (glz::read(out, canonicalJson(value))) { + return std::nullopt; + } + return out; +} + +} // namespace + +[[nodiscard]] std::optional layoutNow(TableConfig const& config) { + static_cast(config.version.get()); + if (config.bound != nullptr) { + return layoutFromValue(config.bound->get()); + } + return config.held; +} + +// NOLINTNEXTLINE(misc-no-recursion): a band nests bands, and the walk follows them. +[[nodiscard]] std::vector bandsOf(std::span parts) { + std::vector bands; + for (DocNodePtr const& part : parts) { + table::BandInfo band{.label = std::string{part->name("label")}, + .unit = std::string{part->name("unit")}, + .columns = {}, + .bands = bandsOf(part->partList("bands"))}; + if (ExprPtr const members = part->prop("columns"); members != nullptr && members->kind == ExprKind::Literal) { + if (ValueList const* const list = members->literal.asList()) { + for (Value const& member : *list) { + if (std::string const* const columnId = member.asString()) { + band.columns.push_back(*columnId); + } + } + } + } + bands.push_back(std::move(band)); + } + return bands; +} + +namespace { + +/// A grid row's record, as its columns' expressions read it: each member's encoded value, `null` when blank or not +/// encoding. +[[nodiscard]] Value gridRowRecord(forms::RowState const& row) { + ValueRecord record; + for (auto const& member : row.fields()) { + forms::Encoding const& encoding = member->encoded().get(); + record.insert_or_assign(member->spec().name, + encoding.has_value() && encoding->has_value() ? (*encoding)->value : Value{}); + } + return Value{std::move(record)}; +} + +} // namespace + +[[nodiscard]] std::vector summarySpecsOf(std::span parts) { + std::vector specs; + for (DocNodePtr const& part : parts) { + specs.push_back(SummarySpec{.key = std::string{part->name("key")}, .top = part->name("position") == "top"}); + } + return specs; +} + +namespace { + +/// A fixed grid's copy and cell menu, set before each mount begins, as a mount's own slots are: a copy writes each +/// cell's text as the grid shows it under its column's label, and a cell menu opens on the row's record, with no +/// filter. +void fixedGridSlots(reactive::Runtime& runtime, GridTable& held) { + GridTable* const grid = &held; + held.config.gather = [&runtime, grid](std::vector keys, std::vector const& ids, + CopyDone const& done) { + CopyGathered gathered; + std::vector kept; + for (std::string const& columnId : ids) { + auto const found = std::ranges::find(grid->config.columns, columnId, &LayoutColumn::id); + if (found != grid->config.columns.end()) { + kept.push_back(columnId); + gathered.headers.push_back(found->label); + } + } + FixedGridSource const& source = *grid->fixed; + runtime.untracked([&] { + for (Key const& key : keys) { + std::optional const position = source.positionOf(key); + if (!position) { + continue; + } + CopyRow row{.viewRow = static_cast(*position), .cells = {}}; + for (std::string const& columnId : kept) { + row.cells.emplace_back(source.text(key, columnId)); + } + gathered.rows.push_back(std::move(row)); + } + }); + done(std::move(gathered)); + }; + held.config.heldCell = [grid](Key const& key, std::string const& columnId) -> std::optional { + static_cast(columnId); + std::optional const position = grid->fixed->positionOf(key); + std::optional const ref = + position ? grid->fixed->view().row(static_cast(*position)) : std::nullopt; + if (!ref) { + return std::nullopt; + } + return HeldCell{.record = ref->row, .cell = table::Cell{}, .shown = {}, .units = {}, .keep = nullptr}; + }; +} + +} // namespace + +// A fixed grid, made once per element as a grid of a form is: its rows the table's `layoutRows`, each block's repeated +// for each row of its collection, and each cell a field of the form `form` names, an expression read in the table's +// scope (in a block, with `row` its collection row's record), or a text, with a grid column's overlays read the same +// way. A row's `label` is read once. Its header, its menus and its arrangement are +// a table's, with no column that sorts or filters. What its cells' expressions keep holds the scope weakly. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per part of a fixed grid. +Node ScreenCore::lowerFixedGrid(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + auto const muted = [] { return ui::text(Text{.text = std::string{}, .role = TextRole::Muted}); }; + if (element == nullptr) { + return muted(); + } + if (element->gridTable != nullptr) { + return gridTableNode(node, ctx, *element); + } + forms::FormSession* form = nullptr; + if (!node.name("form").empty()) { + NameRef const* const named = ctx.scope->find(node.name("form")); + form = named != nullptr && named->element != nullptr ? named->element->form.get() : nullptr; + if (form == nullptr) { + return muted(); + } + } + DetachedLower const detached = detachedLower(ctx); + // An expression read in the table's scope, `row` the block row's record when there is one; nothing once the scope + // is gone. Tracked. + auto const reader = [detached](ExprPtr const& expr) { + return [detached, expr](forms::RowState const* row) -> std::optional> { + LowerCtx const live = attached(detached); + if (live.scope == nullptr) { + return std::nullopt; + } + Bindings bindings = live.bindings != nullptr ? *live.bindings : Bindings{}; + if (row != nullptr) { + Value const record = gridRowRecord(*row); + // NOLINTNEXTLINE(performance-no-automatic-move): the binding's read runs on every evaluation and each returns a copy of the captured record, so the capture stays const + bindings.push_back(Binding{.name = "row", .read = [record] { return record; }}); + } + return std::pair{evalIn(*live.scope, &bindings, expr), live.scope->formatting()}; + }; + }; + auto const count = [](ExprPtr const& expr) { + std::int64_t const* const literal = + expr != nullptr && expr->kind == ExprKind::Literal ? expr->literal.asInt() : nullptr; + return literal != nullptr && *literal > 0 ? static_cast(*literal) : std::size_t{1}; + }; + // NOLINTNEXTLINE(readability-function-cognitive-complexity): lowers one row part of a grid: its cells and options in document order, each reading the row part before + auto const rowOf = [&](DocNode const& part) { + ExprPtr const label = part.prop("label"); + std::string const key{part.name("key")}; + FixedRow made{ + .key = key, .label = label ? textOf(once(ctx, label), ctx.scope->formatting()) : key, .cells = {}}; + for (DocNodePtr const& record : part.partList("cells")) { + for (DocNodePtr const& given : record->partList("cells")) { + FixedCell cell; + cell.field = std::string{given->name("field")}; + cell.text = std::string{given->name("text")}; + cell.rows = count(given->prop("rows")); + cell.columns = count(given->prop("columns")); + if (ExprPtr const value = given->prop("value")) { + cell.value = [read = reader(value)](forms::RowState const* row) { + auto const readRow = read(row); + return readRow ? textOf(readRow->first, readRow->second) : std::string{}; + }; + } + if (ExprPtr const readonly = given->prop("readonly")) { + cell.readonly = [read = reader(readonly)](forms::RowState const* row) { + auto const readRow = read(row); + bool const* const flag = readRow ? readRow->first.asBool() : nullptr; + return flag != nullptr && *flag; + }; + } + if (ExprPtr const decimals = given->prop("decimals")) { + cell.decimals = + [read = reader(decimals)](forms::RowState const* row) -> std::optional { + auto const readRow = read(row); + int const places = readRow ? placesOf(readRow->first, readRow->second) : -1; + return places >= 0 ? std::optional{static_cast(places)} : std::nullopt; + }; + } + if (ExprPtr const unit = given->prop("unit")) { + cell.unit = [read = reader(unit)](forms::RowState const* row) -> std::optional { + auto const readRow = read(row); + std::string const* const columnId = readRow ? readRow->first.asString() : nullptr; + return columnId != nullptr && !columnId->empty() ? std::optional{*columnId} : std::nullopt; + }; + } + if (ExprPtr const offered = given->prop("options")) { + cell.options = [read = reader(offered)]( + forms::RowState const* row) -> std::optional> { + auto const readRow = read(row); + ValueList const* const items = readRow ? readRow->first.asList() : nullptr; + if (items == nullptr) { + return std::nullopt; + } + std::vector kept; + for (Value const& item : *items) { + kept.push_back(glz::write_json(valueToJson(item)).value_or(std::string{})); + } + return kept; + }; + } + if (ExprPtr const placeholder = given->prop("placeholder")) { + cell.placeholder = [read = reader(placeholder)](forms::RowState const* row) { + auto const readRow = read(row); + return readRow ? textOf(readRow->first, readRow->second) : std::string{}; + }; + } + made.cells.insert_or_assign(given->id, std::move(cell)); + } + } + return made; + }; + std::vector parts; + for (DocNodePtr const& part : node.partList("layoutRows")) { + if (std::string_view const forEach = part->name("forEach"); !forEach.empty()) { + FixedBlock block{.forEach = std::string{forEach}, .rows = {}}; + for (DocNodePtr const& row : part->partList("rows")) { + block.rows.push_back(rowOf(*row)); + } + parts.emplace_back(std::move(block)); + } else { + parts.emplace_back(rowOf(*part)); + } + } + std::vector columns; + for (DocNodePtr const& column : node.partList("columns")) { + ExprPtr const label = column->prop("label"); + columns.push_back(GridColumn{.id = column->id, + .label = label ? textOf(once(ctx, label), ctx.scope->formatting()) : column->id, + .field = {}, + .value = {}}); + } + GridOptions options; + gridOptions(node, ctx, options); + auto grid = std::make_unique(runtime()); + GridTable* const held = grid.get(); + TableConfig& config = held->config; + config.element = element; + std::tie(config.allowed, config.menus) = configurableOf(node); + for (GridColumn const& column : columns) { + config.columns.push_back( + LayoutColumn{.id = column.id, .label = column.label, .locked = false, .kind = table::ColumnKind::Text}); + config.sortable.push_back(false); + held->shown.push_back(TableColumn{.id = column.id, .label = column.label}); + } + config.maxSortKeys = [] { return std::size_t{8}; }; + config.message = [this, element](std::string text) { tableMessage(*element, std::move(text)); }; + config.touch = [this, element] { tableMessage(*element, std::string{}); }; + config.rows = [held]() -> TableRows* { return held->fixed ? &held->fixed->view() : nullptr; }; + if (ExprPtr const layout = node.prop("layout"); + layout && (layout->kind != ExprKind::Literal || !layout->literal.isNull())) { + RtScope& scope = *element->scope; + config.bound = &scope.nodes.computed( + [&scope, bindings = ctx.bindings, layout] { return evalIn(scope, bindings.get(), layout); }); + } + try { + held->fixed = std::make_shared(runtime(), form, std::move(parts), std::move(columns), + ctx.scope->formatting()); + } catch (std::invalid_argument const& failure) { + report(node.path, failure.what()); + return muted(); + } + held->grid.grid = std::make_shared(runtime(), *held->fixed, std::move(options)); + held->grid.grid->keepAlive(held->fixed); + held->fixed->onBeforeSubmit([weak = std::weak_ptr{held->grid.grid}] { + if (auto const live = weak.lock()) { + live->leave(); + } + }); + element->gridTable = std::move(grid); + held->grid.grid->useClipboard([this] { return pasteboard ? pasteboard() : std::nullopt; }); + // The cell selection a document binds is shown; each change of it runs `onSelectionChange` with the new range. + if (ExprPtr const bound = node.prop("selection"); + bound && (bound->kind != ExprKind::Literal || !bound->literal.isNull())) { + element->scope->nodes.effect([this, held, scope = element->scope, bindings = ctx.bindings, bound] { + std::optional const range = cellRangeOf(evalIn(*scope, bindings.get(), bound)); + runtime().untracked([&] { + if (held->grid.grid->selection() != range) { + held->grid.grid->select(range); + } + }); + }); + } + if (Commands const* const commands = node.event("onSelectionChange"); commands != nullptr && !commands->empty()) { + held->grid.grid->onSelectionChange([this, detached, commands](std::optional const& range) { + LowerCtx const live = attached(detached); + if (live.scope != nullptr) { + runEvent(commands, live, cellRangeValue(range)); + } + }); + } + // The walk follows the visible columns in layout order, and the cells the scope's formatting. + RtScope* const scope = element->scope; + scope->nodes.effect([this, held, scope] { + TableConfig const& arranged = held->config; + std::vector visible = + layoutOver(arranged.columns, arranged.declaredHidden, layoutNow(arranged)).visible(); + FormatContext format = scope->formatting(); + std::optional focused = held->grid.grid->focus(); + runtime().untracked([&] { + held->fixed->setLayout(std::move(visible)); + held->fixed->setFormat(std::move(format)); + held->config.focused = std::move(focused); + }); + }); + scope->nodes.effect([this, element, held] { + std::string const text = held->grid.grid->message(); + static_cast(held->grid.grid->notices()); + std::vector const offered = held->grid.grid->messageEntries(); + runtime().untracked([&] { + std::vector>> entries; + entries.reserve(offered.size()); + for (StatusEntry const& entry : offered) { + entries.emplace_back(entry, [held, entryId = entry.id] { held->grid.grid->chooseEntry(entryId); }); + } + tableMessage(*element, text, std::move(entries)); + }); + }); + held->setMountSlots = [this, held] { fixedGridSlots(runtime(), *held); }; + return gridTableNode(node, ctx, *element); +} + +// A grid of a form, made once per element: every mount of the table shows the same grid, so its focus, its open +// editor, its messages, its layout, its sort and its filters outlive a remount. Its columns and walk are `gridParts`'; +// its header, its menus, its cell menu and its arrangement are a table's (`configureTable`): an edit column whose part +// says `sortable` sorts, every edit column filters unless its part says `filterable: false`, and a display column does +// neither. The grid's own cell entries come after the built-ins and before the separator and the document's `cellMenu` +// entries. Sorting and filtering change the view, never the record's order. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per part of a table's configuring. +Node ScreenCore::formGridTable(DocNode const& part, LowerCtx const& ctx, ElementState& element, + forms::FormSession& form, forms::FieldState& array) { + if (element.gridTable != nullptr) { + return gridTableNode(part, ctx, element); + } + auto const muted = [&array] { return ui::text(Text{.text = array.path(), .role = TextRole::Muted}); }; + if (array.spec().kind != forms::FieldKind::ObjectArray || array.spec().truncated) { + report(part.path, "`" + array.path() + "` is not a list of records"); + return muted(); + } + std::vector columns; + GridOptions options; + gridParts(part, ctx, array, columns, options); + auto grid = std::make_unique(runtime()); + GridTable* const held = grid.get(); + TableConfig& config = held->config; + config.element = &element; + std::tie(config.allowed, config.menus) = configurableOf(part); + // A column part filters unless it says `filterable: false`; a display column never does. + std::vector filterable; + std::span const parts = part.partList("columns"); + for (std::size_t at = 0; at < columns.size(); ++at) { + GridColumn const& column = columns.at(at); + auto const member = std::ranges::find(array.spec().children, column.field, &forms::FieldSpec::name); + // A member per row sorts and filters its drafts as text. + bool const perRow = static_cast(column.fieldOf); + bool const edits = perRow || (!column.field.empty() && member != array.spec().children.end()); + config.columns.push_back( + LayoutColumn{.id = column.id, + .label = column.label, + .locked = false, + .kind = edits && !perRow ? detail::columnKindOf(member->kind) : table::ColumnKind::Text}); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): guarded by `at < parts.size()` in the same expression + config.sortable.push_back(edits && at < parts.size() && parts[at]->flag("sortable")); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `at >= parts.size()` short-circuits before the index in the same expression + filterable.push_back(edits && (at >= parts.size() || parts[at]->flag("filterable", true))); + held->shown.push_back(TableColumn{.id = column.id, .label = column.label, .sortable = config.sortable.back()}); + } + config.maxSortKeys = [] { return std::size_t{8}; }; + config.message = [this, &element](std::string text) { tableMessage(element, std::move(text)); }; + config.touch = [this, &element] { tableMessage(element, std::string{}); }; + config.filters = [held] { + static_cast(held->filterVersion.get()); + return held->filter; + }; + config.setFilters = [this, &element, held](table::FilterSpec const& filter) { + if (auto const set = held->grid.source->view().setFilter(filter); !set) { + tableMessage(element, "The filter is refused: " + set.error().message); + return false; + } + held->filter = filter; + held->filterVersion.set(held->filterVersion.peek() + 1); + return true; + }; + config.rows = [held]() -> TableRows* { return held->grid.source ? &held->grid.source->view() : nullptr; }; + if (ExprPtr const layout = part.prop("layout"); + layout && (layout->kind != ExprKind::Literal || !layout->literal.isNull())) { + RtScope& scope = *element.scope; + config.bound = &scope.nodes.computed( + [&scope, bindings = ctx.bindings, layout] { return evalIn(scope, bindings.get(), layout); }); + } + // The slots a mount owns, set again before each mount begins: a mount that ends while it is the latest clears + // them, and a later lowering of the same grid must find them set. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): sets a mount's slots in one pass; each slot is set from the same held grid and checked against the later mount + held->setMountSlots = [this, held, filterable] { + TableConfig& slots = held->config; + slots.filterTarget = [held, filterable](std::string const& columnId) -> std::optional { + auto const found = std::ranges::find(held->config.columns, columnId, &LayoutColumn::id); + auto const index = static_cast(found - held->config.columns.begin()); + if (held->grid.source == nullptr || found == held->config.columns.end() || !filterable.at(index)) { + return std::nullopt; + } + std::span const infos = held->grid.source->view().source().columns(); + auto const info = std::ranges::find(infos, columnId, &table::ColumnInfo::id); + if (info == infos.end()) { + return std::nullopt; + } + FilterTarget target; + target.column = columnId; + target.label = found->label; + target.shown = table::TableColumn{.info = *info}; + target.listed = true; + return target; + }; + // A cell a menu opens on: the member as its column's filter reads it, and the row's record. + slots.heldCell = [held](Key const& key, std::string const& columnId) -> std::optional { + FormGridSource const* const source = held->grid.source.get(); + if (source == nullptr) { + return std::nullopt; + } + std::optional const position = source->positionOf(key); + std::optional const ref = + position ? held->grid.source->view().row(static_cast(*position)) : std::nullopt; + if (!ref) { + return std::nullopt; + } + std::optional> cell = source->filterCell(key, columnId); + if (!cell) { + return HeldCell{.record = ref->row, .cell = table::Cell{}, .shown = {}, .units = {}, .keep = nullptr}; + } + return HeldCell{.record = ref->row, + .cell = std::move(cell->first), + .shown = std::move(cell->second), + .units = {}, + .keep = nullptr}; + }; + // A copy: each cell's text as the grid shows it, under its column's label. + slots.gather = [this, held](std::vector keys, std::vector const& ids, CopyDone const& done) { + CopyGathered gathered; + std::vector kept; + for (std::string const& columnId : ids) { + auto const found = std::ranges::find(held->config.columns, columnId, &LayoutColumn::id); + if (found != held->config.columns.end()) { + kept.push_back(columnId); + gathered.headers.push_back(found->label); + } + } + FormGridSource const& source = *held->grid.source; + runtime().untracked([&] { + for (Key const& key : keys) { + std::optional const position = source.positionOf(key); + if (!position) { + continue; + } + CopyRow row{.viewRow = static_cast(*position), .cells = {}}; + for (std::string const& columnId : kept) { + row.cells.emplace_back(source.text(key, columnId)); + } + gathered.rows.push_back(std::move(row)); + } + }); + done(std::move(gathered)); + }; + }; + for (GridColumn const& column : columns) { + auto const member = std::ranges::find(array.spec().children, column.field, &forms::FieldSpec::name); + if (member == array.spec().children.end()) { + continue; + } + std::optional places = member->decimalPlaces ? member->decimalPlaces : member->displayDecimals; + if (!places && member->kind == forms::FieldKind::Integer) { + places = 0; + } + held->places.insert_or_assign(column.id, places); + } + try { + held->grid = makeFormGrid(form, array, std::move(columns), std::move(options), ctx.scope->formatting()); + } catch (std::invalid_argument const& failure) { + report(part.path, failure.what()); + return muted(); + } + // Each lowering makes the table node anew, over the grid kept here: the node's handlers hold the lowering's + // scope, which holds this element, so the element never holds a node. + held->grid.node = nullptr; + element.gridTable = std::move(grid); + held->grid.grid->useClipboard([this] { return pasteboard ? pasteboard() : std::nullopt; }); + // A `group` part groups the rows by its `by`, read with `row` the row's record, over the array's order; the + // summaries of the table and of each run, and each run's heading, are rows of a decorator the mount is handed in + // place of the grid's rows. What the decorator and `by` keep holds the scope weakly, as the columns do. + std::span const groups = part.partList("group"); + DocNode const* const group = groups.empty() ? nullptr : groups.front().get(); + if (group != nullptr) { + held->grouped = true; + held->grid.source->view().setGroup( + [detached = detachedLower(ctx), groupBy = group->prop("by")](forms::RowState const& row) -> Value { + LowerCtx const live = attached(detached); + if (live.scope == nullptr) { + return Value{}; + } + Value const record = gridRowRecord(row); + Bindings bindings = live.bindings != nullptr ? *live.bindings : Bindings{}; + // NOLINTNEXTLINE(performance-no-automatic-move): the binding's read runs on every evaluation and each returns a copy of the captured record, so the capture stays const + bindings.push_back(Binding{.name = "row", .read = [record] { return record; }}); + return evalIn(*live.scope, &bindings, groupBy); + }); + } + std::vector tableSummaries = summarySpecsOf(part.partList("summaries")); + std::vector runSummaries = + group != nullptr ? summarySpecsOf(group->partList("summaries")) : std::vector{}; + if (group != nullptr || !tableSummaries.empty()) { + SummaryRows::Runs runs; + if (group != nullptr) { + runs = [held] { return gridRuns(*held); }; + } + held->summaries = std::make_shared( + std::shared_ptr(std::shared_ptr{}, &held->grid.source->view()), std::move(tableSummaries), + std::move(runSummaries), std::move(runs)); + if (group != nullptr) { + held->summaries->setHeadings([held](std::size_t run) { return gridHeading(*held, run); }); + } + // A copy that spans a summary row writes its cells as they are drawn; the scope is held weakly. + held->grid.grid->copySummaries(held->summaries, [this, &part, held, detached = detachedLower(ctx)]( + Value const& record, std::string const& column) { + LowerCtx const live = attached(detached); + return live.scope == nullptr ? std::string{} : gridSummaryText(part, live, *held, record, column); + }); + } + // The cell selection a document binds is shown; each change of it runs `onSelectionChange` with the new range. + if (ExprPtr const bound = part.prop("selection"); + bound && (bound->kind != ExprKind::Literal || !bound->literal.isNull())) { + element.scope->nodes.effect([this, held, scope = element.scope, bindings = ctx.bindings, bound] { + std::optional const range = cellRangeOf(evalIn(*scope, bindings.get(), bound)); + runtime().untracked([&] { + if (held->grid.grid->selection() != range) { + held->grid.grid->select(range); + } + }); + }); + } + if (Commands const* const commands = part.event("onSelectionChange"); commands != nullptr && !commands->empty()) { + held->grid.grid->onSelectionChange( + [this, detached = detachedLower(ctx), commands](std::optional const& range) { + LowerCtx const live = attached(detached); + if (live.scope != nullptr) { + runEvent(commands, live, cellRangeValue(range)); + } + }); + } + // The walk follows the visible columns in layout order, and the cells the scope's formatting; a copy with no row + // selected copies the focused cell. + RtScope* const scope = element.scope; + scope->nodes.effect([this, held, scope] { + TableConfig const& arranged = held->config; + std::vector visible = + layoutOver(arranged.columns, arranged.declaredHidden, layoutNow(arranged)).visible(); + FormatContext format = scope->formatting(); + std::optional focused = held->grid.grid->focus(); + runtime().untracked([&] { + held->grid.source->setLayout(std::move(visible)); + held->grid.source->setFormat(std::move(format)); + held->config.focused = std::move(focused); + }); + }); + // The sort the element holds, or the document binds, orders the view; one naming no edit column is refused. + scope->nodes.effect([this, &element, held, path = part.path] { + Value const sort = tableSort(element); + runtime().untracked([&] { + SortChain chain; + if (ValueList const* const keys = sort.asList()) { + for (Value const& key : *keys) { + Value const* const column = key.field("column"); + Value const* const direction = key.field("direction"); + if (column != nullptr && column->asString() != nullptr) { + bool const descending = direction != nullptr && direction->asString() != nullptr && + *direction->asString() == "desc"; + chain.push_back(table::SortKey{ + .column = *column->asString(), + .dir = descending ? table::SortDirection::Descending : table::SortDirection::Ascending}); + } + } + } + // A grouped grid sorts within its runs: the run column leads every sort. The array's order already keeps + // each run together, so an empty sort stays empty. + if (held->grouped && !chain.empty()) { + chain.insert(chain.begin(), table::SortKey{.column = std::string{kGroupRunColumn}, + .dir = table::SortDirection::Ascending}); + } + if (auto const set = held->grid.source->view().setSort(std::move(chain)); !set) { + report(pointerAppend(path, "sort"), "the sort is refused: " + set.error().message); + } + }); + }); + scope->nodes.effect([this, &element, held] { + std::string const text = held->grid.grid->message(); + static_cast(held->grid.grid->notices()); + std::vector const offered = held->grid.grid->messageEntries(); + runtime().untracked([&] { + std::vector>> entries; + entries.reserve(offered.size()); + for (StatusEntry const& entry : offered) { + entries.emplace_back(entry, [held, entryId = entry.id] { held->grid.grid->chooseEntry(entryId); }); + } + tableMessage(element, text, std::move(entries)); + }); + }); + return gridTableNode(part, ctx, element); +} + +// The table node of a grid kept in @p element: its status line, its configuring and its columns' filter buttons. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): builds the grid's table node: its status line, its configuring and each column's filter button in order +Node ScreenCore::gridTableNode(DocNode const& part, LowerCtx const& ctx, ElementState& element) { + GridTable* const held = element.gridTable.get(); + TableOptions table; + commonOf(part, ctx, &element, table.common); + // The status line: the grid's notices, posted through `tableMessage` so they are held as a table's are, and the + // state that lasts while its cause holds. + table.status = slotProp([held] { + TableStatus status{.message = held->message.get(), .entries = held->entries.get()}; + status.standing = held->grid.grid->standing(); + status.standingEntries = held->grid.grid->standingEntries(); + status.shown = !status.message.empty() || !status.entries.empty() || !status.standing.empty() || + !status.standingEntries.empty(); + return status; + }); + table.onStatusEntry = [held](std::string const& entryId) { + if (auto const handler = held->entryHandlers.find(entryId); handler != held->entryHandlers.end()) { + std::function const run = handler->second; + run(); + return; + } + held->grid.grid->chooseEntry(entryId); + }; + if (held->setMountSlots) { + held->setMountSlots(); + } + held->config.beginMount(); + Node dialogs = configureTable(held->config, ctx, table, nullptr); + // A copy of a cell selection writes its rectangle; with none the table's copy runs, the focused cell alone. + table.onCopy = [this, held, &element, scope = ctx.scope, rows = std::move(table.onCopy)] { + GridController& grid = *held->grid.grid; + if (!runtime().untracked([&] { return grid.selection().has_value(); })) { + if (rows) { + rows(); + } + return; + } + std::string const separator{scope->formatting().numeric.groupSeparator}; + if (std::optional refused = grid.copyRefusal(separator)) { + tableMessage(element, std::move(*refused)); + return; + } + std::string const text = grid.copy(); + if (text.empty()) { + return; + } + std::size_t const lines = static_cast(std::ranges::count(text, '\n')) + 1; + if (!clipboard || !clipboard(text)) { + tableMessage(element, "The rows could not be copied: there is no clipboard"); + return; + } + tableMessage(element, tableText::copied(lines, 0, separator)); + }; + // The table's own menu offers the focused row's entries after its own, past a separator. + if (table.menu && table.onMenu) { + auto const rowEntries = [this, held] { + return runtime().untracked([&] { + std::optional const focused = held->grid.grid->focus(); + return focused ? held->grid.grid->rowEntries(focused->key) : std::vector{}; + }); + }; + auto const own = table.menu; + table.menu = [this, own, rowEntries](std::optional column) { + std::vector entries = own(column); + if (column) { + return entries; + } + std::vector const rows = rowEntries(); + if (!rows.empty() && !entries.empty()) { + entries.push_back(MenuEntry{.separator = true}); + } + runtime().untracked([&] { + for (MenuItem const& item : rows) { + entries.push_back(MenuEntry{.label = item.label.evaluate(), + .enabled = item.enabled.evaluate(), + .description = item.description.evaluate()}); + } + }); + return entries; + }; + table.onMenu = [this, own, rowEntries, chosen = std::move(table.onMenu)]( + std::optional column, std::vector const& path) { + if (!column && !path.empty()) { + std::size_t const shown = own(column).size(); + std::size_t const first = shown + (shown > 0 ? 1 : 0); + if (path.front() >= first) { + std::vector const rows = rowEntries(); + std::size_t const index = path.front() - first; + if (index < rows.size() && + runtime().untracked([&] { return rows.at(index).enabled.evaluate(); }) && + rows.at(index).onSelect) { + rows.at(index).onSelect(); + } + return; + } + } + chosen(column, path); + }; + } + std::vector columns = held->shown; + markFilterable(held->config, columns, table); + table.bands = bandsOf(part.partList("bands")); + std::optional base; + if (held->summaries != nullptr) { + base = summarySource(part, ctx, *held, columns); + } + // A fixed grid's row is named by its label. + if (held->fixed != nullptr) { + TableSource named; + named.rows = std::shared_ptr(held->grid.grid, &held->fixed->view()); + named.rowView = [fixed = held->fixed](reactive::Signal const& row) { + TableRowLook look; + reactive::Signal const* const record = &row; + look.label = Prop{[fixed, record] { + std::optional const key = fixed->keyOf(record->get()); + return key ? fixed->label(*key) : std::string{}; + }}; + return look; + }; + base = std::move(named); + } + return besideDialogs(table.common, std::move(dialogs), + [&] { return held->grid.grid->node(std::move(columns), std::move(table), std::move(base)); }); +} + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_forms.cpp b/src/ui/interpreter_forms.cpp new file mode 100644 index 000000000..15b359150 --- /dev/null +++ b/src/ui/interpreter_forms.cpp @@ -0,0 +1,1205 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Lowering forms, wizards and components. + +#include "interpreter_grid_detail.hpp" + +namespace morph::ui::detail { + +namespace { + +/// @brief A document field overlay's expressions, evaluated once, as the engine's overlay. +/// @param scope The scope the form is declared in. +/// @param part The `fields` entry. +/// @param format How values read as text and numbers. +/// @return The overlay. +[[nodiscard]] forms::FieldOverlay overlayOf(RtScope const& scope, DocNode const& part, FormatContext const& format) { + auto const read = [&](std::string_view key) -> std::optional { + ExprPtr const expr = part.prop(key); + if (!expr) { + return std::nullopt; + } + return scope.core.runtime().untracked([&] { return evalIn(scope, nullptr, expr); }); + }; + auto const text = [&](std::string_view key) -> std::optional { + auto const value = read(key); + return value.has_value() && !value->isNull() ? std::optional{textOf(*value, format)} + : std::nullopt; + }; + auto const flag = [&](std::string_view key) { + auto const value = read(key); + bool const* const set = value.has_value() ? value->asBool() : nullptr; + return set != nullptr && *set; + }; + forms::FieldOverlay overlay{.omit = flag("omit"), .hidden = flag("hidden")}; + overlay.label = text("label"); + overlay.unit = text("unit"); + overlay.widget = text("widget"); + if (auto const decimals = read("decimals"); + decimals.has_value() && decimals->asInt() != nullptr && *decimals->asInt() >= 0) { + overlay.decimals = static_cast(std::min(*decimals->asInt(), 18)); + } + if (auto const blankAs = text("blankAs")) { + overlay.blankAs = *blankAs == "empty" ? forms::BlankAs::Empty : forms::BlankAs::Omit; + } + return overlay; +} + +} // namespace + +[[nodiscard]] DetachedLower detachedLower(LowerCtx const& ctx) { + return DetachedLower{.scope = ctx.scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; +} + +[[nodiscard]] LowerCtx attached(DetachedLower const& held) { + return LowerCtx{.scope = held.scope.lock(), .bindings = held.bindings, .boundary = held.boundary}; +} + +// Builds the form's session when its element is declared, so its values can be read before the form is drawn. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per kind of form element and its sessions. +void ScreenCore::wireForm(ElementState& element) { + DocNode const& node = *element.node; + RtScope& scope = *element.scope; + std::string const action{node.name("action")}; + Catalog const& catalog = session.options().catalog; + std::optional const schema = catalog.schema ? catalog.schema(action) : std::nullopt; + if (!schema.has_value()) { + report(node.path, "no schema for `" + action + "`: the catalog has none for a `form` to build from"); + return; + } + NameRef const* const alias = scope.find(node.name("model")); + if (alias == nullptr || alias->model == nullptr) { + report(node.path, "`" + std::string{node.name("model")} + "` is not a model alias"); + return; + } + forms::FieldOverlays overlays; + // `fields` is one record part holding a `field` part per overlaid member. + for (DocNodePtr const& record : node.partList("fields")) { + for (DocNodePtr const& part : record->partList("fields")) { + forms::FieldOverlay overlay = overlayOf(scope, *part, session.formatting()); + // A computed `decimals` is carried by the effect below alone: baking the value read now would make it + // the fallback when the expression later gives no places, where the schema's places belong. + if (ExprPtr const places = part->prop("decimals"); places && places->kind != ExprKind::Literal) { + overlay.decimals.reset(); + } + overlays.insert_or_assign(part->id, std::move(overlay)); + } + } + auto model = forms::FormModel::fromSchema(action, *schema, overlays); + if (!model) { + report(node.path, + "the form of `" + action + "` does not build: " + model.error().path + ": " + model.error().message); + return; + } + if (node.name("submit") == "explicit") { + model = model->withSubmitMode(forms::SubmitMode::Explicit); + } else if (node.name("submit") == "auto") { + model = model->withSubmitMode(forms::SubmitMode::Automatic); + } + element.form = std::make_unique(runtime(), *std::move(model), aliasSubmits(alias->model), + aliasCalls(alias->model), engineOptions()); + followFormatting(element, scope); + deriveForm(element, alias->model); + // An overlay's `decimals` follows its expression: the field keeps the draft as typed and checks it again against + // the places the expression gives now. + for (DocNodePtr const& record : node.partList("fields")) { + for (DocNodePtr const& part : record->partList("fields")) { + ExprPtr const places = part->prop("decimals"); + if (!places) { + continue; + } + forms::FieldState* state = nullptr; + try { + state = &element.form->field(part->id); + } catch (std::out_of_range const&) { + continue; // The overlay names a field the form does not have (an omitted one). + } + scope.nodes.effect([this, &scope, places, state] { + int const now = placesOf(evalIn(scope, nullptr, places), session.formatting()); + runtime().untracked([&] { + state->places().set(now >= 0 ? std::optional{static_cast(now)} + : std::nullopt); + }); + }); + } + } + if (ExprPtr const prefill = node.prop("prefill")) { + // A prefill follows its expression. A value of the record being edited (the first value, or one under the + // same `key`) keeps the fields the user changed; another record, a new `key`, or any later value of a form + // without one, loads every field. + forms::FormSession* const form = element.form.get(); + struct Followed { + bool loaded = false; + Value key; + }; + auto const followed = std::make_shared(); + scope.nodes.effect([this, &scope, prefill, key = node.prop("key"), form, followed] { + Value const value = evalIn(scope, nullptr, prefill); + if (value.isNull()) { + return; + } + runtime().untracked([&] { + Value const current = key ? evalIn(scope, nullptr, key) : Value{}; + bool const same = !followed->loaded || (key && current == followed->key); + followed->loaded = true; + followed->key = current; + std::string const json = glz::write_json(valueToJson(value)).value_or(std::string{}); + if (same) { + form->refill(json); + } else { + form->prefill(json); + } + }); + }); + } +} + +namespace { + +// Whether a field, or a member of it at any depth, is computed: what an evaluation round would bring back. +// NOLINTBEGIN(misc-no-recursion): an object's and a row's members are fields. +[[nodiscard]] bool computesAny(std::span fields) { + return std::ranges::any_of( + fields, [](forms::FieldSpec const& field) { return field.computed || computesAny(field.children); }); +} +// NOLINTEND(misc-no-recursion) + +} // namespace + +// A form's rounds of derived values: its action's evaluation while a member is computed, and its `derive` action when +// it names one, each sent through the form's alias, `deriveDebounce` (150 ms when absent) after the last commit on the +// session's timers. A path a derive reply names that is no derived member is reported once. +void ScreenCore::deriveForm(ElementState& element, ModelAlias* alias) { + DocNode const& node = *element.node; + std::string const action{node.name("action")}; + std::string const derive{node.name("derive")}; + bool const computes = computesAny(element.form->model().fields()); + if (derive.empty() && !computes) { + return; + } + auto const call = [this, alias](std::string actionId, bool evaluate) { + return [this, alias, actionId = std::move(actionId), + evaluate](std::string const& body) -> async::Completion { + std::shared_ptr const channel = channelOf(*alias, *this); + if (channel == nullptr) { + auto [failed, promise] = async::Completion::makeSettleable(&runtime().owner()); + promise.reject(std::make_exception_ptr(std::runtime_error{"the node's model alias is not bound"})); + return std::move(failed); + } + return channel->execute(actionId, body, CallOptions{.evaluate = evaluate}); + }; + }; + forms::DeriveOptions options; + if (computes) { + options.evaluate = call(action, true); + } + if (!derive.empty()) { + options.derive = call(derive, false); + } + options.scheduler = session.options().scheduler; + if (ExprPtr const debounce = node.prop("deriveDebounce"); debounce && debounce->kind == ExprKind::Literal) { + if (std::int64_t const* const millis = debounce->literal.asInt(); millis != nullptr && *millis >= 0) { + options.debounce = std::chrono::milliseconds{*millis}; + } + } + options.refused = [this, path = node.path, derive](std::vector const& paths) { + for (std::string const& refused : paths) { + report( + path + "/derive", + // NOLINTNEXTLINE(performance-inefficient-string-concatenation): builds one refusal message from five pieces, once, on the error path + "the reply of `" + derive + "` names `" + refused + "`, which is not a derived member of the form"); + } + }; + element.form->deriveWith(std::move(options)); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): lowers a form: its fields, collections, actions and derives in document order, each reading the form state before +Node ScreenCore::lowerForm(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + forms::FormSession* const form = element == nullptr ? nullptr : element->form.get(); + if (form == nullptr) { + return ui::text(Text{.text = std::string{node.name("action")}, .role = TextRole::Muted}); + } + // The form's events, each run once per change of the count it watches. + auto const watch = [this, &ctx](Commands const* commands, auto count, auto payload) { + if (commands == nullptr || commands->empty()) { + return; + } + auto const seen = std::make_shared(runtime().untracked(count)); + ctx.scope->nodes.effect([this, held = detachedLower(ctx), commands, count, payload, seen] { + std::uint64_t const now = count(); + if (now == *seen) { + return; + } + *seen = now; + runtime().untracked([&] { runEvent(commands, attached(held), payload()); }); + }); + }; + watch( + node.event("onSubmit"), [form] { return form->submitAttempts(); }, + [form] { + std::optional const body = form->body(); + return body.has_value() ? jsonTextValue(*body) : Value{}; + }); + watch( + node.event("onSuccess"), [form] { return form->successCount(); }, + [form] { + std::optional const& reply = form->lastReply(); + return reply.has_value() ? jsonTextValue(*reply) : Value{}; + }); + if (Commands const* const onError = node.event("onError"); onError != nullptr && !onError->empty()) { + // Each failure is a new exception: run once per failure, with its text. + auto const seen = + std::make_shared(runtime().untracked([form] { return form->lastError(); })); + ctx.scope->nodes.effect([this, held = detachedLower(ctx), onError, form, seen] { + std::exception_ptr const error = form->lastError(); + if (error == nullptr || error == *seen) { + return; + } + *seen = error; + runtime().untracked([&] { runEvent(onError, attached(held), Value{failureText(error)}); }); + }); + } + forms::FormViewOptions options{.showTitle = false}; + presentForm(node, ctx, options); + options.title = bindProp(ctx, node.prop("title"), std::string{}, stringOf); + // A field whose overlay names a component is drawn by it; only top-level fields take one, as every overlay. + for (DocNodePtr const& record : node.partList("fields")) { + for (DocNodePtr const& overlay : record->partList("fields")) { + if (!overlay->name("component").empty()) { + options.overrides.byField(overlay->id, + [this, ctx, field = overlay.get()](forms::FieldView const& view) { + return fieldComponent(view, *field, ctx); + }); + } + // A `grid` part makes the field a grid table, kept on the form's element by the field's name so every + // mount of the form shows the same grid; the scope is held weakly, as the grid's is. + if (std::span const grid = overlay->partList("grid"); !grid.empty()) { + options.overrides.byField( + overlay->id, [this, element, detached = detachedLower(ctx), part = grid.front().get(), + name = overlay->id](forms::FieldView const& view) { + LowerCtx const live = attached(detached); + if (live.scope == nullptr) { + return ui::text(Text{.text = view.state().path(), .role = TextRole::Muted}); + } + std::unique_ptr& slot = element->fieldGrids[name]; + if (slot == nullptr) { + slot = std::make_unique(runtime()); + slot->node = part; + slot->scope = element->scope; + } + return formGridTable(*part, live, *slot, view.session(), view.state()); + }); + } + } + } + Column column{.children = {forms::formView(*form, std::move(options))}}; + commonOf(node, ctx, element, column.common); + return ui::column(std::move(column)); +} + +// What a grid's part gives beyond its table: its columns, each a member its `field` names or a display column whose +// `value` is read with `row` the row's record, every member of the row type in schema order when it gives none; +// `enterMoves`, `walk`, and `onActivate`, run with the row's key on a read-only cell. What the columns and +// `onActivate` keep holds the scope weakly: the grid lives as long as the element the scope owns. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one section per key of a grid column. +void ScreenCore::gridParts(DocNode const& part, LowerCtx const& ctx, forms::FieldState const& array, + std::vector& columns, GridOptions& options) { + DetachedLower const detached = detachedLower(ctx); + // An expression read in a row's scope, `row` its record of encoded members; null once the scope is gone. Tracked. + auto const inRow = [detached](ExprPtr const& expr) { + return [detached, expr](forms::RowState const& row) -> std::optional> { + LowerCtx const live = attached(detached); + if (live.scope == nullptr) { + return std::nullopt; + } + ValueRecord record; + for (auto const& member : row.fields()) { + forms::Encoding const& encoding = member->encoded().get(); + record.insert_or_assign(member->spec().name, + encoding.has_value() && encoding->has_value() ? (*encoding)->value : Value{}); + } + Bindings bindings = live.bindings != nullptr ? *live.bindings : Bindings{}; + bindings.push_back(Binding{.name = "row", .read = [record] { return Value{record}; }}); + return std::pair{evalIn(*live.scope, &bindings, expr), live.scope->formatting()}; + }; + }; + for (DocNodePtr const& column : part.partList("columns")) { + ExprPtr const label = column->prop("label"); + GridColumn made{.id = column->id, + .label = label ? textOf(once(ctx, label), ctx.scope->formatting()) : column->id, + .field = std::string{column->name("field")}, + .value = {}}; + if (ExprPtr const field = column->prop("field")) { + // One member per row: a name that is no member of the row type is reported once, and its cell is + // read-only. + std::vector members; + for (forms::FieldSpec const& member : array.spec().children) { + members.push_back(member.name); + } + made.fieldOf = [this, read = inRow(field), members = std::move(members), + path = field->path](forms::RowState const& row) { + auto const readRow = read(row); + std::string const name = readRow ? textOf(readRow->first, readRow->second) : std::string{}; + if (!name.empty() && std::ranges::find(members, name) == members.end()) { + report(path, "`" + name + "` names no member of the row"); + } + return name; + }; + } + ExprPtr const value = column->prop("value"); + if (made.field.empty() && !made.fieldOf && value) { + made.value = [read = inRow(value)](forms::RowState const& row) { + auto const readRow = read(row); + return readRow ? textOf(readRow->first, readRow->second) : std::string{}; + }; + } + // Overlays per row, as a form field's overlays, each read in the row's scope. + if (ExprPtr const decimals = column->prop("decimals")) { + made.decimals = [read = inRow(decimals)](forms::RowState const& row) -> std::optional { + auto const readRow = read(row); + int const places = readRow ? placesOf(readRow->first, readRow->second) : -1; + return places >= 0 ? std::optional{static_cast(places)} : std::nullopt; + }; + } + if (ExprPtr const unit = column->prop("unit")) { + made.unit = [read = inRow(unit)](forms::RowState const& row) -> std::optional { + auto const readRow = read(row); + std::string const* const columnId = readRow ? readRow->first.asString() : nullptr; + return columnId != nullptr && !columnId->empty() ? std::optional{*columnId} : std::nullopt; + }; + } else if (std::string_view const unitName = column->name("unit"); !unitName.empty()) { + made.unit = [unitId = std::string{unitName}](forms::RowState const&) { return std::optional{unitId}; }; + } + if (ExprPtr const readonly = column->prop("readonly")) { + made.readonly = [read = inRow(readonly)](forms::RowState const& row) { + auto const readRow = read(row); + bool const* const flag = readRow ? readRow->first.asBool() : nullptr; + return flag != nullptr && *flag; + }; + } + if (ExprPtr const offered = column->prop("options")) { + made.options = + [read = inRow(offered)](forms::RowState const& row) -> std::optional> { + auto const readRow = read(row); + ValueList const* const items = readRow ? readRow->first.asList() : nullptr; + if (items == nullptr) { + return std::nullopt; + } + std::vector kept; + for (Value const& item : *items) { + kept.push_back(glz::write_json(valueToJson(item)).value_or(std::string{})); + } + return kept; + }; + } + if (ExprPtr const placeholder = column->prop("placeholder")) { + made.placeholder = [read = inRow(placeholder)](forms::RowState const& row) { + auto const readRow = read(row); + return readRow ? textOf(readRow->first, readRow->second) : std::string{}; + }; + } + columns.push_back(std::move(made)); + } + if (columns.empty()) { + for (forms::FieldSpec const& member : array.spec().children) { + columns.push_back(GridColumn{.id = member.name, .label = member.title, .field = member.name, .value = {}}); + } + } + gridOptions(part, ctx, options); +} + +// What any grid's part gives of its walk and its activation: `enterMoves`, `walk`, `appendRows`, `rowsFixed`, the +// session's paste and copy bounds and its timers, and `onActivate`, run with the row's key on a read-only cell, which +// holds the scope weakly. +void ScreenCore::gridOptions(DocNode const& part, LowerCtx const& ctx, GridOptions& options) { + DetachedLower const detached = detachedLower(ctx); + std::string_view const enter = part.name("enterMoves"); + options.enterMoves = + // NOLINTNEXTLINE(readability-avoid-nested-conditional-operator): a three-way map of the enterMoves text to the enum + enter == "right" ? EnterMoves::Right : (enter == "none" ? EnterMoves::None : EnterMoves::Down); + options.walk = part.name("walk") == "columns" ? Walk::Columns : Walk::Rows; + options.appendRows = part.flag("appendRows"); + options.rowsFixed = part.flag("rowsFixed"); + options.maxPasteCells = session.options().maxPasteCells; + options.maxCopyRows = session.options().maxCopyRows; + options.scheduler = session.options().scheduler; + options.undoHold = kStatusMessageHold; + if (Commands const* const commands = part.event("onActivate"); commands != nullptr && !commands->empty()) { + options.onActivate = [this, detached, commands](Key const& key) { + LowerCtx const live = attached(detached); + if (live.scope != nullptr) { + runEvent(commands, live, valueOfKey(key)); + } + }; + } +} + +// A grid of a form named by a table's `form` and `field`. +Node ScreenCore::lowerFormGrid(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + NameRef const* const named = ctx.scope->find(node.name("form")); + forms::FormSession* const form = + named != nullptr && named->element != nullptr ? named->element->form.get() : nullptr; + if (form == nullptr || element == nullptr) { + return ui::text(Text{.text = std::string{node.name("field")}, .role = TextRole::Muted}); + } + forms::FieldState* array = nullptr; + try { + array = &form->field(node.name("field")); + } catch (std::out_of_range const&) { + report(node.path, "`" + std::string{node.name("field")} + "` is not a field of the form"); + return ui::text(Text{.text = std::string{node.name("field")}, .role = TextRole::Muted}); + } + return formGridTable(node, ctx, *element, *form, *array); +} + +[[nodiscard]] std::expected changeWire(std::string const& payload, + std::string_view type) { + std::string_view text{payload}; + if (type == "string") { + if (text.starts_with("s:")) { + text.remove_prefix(2); + } + // Parentheses: braces would pick the initializer-list constructor and make a one-element array. + return forms::detail::engine::Json(std::string{text}); + } + if (text.starts_with("i:")) { + text.remove_prefix(2); + } + std::optional json = forms::detail::engine::parseJson(text); + if (!json) { + return std::unexpected(std::string{"it is not JSON"}); + } + bool const fits = type == "json" || json->is_null() || (type == "bool" && json->is_boolean()) || + ((type == "int" || type == "number") && json->is_number()) || + (type == "exact" && (json->is_number() || json->is_string())); + if (!fits) { + bool const vowel = type == "int" || type == "exact"; + return std::unexpected("it is not " + std::string{vowel ? "an " : "a "} + std::string{type}); + } + return *std::move(json); +} + +namespace { + +/// @brief What a form fills of a field component's props: the field's value, errors, read-only and required state, +/// and label, each a tracked read of the field. +/// @param prop The prop's name. +/// @param state The field. +/// @return The read, or empty for a prop the form does not fill. +[[nodiscard]] std::function formFilled(std::string const& prop, forms::FieldState const* state) { + if (prop == "value") { + return [state] { + forms::Encoding const& encoding = state->encoded().get(); + if (!encoding.has_value() || !encoding->has_value()) { + return Value{}; + } + return (*encoding)->value.isNull() ? jsonTextValue((*encoding)->json) : (*encoding)->value; + }; + } + if (prop == "errors") { + return [state] { + std::optional const& error = state->error().get(); + return error.has_value() ? Value{ValueList{Value{error->message}}} : Value{ValueList{}}; + }; + } + if (prop == "readonly") { + return [state] { return Value{state->readonly().get()}; }; + } + if (prop == "required") { + return [state] { return Value{state->required().get()}; }; + } + if (prop == "label") { + return [state] { return Value{state->label()}; }; + } + return {}; +} + +} // namespace + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): a prop's name, then its declared type. +CustomProp ScreenCore::componentProp(std::string const& prop, std::string const& type, std::function read) { + if (type == "bool") { + return CustomProp{ + .name = prop, + .value = slotProp([this, read = std::move(read)] { return boolOf(read(), session.formatting()); }), + }; + } + if (type == "number") { + return CustomProp{ + .name = prop, + .value = slotProp([read = std::move(read)] { return componentNumber(read()); }), + }; + } + return CustomProp{ + .name = prop, + .value = slotProp( + [this, read = std::move(read), type] { return componentText(read(), type, session.formatting()); }), + }; +} + +void ScreenCore::changeField(forms::FieldState& state, forms::FieldSpec const& spec, std::string const& path, + std::string_view valueType, std::string const& payload) { + auto wire = changeWire(payload, valueType); + // A base64 member holds a file's bytes, which a document moves inline only under the session's cap. + if (std::size_t const cap = session.options().maxInlineFileBytes; + wire && spec.bytes && wire->is_string() && base64Size(wire->get_string()) > cap) { + report(path, "field " + spec.name + ": " + std::to_string(base64Size(wire->get_string())) + + " bytes is over the " + std::to_string(cap) + " inline cap"); + return; + } + if (wire) { + if (auto edited = state.edit(*wire); !edited) { + wire = std::unexpected(edited.error()); + } + } + if (!wire) { + report(path, "field " + spec.name + ": the component's change does not decode: " + wire.error()); + } +} + +Node ScreenCore::fieldComponent(forms::FieldView const& view, DocNode const& overlay, LowerCtx const& ctx) { + std::string const name{overlay.name("component")}; + // A loaded document's field component is declared, with a `value` prop and a `change` event. + Component const& component = _doc->components.at(name); + forms::FieldState* const state = &view.state(); + Custom spec{ + .name = name, + .fallback = view.defaultControl(), + .props = {}, + .minVersion = + static_cast(std::clamp(component.version, 0, std::numeric_limits::max())), + .onEvent = {}, + }; + for (auto const& [prop, type] : component.props) { + if (prop == "value" && type == "json") { + // The wire JSON itself, so an object's or a collection's every digit reaches the component. + spec.props.push_back(CustomProp{ + .name = prop, + .value = slotProp([state] { + forms::Encoding const& encoding = state->encoded().get(); + return encoding.has_value() && encoding->has_value() ? (*encoding)->json : std::string{"null"}; + }), + }); + continue; + } + std::function read = formFilled(prop, state); + if (!read) { + ExprPtr given; + for (DocNodePtr const& record : overlay.partList("props")) { + if (ExprPtr const expr = record->prop(prop)) { + given = expr; + } + } + read = [scope = ctx.scope, bindings = ctx.bindings, given] { + return given ? evalIn(*scope, bindings.get(), given) : Value{}; + }; + } + spec.props.push_back(componentProp(prop, type, std::move(read))); + } + spec.onEvent = [this, state, path = overlay.path, fieldSpec = &view.spec(), + valueType = component.props.at("value")](std::string const& event, std::string const& payload) { + if (event == "change") { + changeField(*state, *fieldSpec, path, valueType, payload); + } + }; + return ui::custom(std::move(spec)); +} + +// Every call goes through the alias's channel, bound for its current instance when the call is made. +forms::Submitter ScreenCore::aliasCalls(ModelAlias* alias) { + return [this, alias](std::string_view actionId, std::string const& body) -> async::Completion { + std::shared_ptr const channel = channelOf(*alias, *this); + if (channel == nullptr) { + auto [failed, promise] = async::Completion::makeSettleable(&runtime().owner()); + promise.reject(std::make_exception_ptr(std::runtime_error{"the node's model alias is not bound"})); + return std::move(failed); + } + return channel->execute(std::string{actionId}, body, CallOptions{}); + }; +} + +// The calls of a form, collection or wizard: a success other than of @p read, the collection's own query, tells the +// session, which applies the action's effects, as a mutation's success does. +forms::Submitter ScreenCore::aliasSubmits(ModelAlias* alias, std::string read) { + return [this, alias, call = aliasCalls(alias), read = std::move(read)]( + std::string_view actionId, std::string body) -> async::Completion { + async::Completion completion = call(actionId, std::move(body)); + if (actionId != read) { + completion.then([this, alive = std::weak_ptr{_alive}, alias, typeId = alias->decl->type, + action = std::string{actionId}](std::string const& reply) { + if (alive.expired()) { + return; + } + auto json = parseJson(reply); + auto value = json ? valueFromJson(*json) : std::unexpected(json.error()); + std::string const token = runtime().untracked([&] { return alias->token->get(); }); + session.actionSucceeded(typeId, action, value ? *value : Value{}, ReplyUse::Applied, token); + }); + } + return completion; + }; +} + +// The session's locale, translations, display zone and date patterns, as every form the engine builds here reads them. +forms::FormSessionOptions ScreenCore::engineOptions() const { + FormatContext const& format = session.formatting(); + forms::FormSessionOptions options{}; + options.locale = withoutGrouping(format.numeric); + options.bcp47 = format.locale; + options.translations = format.translations; + options.displayOffsetMinutes = format.utcOffsetMinutes; + options.datePattern = format.datePattern; + options.dateTimePattern = format.dateTimePattern; + return options; +} + +// Keeps a form's, collection's or wizard's number locale, date patterns, translations and locale at the session's +// current formatting, so its field texts follow a `setLocale` or `setTranslations` without a remount. The +// engine's number locale holds views into the facts it was given, so the effect also holds the facts it last applied. +void ScreenCore::followFormatting(ElementState& element, RtScope& scope) { + auto const held = std::make_shared>(); + forms::FormSession* const form = element.form.get(); + forms::CollectionSession* const collection = element.collection.get(); + forms::WizardSession* const wizard = element.wizard.get(); + scope.nodes.effect([this, held, form, collection, wizard] { + std::shared_ptr const format = session.formattingHandle(); + runtime().untracked([&] { + render::NumericLocale const locale = withoutGrouping(format->numeric); + if (form != nullptr) { + form->setFormat(locale, format->datePattern, format->dateTimePattern); + form->setTranslations(format->translations, format->locale); + } + if (collection != nullptr) { + collection->setFormat(locale, format->datePattern, format->dateTimePattern); + collection->setTranslations(format->translations, format->locale); + } + if (wizard != nullptr) { + wizard->setFormat(locale, format->datePattern, format->dateTimePattern); + wizard->setTranslations(format->translations, format->locale); + } + *held = format; + }); + }); +} + +// Builds a collection's or wizard's session when its element is declared. The node's `action` is the collection's +// query or the wizard's first step; the catalog answers the document for it, and every call (the query, the actions, +// every step's submission) goes through the node's model alias. +void ScreenCore::wireComposite(ElementState& element) { + DocNode const& node = *element.node; + RtScope& scope = *element.scope; + bool const collection = node.kind == "collection"; + std::string const action{node.name("action")}; + Catalog const& catalog = session.options().catalog; + auto const& lookup = collection ? catalog.view : catalog.wizard; + std::optional const document = lookup ? lookup(action) : std::nullopt; + if (!document.has_value()) { + report(node.path, std::string{"no "} + (collection ? "view" : "wizard") + " document for `" + action + + "`: the catalog has none for a `" + node.kind + "` to build from"); + return; + } + NameRef const* const alias = scope.find(node.name("model")); + if (alias == nullptr || alias->model == nullptr) { + report(node.path, "`" + std::string{node.name("model")} + "` is not a model alias"); + return; + } + forms::SchemaLookup const schemas = catalog.schema ? forms::SchemaLookup{catalog.schema} : forms::SchemaLookup{}; + forms::Submitter const call = aliasCalls(alias->model); + if (collection) { + auto model = forms::CollectionModel::fromSchema(*document); + if (!model) { + report(node.path, "the collection of `" + action + "` does not build: " + model.error().path + ": " + + model.error().message); + return; + } + if (model->query() != action) { + report(node.path, "the view document of `" + action + "` lists `" + std::string{model->query()} + "`"); + return; + } + std::string query{model->query()}; + element.collection = std::make_unique(runtime(), *std::move(model), schemas, + aliasSubmits(alias->model, std::move(query)), + call, engineOptions()); + followFormatting(element, scope); + wireCollectionTable(element, alias->model->decl->type); + return; + } + // The wizard's id, the stem of its translation keys, is the action it starts with. + auto model = forms::WizardModel::fromSchema(action, *document); + if (!model) { + report(node.path, + "the wizard of `" + action + "` does not build: " + model.error().path + ": " + model.error().message); + return; + } + if (model->steps().front().action != action) { + report(node.path, + "the wizard document of `" + action + "` starts with `" + model->steps().front().action + "`"); + return; + } + try { + element.wizard = std::make_unique(runtime(), *std::move(model), schemas, + aliasSubmits(alias->model), call, engineOptions()); + followFormatting(element, scope); + } catch (std::invalid_argument const& error) { + report(node.path, error.what()); + } +} + +// The presentation keys a form, a collection and a wizard share, but the title: the label of the explicit-mode button +// and the status line naming it, bound in the node's scope; whether the status line shows, the grid's columns and the +// field layout and the inline caption column's width, as read at load. +void ScreenCore::presentForm(DocNode const& node, LowerCtx const& ctx, forms::FormViewOptions& options) { + if (ExprPtr const label = node.prop("submitLabel")) { + options.submitLabel = bindProp(ctx, label, std::string{}, stringOf); + } + if (auto const shown = node.flags.find("showStatus"); shown != node.flags.end()) { + options.showStatus = shown->second; + } + if (ExprPtr const columns = node.prop("columns"); columns != nullptr && columns->literal.asInt() != nullptr) { + options.gridColumns = static_cast(*columns->literal.asInt()); + options.flatGridColumns = options.gridColumns; + } + if (node.name("fieldLayout") == "inline") { + options.fieldLayout = forms::FieldLayout::Inline; + } + // The loader has checked `captionWidth` is a literal integer. + if (ExprPtr const width = node.prop("captionWidth")) { + options.inlineLabelWidth = static_cast(*width->literal.asInt()); + } +} + +Node ScreenCore::lowerComposite(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + // The editor's and the steps' titles are the dialog's and the header's; the forms do not repeat them. A `title` + // replaces the view's own heading. + forms::FormViewOptions form{}; + form.showTitle = false; + presentForm(node, ctx, form); + Prop title = bindProp(ctx, node.prop("title"), std::string{}, stringOf); + Node view; + if (element != nullptr && element->collection != nullptr) { + forms::CollectionViewOptions options{}; + options.form = std::move(form); + options.title = std::move(title); + // The rows are a table as every other table of the screen is. + if (element->rowsTable != nullptr) { + options.chrome.rows = [this, ctx, element](forms::CollectionSession& /*collection*/, + std::function const& buttons) { + return lowerCollectionRows(*element, ctx, buttons); + }; + } + view = forms::collectionView(*element->collection, std::move(options)); + } else if (element != nullptr && element->wizard != nullptr) { + forms::WizardViewOptions options{}; + options.form = std::move(form); + options.title = std::move(title); + view = forms::wizardView(*element->wizard, options); + } else { + return ui::text(Text{.text = std::string{node.name("action")}, .role = TextRole::Muted}); + } + Column column{.children = {std::move(view)}}; + commonOf(node, ctx, element, column.common); + return ui::column(std::move(column)); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): an overlay's scope, content, actions and keys are one lowering. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): an overlay's scope, content, actions and keys are one lowering. +Node ScreenCore::lowerDialog(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + Prop open = node.prop("open") ? bindProp(ctx, node.prop("open"), false, boolOf) + : slotProp([element] { return element->open.get(); }); + std::vector bodyContent; + for (DocNodePtr const& child : node.nodes("children")) { + bodyContent.push_back(child.get()); + } + int const bodyGap = + node.prop("gap") ? static_cast(intOf(once(ctx, node.prop("gap")), kDialogGap)) : kDialogGap; + LayoutHints const bodyHints = holderHints(bodyContent, node.scope ? &*node.scope : nullptr, ctx); + Node body = lazy( + [this, ctx, &node, element, bodyGap] -> Node { + auto const inner = std::make_shared(*this, ctx.scope, nullptr, ctx.scope->nodes.depth() + 2); + inner->owner = element; + addPending(1); + inner->submitted = &element->submitted; + inner->showErrors = std::string{node.name("showErrors")}; + std::vector content; + for (DocNodePtr const& child : node.nodes("children")) { + content.push_back(child.get()); + } + std::vector lists; + for (std::string_view const key : {"default", "cancel"}) { + if (Commands const* const commands = node.event(key)) { + lists.push_back(commands); + } + } + for (DocNodePtr const& action : node.partList("actions")) { + if (Commands const* const commands = action->event("onClick")) { + lists.push_back(commands); + } + } + declare(*inner, node.scope ? &*node.scope : nullptr, content, lists); + element->inner.set(inner.get()); + LowerCtx const innerCtx{ + .scope = inner, + .bindings = ctx.bindings, + .boundary = ctx.boundary, + .listGap = bodyGap, + }; + std::vector children; + children.reserve(content.size()); + for (DocNode const* const child : content) { + children.push_back(lower(*child, innerCtx)); + } + // The overlay's actions end its scoped content, so they bind in its scope; the mount puts them in its + // footer. + if (ActionModels actions = lowerActionParts(node.partList("actions"), innerCtx); !actions.empty()) { + children.push_back(actionBarOf(std::move(actions))); + } + std::vector keys; + if (Commands const* const commands = node.event("default")) { + keys.push_back(KeyBinding{ + .chord = "Enter", + .onPress = [this, innerCtx, commands] { runEvent(commands, innerCtx, Value{}); }, + }); + } + if (Commands const* const commands = node.event("cancel")) { + keys.push_back(KeyBinding{ + .chord = "Esc", + .onPress = [this, innerCtx, commands] { runEvent(commands, innerCtx, Value{}); }, + }); + } + fillHolder(children, node.path); + return holding(std::move(children), inner, std::move(keys), bodyGap); + }, + bodyHints); + Action onDismiss = [this, ctx, element, commands = node.event("onDismiss")] { + session.asUser([&] { + session.noteWrite(); + element->open.set(false); + }); + runEvent(commands, ctx, Value{}); + }; + if (node.kind == "drawer") { + ExprPtr const side = node.prop("side"); + Drawer spec{ + .open = std::move(open), + .title = bindProp(ctx, node.prop("title"), std::string{}, stringOf), + .description = bindProp(ctx, node.prop("description"), std::string{}, stringOf), + .child = std::move(body), + .onDismiss = std::move(onDismiss), + .side = side && textOf(once(ctx, side), ctx.scope->formatting()) == "start" ? Side::Start : Side::End, + .headNote = bindProp(ctx, node.prop("headNote"), std::string{}, stringOf), + .footerNote = bindProp(ctx, node.prop("footerNote"), std::string{}, stringOf), + .closeButton = bindProp(ctx, node.prop("closeButton"), false, boolOf), + .dismissLabel = bindProp(ctx, node.prop("dismissLabel"), std::string{"Close"}, stringOf), + }; + if (ExprPtr const spans = node.prop("descriptionSpans")) { + spec.descriptionSpans = spansProp(ctx, spans); + } + commonOf(node, ctx, element, spec.common); + return ui::drawer(std::move(spec)); + } + Dialog spec{ + .open = std::move(open), + .title = bindProp(ctx, node.prop("title"), std::string{}, stringOf), + .description = bindProp(ctx, node.prop("description"), std::string{}, stringOf), + .child = std::move(body), + .onDismiss = std::move(onDismiss), + .common = {}, // NOLINT(readability-trailing-comma): the comma ends the designator, not the empty braces. + .sheet = bindProp(ctx, node.prop("sheet"), false, boolOf), + .dismissLabel = bindProp(ctx, node.prop("dismissLabel"), std::string{"Close"}, stringOf), + .headNote = bindProp(ctx, node.prop("headNote"), std::string{}, stringOf), + .footerNote = bindProp(ctx, node.prop("footerNote"), std::string{}, stringOf), + .closeButton = bindProp(ctx, node.prop("closeButton"), false, boolOf), + }; + if (ExprPtr const spans = node.prop("descriptionSpans")) { + spec.descriptionSpans = spansProp(ctx, spans); + } + commonOf(node, ctx, element, spec.common); + return ui::dialog(std::move(spec)); +} + +Node ScreenCore::lowerSwitch(DocNode const& node, LowerCtx const& ctx) { + std::vector whens; + Switch spec; + std::int64_t index = 0; + for (DocNodePtr const& part : node.partList("cases")) { + whens.push_back(part->prop("when")); + DocNode const* const casePart = part.get(); + std::vector caseContent; + for (DocNodePtr const& child : casePart->nodes("children")) { + caseContent.push_back(child.get()); + } + LayoutHints const caseHints = holderHints(caseContent, casePart->scope ? &*casePart->scope : nullptr, ctx); + spec.cases.push_back(SwitchCase{ + .key = Key{index++}, + .node = lazy( + [this, ctx, casePart, caseGap = ctx.listGap] -> Node { + auto const inner = + std::make_shared(*this, ctx.scope, nullptr, ctx.scope->nodes.depth() + 2); + std::vector content; + for (DocNodePtr const& child : casePart->nodes("children")) { + content.push_back(child.get()); + } + declare(*inner, casePart->scope ? &*casePart->scope : nullptr, content, {}); + LowerCtx const innerCtx{ + .scope = inner, + .bindings = ctx.bindings, + .boundary = ctx.boundary, + .listGap = caseGap, + }; + std::vector children; + children.reserve(content.size()); + for (DocNode const* const child : content) { + children.push_back(lower(*child, innerCtx)); + } + fillHolder(children, casePart->path); + return holding(std::move(children), inner, {}, caseGap); + }, + caseHints), + }); + } + spec.selector = slotProp( + [scope = ctx.scope, bindings = ctx.bindings, selected = node.prop("on"), whens = std::move(whens)] { + Value const value = evalIn(*scope, bindings.get(), selected); + for (std::size_t at = 0; at < whens.size(); ++at) { + if (evalIn(*scope, bindings.get(), whens.at(at)) == value) { + return Key{static_cast(at)}; + } + } + return Key{std::int64_t{-1}}; + }); + auto const fallback = node.nodes("default"); + spec.fallback = fallback.empty() ? Node{} : lowerAll(fallback, ctx, ctx.listGap); + commonOf(node, ctx, nullptr, spec.common); + return ui::switchOf(std::move(spec)); +} + +// The tab a bound `selected` names. A value that names no tab shows the first, and is reported once. +Prop ScreenCore::controlledTabSelection(DocNode const& node, LowerCtx const& ctx, ExprPtr const& selected, + std::shared_ptr> const& ids) { + auto const unknownReported = std::make_shared(false); + return Prop{[this, scope = ctx.scope, bindings = ctx.bindings, selected, ids, unknownReported, + path = pointerAppend(node.path, "selected")] -> std::size_t { + Value const value = evalIn(*scope, bindings.get(), selected); + std::string const* const named = value.asString(); + auto const found = named == nullptr ? ids->end() : std::ranges::find(*ids, *named); + if (found != ids->end()) { + return static_cast(std::distance(ids->begin(), found)); + } + if (!*unknownReported) { + *unknownReported = true; + report(path, canonicalJson(value) + " names no tab; the first is shown"); + } + return 0; + }}; +} + +// A document names tabs by id; the view tree by index, so the ids map to indices once. A bound `selected` is the +// controlled index: a pick runs `onChoose` and the page follows `selected` alone. Without it the node keeps the +// user's pick itself, as a bound index too, whose page follows the pick: a constant would move only the highlight. +Node ScreenCore::lowerTabs(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + Tabs spec; + auto const ids = std::make_shared>(); + for (DocNodePtr const& tab : node.partList("tabs")) { + auto const nodes = tab->nodes("children"); + ids->push_back(tab->id); + spec.tabs.push_back(Tab{ + .label = bindProp(ctx, tab->prop("label"), std::string{}, stringOf), + .node = nodes.empty() ? Node{} : lowerAll(nodes, ctx), + }); + } + spec.moreLabel = bindProp(ctx, node.prop("moreLabel"), std::string{"More"}, stringOf); + if (ExprPtr const inset = node.prop("inset")) { + spec.inset = static_cast(intOf(once(ctx, inset), 0)); + } + if (ExprPtr const pageInset = node.prop("pageInset")) { + spec.pageInset = static_cast(intOf(once(ctx, pageInset), 0)); + } + spec.stripSurface = std::string{node.name("stripSurface")}; + ExprPtr const selected = node.prop("selected"); + Commands const* const onChoose = node.event("onChoose"); + bool const controlled = selected && (selected->kind != ExprKind::Literal || !selected->literal.isNull()); + auto const picked = std::make_shared>(runtime(), std::size_t{0}); + spec.selected = controlled ? controlledTabSelection(node, ctx, selected, ids) + : Prop{[picked] { return picked->get(); }}; + spec.onSelect = [this, ctx, onChoose, ids, picked, controlled, element](std::size_t index) { + if (!controlled) { + picked->set(index); + if (element != nullptr && index < ids->size()) { + element->draft.set(Value{ids->at(index)}); + } + } + if (onChoose != nullptr && index < ids->size()) { + runEvent(onChoose, ctx, Value{ids->at(index)}); + } + }; + commonOf(node, ctx, element, spec.common); + return ui::tabs(std::move(spec)); +} + +// Focuses the declaration the command's target resolved to: of several candidates (cases of one switch), the one +// that is mounted. Each candidate is keyed by the command's own enclosing row keys, as many as enclose the +// candidate; with `row`, the innermost of them is the row's key instead. +bool ScreenCore::focusTarget(Command const& command, RtScope const& scope, Bindings const* bindings) { + if (!focusElement) { + return false; + } + auto const found = _doc->focusTargets.find(command.path); + if (found == _doc->focusTargets.end()) { + return focusElement(command.target); + } + FocusPlace const place = focusPlace(scope); + std::optional row; + if (found->second.row) { + Value const value = evalIn(scope, bindings, command.extra); + if (value.isNull()) { + return false; + } + row = canonicalJson(valueOfKey(keyOf(value))); + } + for (FocusCandidate const& candidate : found->second.candidates) { + std::size_t const kept = row ? candidate.rows - 1 : candidate.rows; + if (candidate.rows == 0 && row) { + continue; + } + if (kept > place.rows.size()) { + continue; + } + FocusPlace candidatePlace{ + .prefix = place.prefix, + .rows = {place.rows.begin(), std::next(place.rows.begin(), static_cast(kept))}, + }; + if (row) { + candidatePlace.rows.push_back(*row); + } + if (focusElement(focusKey(candidatePlace, candidate.path))) { + return true; + } + } + return false; +} + +std::shared_ptr ScreenCore::rowScope(DocNode const& node, LowerCtx const& ctx, + reactive::Signal const& row, + std::vector const& content, std::string key) { + auto scope = std::make_shared(*this, ctx.scope, &row, ctx.scope->nodes.depth() + 2); + scope->rowKey = std::move(key); + declare(*scope, node.scope ? &*node.scope : nullptr, content, {}); + return scope; +} + +[[nodiscard]] bool givesDisplay(DocNode const& part) { + return part.prop("decimals") != nullptr || part.prop("labels") != nullptr || part.names.contains("rounding") || + part.names.contains("empty") || part.names.contains("unit") || part.names.contains("date") || + part.flags.contains("padPlaces") || part.flags.contains("grouping"); +} + +[[nodiscard]] table::ColumnDisplay displayOf(DocNode const& part, table::ColumnDisplay display, + std::function const& read) { + if (ExprPtr const decimals = part.prop("decimals")) { + constexpr std::int64_t kMostPlaces = 18; + Value const places = read(decimals); + if (std::int64_t const* const count = places.asInt(); + count != nullptr && *count >= 0 && *count <= kMostPlaces) { + display.decimals = static_cast(*count); + } + } + if (auto const rounding = part.names.find("rounding"); rounding != part.names.end()) { + display.rounding = rounding->second == "halfUp" ? table::Rounding::HalfUp : table::Rounding::HalfEven; + } + if (auto const pad = part.flags.find("padPlaces"); pad != part.flags.end()) { + display.padPlaces = pad->second; + } + if (auto const grouping = part.flags.find("grouping"); grouping != part.flags.end()) { + display.grouping = grouping->second; + } + for (auto [key, member] : + {std::pair{"empty", &display.empty}, std::pair{"unit", &display.unit}, std::pair{"date", &display.date}}) { + if (auto const found = part.names.find(std::string_view{key}); found != part.names.end()) { + *member = found->second; + } + } + if (ExprPtr const labels = part.prop("labels")) { + display.labels.clear(); + Value const list = read(labels); + for (Value const& item : list.asList() != nullptr ? *list.asList() : ValueList{}) { + Value const* const operand = item.field("operand"); + Value const* const text = item.field("text"); + if (operand == nullptr || text == nullptr || text->asString() == nullptr) { + continue; + } + display.labels.push_back(table::ValueLabel{ + .operand = operand->asString() != nullptr ? *operand->asString() : canonicalJson(*operand), + .text = *text->asString()}); + } + } + return display; +} + +[[nodiscard]] table::Cell cellOfRecord(Value const* value, table::TableColumn const& column, + table::UnitRegistry const* units) { + using table::ColumnKind; + if (value == nullptr || value->isNull()) { + return std::monostate{}; + } + bool const measure = column.info.kind == ColumnKind::Measure; + if (std::int64_t const* const integer = value->asInt()) { + return *integer; + } + if (Decimal const* const decimal = value->asDecimal()) { + if (measure) { + return table::Measure{.amount = decimal->value, .unit = table::kUnknownUnit}; + } + return decimal->value; + } + if (bool const* const flag = value->asBool()) { + return *flag; + } + if (Quantity const* const quantity = value->asQuantity()) { + if (measure) { + std::optional const unit = units != nullptr ? units->find(quantity->unit) : std::nullopt; + return table::Measure{.amount = quantity->value, .unit = unit.value_or(table::kUnknownUnit)}; + } + return quantity->value; + } + if (time::DateTime const* const instant = value->asTimestamp()) { + return std::int64_t{ + std::chrono::duration_cast(instant->value.time_since_epoch()).count()}; + } + if (std::string const* const text = value->asString()) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `text->size() == 10` is the previous operand of this condition, so indices 4 and 7 are in range + if (column.info.kind == ColumnKind::Date && text->size() == 10 && (*text)[4] == '-' && (*text)[7] == '-') { + int year = 0; + unsigned month = 0; + unsigned day = 0; + char const* const cursor = text->data(); + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic): from_chars takes a pointer range; the ranges are fixed offsets into the 10-character `YYYY-MM-DD` text the size and separator checks above validated + bool const read = std::from_chars(cursor, cursor + 4, year).ec == std::errc{} && + std::from_chars(cursor + 5, cursor + 7, month).ec == std::errc{} && + std::from_chars(cursor + 8, cursor + 10, day).ec == std::errc{}; + // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic) + std::chrono::year_month_day const date{std::chrono::year{year}, std::chrono::month{month}, + std::chrono::day{day}}; + if (read && date.ok()) { + return std::int64_t{std::chrono::sys_days{date}.time_since_epoch().count()}; + } + } + return *text; + } + return canonicalJson(*value); +} + +[[nodiscard]] table::TableColumn columnFor(Value const& value, table::ColumnDisplay const& display) { + using table::ColumnKind; + ColumnKind const kind = + value.asInt() != nullptr ? ColumnKind::Integer + // NOLINTBEGIN(readability-avoid-nested-conditional-operator): a flat pick over the value's kind, one test per line in the order the kinds are tried + : value.asDecimal() != nullptr ? ColumnKind::Decimal + : value.asQuantity() != nullptr ? ColumnKind::Decimal + : value.asBool() != nullptr ? ColumnKind::Bool + : value.asTimestamp() != nullptr ? ColumnKind::DateTime + : ColumnKind::Text; + // NOLINTEND(readability-avoid-nested-conditional-operator) + return table::TableColumn{.info = {.id = {}, .kind = kind}, .display = display}; +} + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_grid_detail.hpp b/src/ui/interpreter_grid_detail.hpp new file mode 100644 index 000000000..ede16bfc7 --- /dev/null +++ b/src/ui/interpreter_grid_detail.hpp @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 + +// What the interpreter's grid lowering shares: the grid tables and the helpers over them. + +#pragma once + +#include +#include +#include +#include + +#include "interpreter_table_detail.hpp" + +namespace morph::ui::detail { + +/// A grid of a form: the grid it shows, and its status line's message, held for 6 s as a table's is. +struct GridTable { + explicit GridTable(reactive::Runtime& runtime) + : config{runtime}, + filterVersion{runtime, std::uint64_t{0}}, + message{runtime, std::string{}}, + entries{runtime, std::vector{}} {} + + GridTable(GridTable const&) = delete; + GridTable& operator=(GridTable const&) = delete; + GridTable(GridTable&&) = delete; + GridTable& operator=(GridTable&&) = delete; + ~GridTable() = default; + + /// The grid: its source, its controller and its table node. A fixed grid's source is `fixed`, and `grid.source` + /// is null. + FormGrid grid; + /// A fixed grid's source; null for a grid of a form. + std::shared_ptr fixed; + /// The summary rows over the grid's rows, which the mount is handed in their place; null for a grid with no + /// summaries and no group. + std::shared_ptr summaries; + /// Whether a `group` part groups the rows. + bool grouped = false; + /// Each run of the view, by ordinal: the source's run index and how many runs of that index came before it in the + /// view (rows added while sorted show at the end, after their run). + std::vector> runOrder; + /// The places a summary of each edit column shows at, by column id: its member's. + std::map, std::less<>> places; + /// The table's columns, one per grid column. + std::vector shown; + /// The table's configuring: its columns, layout, menus and filters. + TableConfig config; + /// Sets the slots of `config` a mount owns (`filterTarget`, `heldCell`, `gather`); run before each mount begins, + /// so a mount after an unmount has them again. + std::function setMountSlots; + /// The filters the user set, and a count that moves with each. + table::FilterSpec filter; + reactive::Signal filterVersion; + /// The status line's message and the choices it offers, with what each runs. + reactive::Signal message; + reactive::Signal> entries; + std::map, std::less<>> entryHandlers; + reactive::TimerHandle messageTimer; + /// Last, so what the message's timer posts does nothing once the grid is gone. + async::CallbackScope scope; +}; + +std::vector> gridRuns(GridTable& held); + +RowRecord gridHeading(GridTable& held, std::size_t ordinal); + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_lowering.cpp b/src/ui/interpreter_lowering.cpp new file mode 100644 index 000000000..320ce71be --- /dev/null +++ b/src/ui/interpreter_lowering.cpp @@ -0,0 +1,1463 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Lowering a document's nodes to widgets. + +#include "interpreter_detail.hpp" + +namespace morph::ui::detail { + +void ScreenCore::fillHolder(std::vector& children, std::string const& path) { + for (Node& child : children) { + if (layoutHintsOf(child).width.kind == Sizing::Kind::Percent) { + report(path, kPercentInHolder); + child = withWidth(child, Sizing::stretch(1)); + } + } +} + +LayoutHints ScreenCore::nodeHints(DocNode const& node, std::set> const& own, + LowerCtx const& ctx) { + LayoutHints hints; + if (ExprPtr const sizing = node.prop("sizing")) { + if (sizing->kind != ExprKind::Literal && readsAny(sizing, own)) { + report(sizing->path, + "this sizing reads a name the case declares, so the case is held at its " + "content size"); + } else { + Value const value = once(ctx, sizing); + Value const* const width = value.field("width"); + Value const* const height = value.field("height"); + if (width != nullptr || height != nullptr) { + hints.width = width != nullptr && isSizing(*width) ? sizingOf(*width) : Sizing::content(); + hints.height = height != nullptr && isSizing(*height) ? sizingOf(*height) : Sizing::content(); + } else if (isSizing(value)) { + hints.width = sizingOf(value); + } + } + } + return hints; +} + +LayoutHints ScreenCore::holderHints(std::span content, ScopeDecl const* decl, + LowerCtx const& ctx) { + std::set> own; + for (DocNode const* const node : content) { + collectIds(*node, own); + } + if (decl != nullptr) { + for (ModelDecl const& model : decl->models) { + own.insert(model.name); + } + for (StateDecl const& state : decl->state) { + own.insert(state.name); + } + for (LetDecl const& let : decl->lets) { + own.insert(let.name); + } + for (QueryDecl const& query : decl->queries) { + own.insert(query.name); + } + for (MutationDecl const& mutation : decl->mutations) { + own.insert(mutation.name); + } + } + std::vector widths; + std::vector heights; + for (DocNode const* const node : content) { + LayoutHints const hints = nodeHints(*node, own, ctx); + widths.push_back(hints.width); + heights.push_back(hints.height); + } + LayoutHints out; + out.width = holderSizing(widths); + out.height = holderSizing(heights); + return out; +} + +// NOLINTBEGIN(misc-no-recursion): a menu nests, and lowering descends the document. +Node ScreenCore::lower(DocNode const& node, LowerCtx const& ctx) { + if (recording) { + if (loweredNodes.size() >= kPruneLoweredAt && loweredNodes.size() % kPruneLoweredAt == 0) { + std::erase_if(loweredNodes, [](LoweredNode const& entry) { return entry.scope.expired(); }); + } + loweredNodes.push_back(LoweredNode{.node = &node, .scope = ctx.scope, .bindings = ctx.bindings}); + } + // Only a switch reads the gap of the list around it; every other kind's children are held by a holder that sets + // their gap, so none sees its grandparent's. + if (ctx.listGap != 0 && node.kind != "switch") { + LowerCtx plain = ctx; + plain.listGap = 0; + return lowerKind(node, plain, elementFor(*ctx.scope, node)); + } + return lowerKind(node, ctx, elementFor(*ctx.scope, node)); +} + +Prop ScreenCore::roleProp(LowerCtx const& ctx, ExprPtr const& expr) { + if (!expr || expr->kind == ExprKind::Literal) { + return bindProp(ctx, expr, TextRole::Normal, roleOf); + } + return slotProp([this, scope = ctx.scope, bindings = ctx.bindings, expr] { + Value const value = evalIn(*scope, bindings.get(), expr); + std::optional const role = roleNamed(textOf(value, scope->formatting())); + if (!role) { + report(expr->path, "role is " + canonicalJson(value) + "; " + std::string{kRoleNames}); + } + return role.value_or(TextRole::Normal); + }); +} + +Prop ScreenCore::surfaceOf(DocNode const& node, LowerCtx const& ctx) { + ExprPtr const expr = node.prop("surface"); + auto nameOf = [this, path = pointerAppend(node.path, "surface")](Value const& value) -> std::string { + if (std::string const* const name = value.asString()) { + return *name; + } + if (!value.isNull()) { + report(path, "a surface is the name of one; " + canonicalJson(value) + " is not a string"); + } + return {}; + }; + if (!expr || expr->kind == ExprKind::Literal) { + return expr ? Prop{nameOf(expr->literal)} : Prop{std::string{}}; + } + return slotProp([scope = ctx.scope, bindings = ctx.bindings, expr, nameOf = std::move(nameOf)] { + return nameOf(evalIn(*scope, bindings.get(), expr)); + }); +} + +KeyValueItem ScreenCore::keyValueItemOf(Value const& item, std::string const& path, RtScope const& scope) { + FormatContext const& format = scope.formatting(); + Value const* const label = item.field("label"); + Value const* const value = item.field("value"); + KeyValueItem out{ + .label = label == nullptr ? std::string{} : textOf(*label, format), + .value = value == nullptr ? std::string{} : textOf(*value, format), + }; + if (Value const* const spans = item.field("spans")) { + bool dropped = false; + bool badTone = false; + out.spans = spansOf(*spans, format, dropped, &badTone); + if (dropped) { + report(path, kSpansReason); + } + if (badTone) { + report(path, kSpanToneReason); + } + } + if (Value const* const tone = item.field("tone")) { + std::optional const named = toneNamed(*tone); + if (!named) { + report(path, "an item's tone is " + canonicalJson(*tone) + "; " + std::string{kToneNames}); + } + out.tone = named.value_or(Tone::Neutral); + } + return out; +} + +// A group needs no widget of its own: it lowers to kinds every backend has, so the view tree and the contract do not +// change. Its description is a line read in order after its children, since `Common` carries no accessible +// description. +Node ScreenCore::lowerGroup(DocNode const& node, LowerCtx const& ctx, ElementState* element, + std::vector children) { + Text legend{ + .text = bindProp(ctx, node.prop("label"), std::string{}, stringOf), + .role = TextRole::Label, + }; + legend.field.required = bindProp(ctx, node.prop("required"), false, boolOf); + std::vector column; + column.reserve(children.size() + 3); + column.push_back(ui::text(std::move(legend))); + std::ranges::move(children, std::back_inserter(column)); + if (ExprPtr const description = node.prop("description")) { + Text line{.text = bindProp(ctx, description, std::string{}, stringOf), .role = TextRole::Muted}; + line.common.visible = slotProp([scope = ctx.scope, bindings = ctx.bindings, description] { + return !textOf(evalIn(*scope, bindings.get(), description), scope->formatting()).empty(); + }); + column.push_back(ui::text(std::move(line))); + } + // The shown errors, one line each: a check that targets the group shows its message here. + auto const shown = [this, element, scope = ctx.scope, bindings = ctx.bindings, errors = node.prop("errors")] { + return stringsOf(element != nullptr ? elementValue(*element, "shownErrors") + : evalIn(*scope, bindings.get(), errors)); + }; + Text messages{ + .text = slotProp([shown] { + std::string joined; + for (std::string const& message : shown()) { + joined += (joined.empty() ? "" : "\n") + message; + } + return joined; + }), + .role = TextRole::Error, + }; + messages.common.visible = slotProp([shown] { return !shown().empty(); }); + column.push_back(ui::text(std::move(messages))); + Column spec{ + .children = std::move(column), + .gap = static_cast(intOf(node.prop("gap") ? once(ctx, node.prop("gap")) : Value{}, 0)), + }; + commonOf(node, ctx, element, spec.common); + if (spec.common.a11y.role.empty()) { + spec.common.a11y.role = "group"; + } + bool const named = std::ranges::any_of(node.partList("a11y"), + [](DocNodePtr const& a11y) { return a11y->prop("name") != nullptr; }); + if (!named) { + spec.common.a11y.name = bindProp(ctx, node.prop("label"), std::string{}, stringOf); + } + return ui::column(std::move(spec)); +} + +Prop> ScreenCore::spansProp(LowerCtx const& ctx, ExprPtr const& expr) { + return slotProp>([this, scope = ctx.scope, bindings = ctx.bindings, expr] { + bool dropped = false; + bool badTone = false; + std::vector spans = + spansOf(evalIn(*scope, bindings.get(), expr), scope->formatting(), dropped, &badTone); + if (dropped) { + report(expr->path, kSpansReason); + } + if (badTone) { + report(expr->path, kSpanToneReason); + } + return spans; + }); +} + +// The size request: `sizing` (the width, or both dimensions), `alignSelf`, and the bounds. +void ScreenCore::layoutOf(DocNode const& node, LowerCtx const& ctx, LayoutHints& layout) { + if (ExprPtr const sizing = node.prop("sizing")) { + // The width, or both dimensions from a `{width, height}` record, one left out being content. The loader + // refuses a literal of another form; a computed one that is none is reported and lowers to content. + Value const value = once(ctx, sizing); + Value const* const width = value.field("width"); + Value const* const height = value.field("height"); + bool const record = width != nullptr || height != nullptr; + bool const valid = record ? (width == nullptr || isSizing(*width)) && (height == nullptr || isSizing(*height)) + : isSizing(value); + if (!valid) { + report(sizing->path, "sizing is " + canonicalJson(value) + + "; a sizing is \"content\", {\"fixed\": n}, {\"stretch\": w}, {\"percent\": n} " + "with n from 1 to 100, or a record of width and height of them"); + } else if (record) { + layout.width = width != nullptr ? sizingOf(*width) : Sizing::content(); + layout.height = height != nullptr ? sizingOf(*height) : Sizing::content(); + if (layout.height.kind == Sizing::Kind::Percent) { + report(sizing->path, kPercentPlaces); + layout.height = Sizing::content(); + } + } else { + layout.width = sizingOf(value); + } + } + if (std::string_view const placed = node.name("alignSelf"); !placed.empty()) { + layout.alignSelf = alignOf(placed); + } + layout.bleed = node.flag("bleed"); + // Literal integers, checked at load. + for (auto const& [key, bound] : { + std::pair{"minWidth", &LayoutHints::minWidth}, + std::pair{"maxWidth", &LayoutHints::maxWidth}, + std::pair{"minHeight", &LayoutHints::minHeight}, + std::pair{"maxHeight", &LayoutHints::maxHeight}, + }) { + if (ExprPtr const expr = node.prop(key); expr != nullptr && expr->literal.asInt() != nullptr) { + layout.*bound = static_cast(*expr->literal.asInt()); + } + } +} + +[[nodiscard]] FocusPlace focusPlace(RtScope const& scope) { + FocusPlace place; + for (RtScope const* current = &scope; current != nullptr; current = current->parent.get()) { + if (current->row != nullptr) { + place.rows.push_back(current->rowKeyNow ? current->rowKeyNow() : current->rowKey); + } + if (current->parent == nullptr) { + place.prefix = current->usePrefix; + } + } + std::ranges::reverse(place.rows); + return place; +} + +[[nodiscard]] std::string focusKey(FocusPlace const& place, std::string_view path) { + std::string key = place.prefix; + key += path; + for (std::string const& row : place.rows) { + key += '@'; + key += row; + } + return key; +} + +[[nodiscard]] std::string focusKeyOf(std::string_view path, RtScope const& scope) { + return focusKey(focusPlace(scope), path); +} + +void ScreenCore::commonOf(DocNode const& node, LowerCtx const& ctx, ElementState* element, Common& common) { + static_cast(element); + common.visible = bindProp(ctx, node.prop("visible"), true, boolOf); + common.enabled = bindProp(ctx, node.prop("enabled"), true, boolOf); + common.tooltip = bindProp(ctx, node.prop("tooltip"), std::string{}, stringOf); + layoutOf(node, ctx, common.layout); + common.testId = std::string{node.name("testId")}; + if (!node.id.empty()) { + // Under a scope whose row changes (a pooled table cell), the key follows the row it holds now. + bool live = false; + for (RtScope const* current = ctx.scope.get(); current != nullptr; current = current->parent.get()) { + live = live || static_cast(current->rowKeyNow); + } + if (live) { + common.focusId = + slotProp([scope = ctx.scope, path = node.path] { return focusKeyOf(path, *scope); }); + } else { + common.focusId = focusKeyOf(node.path, *ctx.scope); + } + } + common.surface = surfaceOf(node, ctx); + if (ExprPtr const autofocus = node.prop("autofocus")) { + common.autofocus = boolOf(once(ctx, autofocus), ctx.scope->formatting()); + } + for (DocNodePtr const& a11y : node.partList("a11y")) { + common.a11y.name = bindProp(ctx, a11y->prop("name"), std::string{}, stringOf); + common.a11y.role = std::string{a11y->name("role")}; + } + for (DocNodePtr const& drag : node.partList("drag")) { + ExprPtr const payload = drag->prop("payload"); + common.dragKey = + slotProp>([scope = ctx.scope, bindings = ctx.bindings, payload] -> std::optional { + Value const value = evalIn(*scope, bindings.get(), payload); + return value.isNull() ? std::nullopt : std::optional{keyOf(value)}; + }); + } + for (DocNodePtr const& drop : node.partList("drop")) { + ExprPtr const accepts = drop->prop("accepts"); + common.accepts = [this, scope = ctx.scope, bindings = ctx.bindings, accepts](Key const& key) { + if (!accepts) { + return true; + } + Value const accepted = runtime().untracked([&] { return evalIn(*scope, bindings.get(), accepts); }); + if (ValueList const* const items = accepted.asList()) { + return std::ranges::any_of(*items, [&](Value const& item) { return keyOf(item) == key; }); + } + return accepted.isNull() || keyOf(accepted) == key; + }; + common.onDrop = [this, ctx, commands = drop->event("onDrop")](Key const& key) { + runEvent(commands, ctx, valueOfKey(key)); + }; + } + for (auto const& [chord, commands] : node.keys) { + common.keys.push_back( + KeyBinding{.chord = chord, .onPress = [this, ctx, list = &commands] { runEvent(list, ctx, Value{}); }}); + } +} + +void ScreenCore::fieldOf(DocNode const& node, LowerCtx const& ctx, ElementState* element, FieldState& field) { + field.readonly = bindProp(ctx, node.prop("readonly"), false, boolOf); + field.required = bindProp(ctx, node.prop("required"), false, boolOf); + field.stale = bindProp(ctx, node.prop("stale"), false, boolOf); + if (element != nullptr) { + field.errors = slotProp>( + [this, scope = ctx.scope, element] { return stringsOf(elementValue(*element, "shownErrors")); }); + } else if (ExprPtr const errors = node.prop("errors")) { + field.errors = slotProp>([scope = ctx.scope, bindings = ctx.bindings, errors] { + return stringsOf(evalIn(*scope, bindings.get(), errors)); + }); + } + // A tone evaluates the value and is not an error: it changes the field's look and nothing of `valid`. + if (node.prop("description")) { + field.description = bindProp(ctx, node.prop("description"), std::string{}, stringOf); + } + if (node.prop("labelHint")) { + field.labelHint = bindProp(ctx, node.prop("labelHint"), std::string{}, stringOf); + } + if (ExprPtr const tone = node.prop("tone")) { + field.tone = slotProp([this, scope = ctx.scope, bindings = ctx.bindings, tone] { + Value const value = evalIn(*scope, bindings.get(), tone); + std::optional const named = toneNamed(value); + if (!named) { + report(tone->path, "tone is " + canonicalJson(value) + "; " + std::string{kToneNames}); + } + return named.value_or(Tone::Neutral); + }); + } +} + +MenuItem ScreenCore::menuItemOf(DocNode const& part, LowerCtx const& ctx) { + MenuItem item; + if (part.flag("separator")) { + item.separator = true; + return item; + } + item.label = bindProp(ctx, part.prop("label"), std::string{}, stringOf); + item.description = bindProp(ctx, part.prop("description"), std::string{}, stringOf); + item.visible = bindProp(ctx, part.prop("visible"), true, boolOf); + if (Commands const* const commands = part.event("onClick")) { + item.onSelect = [this, ctx, commands] { runEvent(commands, ctx, Value{}); }; + } + if (ExprPtr const icon = part.prop("icon")) { + item.icon = textOf(once(ctx, icon), ctx.scope->formatting()); + } + item.keys = std::string{part.name("keys")}; + if (ExprPtr const checked = part.prop("checked")) { + item.checked = slotProp>( + [scope = ctx.scope, bindings = ctx.bindings, checked] -> std::optional { + Value const value = evalIn(*scope, bindings.get(), checked); + bool const* const flag = value.asBool(); + return flag == nullptr ? std::nullopt : std::optional{*flag}; + }); + } + item.enabled = bindProp(ctx, part.prop("enabled"), true, boolOf); + return item; +} + +// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. +std::vector ScreenCore::menuItems(std::span parts, LowerCtx const& ctx) { + std::vector items; + for (DocNodePtr const& part : parts) { + MenuItem item = menuItemOf(*part, ctx); + if (!item.separator) { + item.items = menuItems(part->partList("items"), ctx); + } + items.push_back(std::move(item)); + } + return items; +} + +// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. +std::vector ScreenCore::lowerHeadMenu(std::span parts, LowerCtx const& ctx) { + std::vector models; + models.reserve(parts.size()); + for (DocNodePtr const& part : parts) { + models.push_back(HeadMenuModel{ + .id = part->id, + .path = part->path, + .item = menuItemOf(*part, ctx), + .items = lowerHeadMenu(part->partList("items"), ctx), + }); + } + return models; +} + +std::vector ScreenCore::lowerHeadTools(std::span parts, LowerCtx const& ctx) { + static constexpr int kSearchWidth = 30; + std::vector models; + models.reserve(parts.size()); + for (DocNodePtr const& part : parts) { + bool const search = part->name("kind") == "search"; + HeadToolModel model{ + .id = part->id, + .path = part->path, + .kind = search ? HeadToolKind::Search : HeadToolKind::Select, + .label = bindProp(ctx, part->prop("label"), std::string{}, stringOf), + .value = bindProp(ctx, part->prop("value"), std::string{}, stringOf), + .placeholder = bindProp(ctx, part->prop("placeholder"), std::string{}, stringOf), + .options = {}, + .selected = {}, + .width = search ? kSearchWidth : 0, + .enabled = bindProp(ctx, part->prop("enabled"), true, boolOf), + .visible = bindProp(ctx, part->prop("visible"), true, boolOf), + .edit = {}, + .submit = {}, + }; + if (ExprPtr const width = part->prop("width")) { + if (std::int64_t const* const units = width->literal.asInt()) { + model.width = static_cast(*units); + } + } + if (!search) { + model.options = slotProp>( + [scope = ctx.scope, bindings = ctx.bindings, options = part->prop("options")] { + return selectOptions(evalIn(*scope, bindings.get(), options), scope->formatting()); + }); + model.selected = slotProp>( + [scope = ctx.scope, bindings = ctx.bindings, selected = part->prop("selected")] -> std::optional { + Value const value = selected ? evalIn(*scope, bindings.get(), selected) : Value{}; + return value.isNull() ? std::nullopt : std::optional{keyOf(value)}; + }); + } + Commands const* const edited = part->event(search ? "onChange" : "onChoose"); + model.edit = [this, ctx, edited](Value event) { runEvent(edited, ctx, std::move(event)); }; + if (search) { + model.submit = [this, ctx, onSubmit = part->event("onSubmit")](Value event) { + runEvent(onSubmit, ctx, std::move(event)); + }; + } + models.push_back(std::move(model)); + } + return models; +} + +ActionModels ScreenCore::lowerActionParts(std::span parts, LowerCtx const& ctx) { + ActionModels models; + models.reserve(parts.size()); + for (DocNodePtr const& part : parts) { + ActionModel model{ + .id = part->id, + .path = part->path, + .label = bindProp(ctx, part->prop("label"), std::string{}, stringOf), + .icon = bindProp(ctx, part->prop("icon"), std::string{}, stringOf), + .iconOnly = bindProp(ctx, part->prop("iconOnly"), false, boolOf), + .emphasis = ButtonEmphasis::Normal, + .enabled = bindProp(ctx, part->prop("enabled"), true, boolOf), + .visible = bindProp(ctx, part->prop("visible"), true, boolOf), + .run = {}, + }; + model.emphasis = emphasisNamed(part->name("emphasis")).value_or(ButtonEmphasis::Normal); + if (Commands const* const commands = part->event("onClick")) { + model.run = [this, ctx, commands] { runEvent(commands, ctx, Value{}); }; + } + models.push_back(std::move(model)); + } + return models; +} + +Node ScreenCore::actionBarOf(ActionModels actions) { + ActionBar bar; + for (ActionModel& action : actions) { + Button button{ + .label = action.label, + .emphasis = action.emphasis, + .onClick = std::move(action.run), + .common = {}, // NOLINT(readability-trailing-comma): the comma ends the designator, not the empty braces. + .icon = action.icon.evaluate(), + }; + if (action.iconOnly.isBound() || action.iconOnly.constant()) { + // The label is the button's name and tooltip; the caption is empty while the icon stands alone. + button.label = Prop{[label = action.label, iconOnly = action.iconOnly] { + return iconOnly.evaluate() ? std::string{} : label.evaluate(); + }}; + button.common.a11y.name = action.label; + button.common.tooltip = action.label; + } + button.common.visible = std::move(action.visible); + button.common.enabled = std::move(action.enabled); + button.common.testId = "action_" + action.id; + bar.children.push_back(ui::button(std::move(button))); + } + return ui::actionBar(std::move(bar)); +} + +std::vector ScreenCore::lowerBadgeParts(std::span parts, LowerCtx const& ctx) { + std::vector badges; + badges.reserve(parts.size()); + for (DocNodePtr const& part : parts) { + badges.push_back(BadgeModel{ + .text = bindProp(ctx, part->prop("text"), std::string{}, stringOf), + .tone = bindProp(ctx, part->prop("tone"), Tone::Neutral, toneOf), + .icon = bindProp(ctx, part->prop("icon"), std::string{}, stringOf), + .visible = bindProp(ctx, part->prop("visible"), true, boolOf), + }); + } + return badges; +} + +// The readers every kind's lowering shares, each bound to the node being lowered. +class ScreenCore::KindKit { +public: + KindKit(ScreenCore& core, DocNode const& node, LowerCtx const& ctx, ElementState* element) + : _core{core}, _node{node}, _ctx{ctx}, _element{element}, _format{ctx.scope->formatting()} {} + + // The children under @p key, each lowered with @p gap as the gap of the list around it. + [[nodiscard]] std::vector children(std::string_view key, int gap = 0) const { + LowerCtx listCtx = _ctx; + listCtx.listGap = gap; + std::vector out; + for (DocNodePtr const& child : _node.nodes(key)) { + out.push_back(_core.lower(*child, listCtx)); + } + return out; + } + + // The children under @p key as one node: none is empty, several share a holder that sets @p gap. + [[nodiscard]] Node child(std::string_view key, int gap = 0) const { + auto const nodes = _node.nodes(key); + return nodes.empty() ? Node{} : _core.lowerAll(nodes, _ctx, gap); + } + + [[nodiscard]] std::int64_t onceInt(std::string_view key, std::int64_t fallback) const { + ExprPtr const expr = _node.prop(key); + return expr ? intOf(_core.once(_ctx, expr), fallback) : fallback; + } + + [[nodiscard]] bool onceBool(std::string_view key, bool fallback) const { + ExprPtr const expr = _node.prop(key); + return expr ? boolOf(_core.once(_ctx, expr), _format) : fallback; + } + + // A stack's padding: one step, or the loader-checked constant list of the vertical and the horizontal step. A + // computed padding that yields a list is not a step: it is reported once and taken as 0. + [[nodiscard]] Padding stackPadding() const { + ExprPtr const expr = _node.prop("padding"); + if (!expr) { + return {}; + } + Value const value = _core.once(_ctx, expr); + if (ValueList const* const steps = value.asList()) { + if (expr->kind == ExprKind::Literal && steps->size() == 2) { + return Padding{static_cast(intOf(steps->at(0), 0)), static_cast(intOf(steps->at(1), 0))}; + } + _core.report(_node.path + "/padding", "a computed `padding` is one spacing step, not a list; taken as 0"); + return {}; + } + return Padding{static_cast(intOf(value, 0))}; + } + + [[nodiscard]] std::string onceText(std::string_view key) const { + ExprPtr const expr = _node.prop(key); + return expr ? textOf(_core.once(_ctx, expr), _format) : std::string{}; + } + + [[nodiscard]] Prop textProp(std::string_view key) const { + return _core.bindProp(_ctx, _node.prop(key), std::string{}, stringOf); + } + + // A field shows no caption of its own, so its label is what names it to assistive technology. An `a11y` part + // that gives a name was written for that purpose and wins; one that gives only a role leaves the label. + void nameByLabel(Common& common) const { + bool const named = std::ranges::any_of(_node.partList("a11y"), + [](DocNodePtr const& a11y) { return a11y->prop("name") != nullptr; }); + if (_node.prop("label") && !named) { + common.a11y.name = textProp("label"); + } + } + + // A standalone input draws its label as a caption only when the document asks for it (`showLabel`). + template + void captionOf(Spec& spec) const { + if (_node.prop("label")) { + spec.label = textProp("label"); + } + spec.showLabel = _node.flag("showLabel"); + } + + [[nodiscard]] Action action(std::string_view key) const { + Commands const* const commands = _node.event(key); + if (commands == nullptr) { + return {}; + } + return [core = &_core, ctx = _ctx, commands] { core->runEvent(commands, ctx, Value{}); }; + } + + [[nodiscard]] ActionButton actionPart() const { + ActionButton button; + for (DocNodePtr const& part : _node.partList("action")) { + button.label = _core.bindProp(_ctx, part->prop("label"), std::string{}, stringOf); + if (Commands const* const commands = part->event("onClick")) { + button.onClick = [core = &_core, ctx = _ctx, commands] { core->runEvent(commands, ctx, Value{}); }; + } + } + return button; + } + + // A reader of the element's value under @p name. + [[nodiscard]] auto read(std::string_view name) const { + return [element = _element, core = &_core, name = std::string{name}] { + return core->elementValue(*element, name); + }; + } + +private: + // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members): the kit lives inside one lowering call, in + // which all four outlive it. + ScreenCore& _core; + DocNode const& _node; + LowerCtx const& _ctx; + ElementState* _element; + FormatContext const& _format; + // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) +}; + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of ui/1. +std::optional ScreenCore::lowerWidget(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + std::string_view const kind = node.kind; + FormatContext const& format = ctx.scope->formatting(); + KindKit const kit{*this, node, ctx, element}; + if (kind == "text") { + Text spec{.role = roleProp(ctx, node.prop("role"))}; + // A text with spans shows them, so its `text`, an older client's fallback, is not lowered. + if (ExprPtr const spans = node.prop("spans")) { + spec.spans = spansProp(ctx, spans); + } else { + spec.text = kit.textProp("text"); + } + if (!node.name("align").empty()) { + spec.align = textAlignNamed(node.name("align")); + } + fieldOf(node, ctx, element, spec.field); + commonOf(node, ctx, element, spec.common); + return ui::text(std::move(spec)); + } + if (kind == "button") { + Button spec{.label = kit.textProp("label")}; + spec.icon = kit.onceText("icon"); + spec.emphasis = emphasisNamed(node.name("emphasis")).value_or(ButtonEmphasis::Normal); + if (node.name("style") == "item") { + spec.style = ButtonStyle::Item; + } + spec.shape = shapeNamed(node.name("shape")).value_or(ControlShape::Default); + spec.size = sizeNamed(node.name("size")).value_or(ButtonSize::Normal); + spec.mono = node.flag("mono"); + spec.weight = weightNamed(node.name("weight")).value_or(0); + if (node.prop("selected")) { + spec.selected = bindProp(ctx, node.prop("selected"), false, boolOf); + // An entry's content, drawn in place of its label: one node as it is, several in a column. + if (std::vector content = kit.children("children"); content.size() == 1) { + spec.child = std::move(content.front()); + } else if (!content.empty()) { + spec.child = ui::column(Column{.children = std::move(content)}); + } + } + Commands const* const onClick = node.event("onClick"); + Commands const* const onActivate = node.event("onActivate"); + if (onClick != nullptr || onActivate != nullptr) { + spec.onClick = [this, ctx, onClick, onActivate] { + runEvent(onClick, ctx, Value{}); + runEvent(onActivate, ctx, Value{}); + }; + } + commonOf(node, ctx, element, spec.common); + return ui::button(std::move(spec)); + } + if (kind == "textInput") { + std::string const commitOn = node.name("commitOn").empty() ? "change" : std::string{node.name("commitOn")}; + auto const commit = [this, ctx, element, commitOn, onChange = node.event("onChange")]( + std::string const& when, std::string const& text) { + if (commitOn != when) { + return; + } + if (element->bound == nullptr) { + session.noteWrite(); + element->committed.set(Value{text}); + } + runEvent(onChange, ctx, Value{text}); + }; + TextInput spec; + spec.value = + slotProp([this, element] { return textOf(element->draft.get(), session.formatting()); }); + spec.onChange = [this, element, commit](std::string text) { + session.asUser([&] { + session.noteWrite(); + element->draft.set(Value{text}); + element->edited.set(true); + }); + commit("change", text); + }; + spec.onCommit = [this, ctx, element, commit, onCommit = node.event("onCommit")](std::string const& text) { + element->touched.set(true); + commit("blur", text); + runEvent(onCommit, ctx, Value{text}); + }; + // Only a field that does something on Enter submits: one without `onSubmit` that does not commit on Enter + // lets Enter go on to its ancestors' chords, a dialog's `default` among them. + if (Commands const* const onSubmit = node.event("onSubmit"); onSubmit != nullptr || commitOn == "enter") { + spec.onSubmit = [this, ctx, commit, onSubmit](std::string const& text) { + commit("enter", text); + runEvent(onSubmit, ctx, Value{text}); + }; + } + spec.placeholder = kit.textProp("placeholder"); + std::string const mode = kit.onceText("mode"); + spec.mode = TextInputMode::SingleLine; + if (mode == "multiline") { + spec.mode = TextInputMode::Multiline; + } else if (mode == "password") { + spec.mode = TextInputMode::Password; + } + // A multiline input shows no unit and no icon; a computed mode that turns out multiline is reported and + // its unit and icon left out, so the mount never meets them there. The loader refuses a literal one. + for (std::string_view const key : { + std::string_view{"unit"}, + std::string_view{"icon"}, + std::string_view{"prefix"}, + std::string_view{"decimals"}, + }) { + if (ExprPtr const given = node.prop(key); given != nullptr && spec.mode == TextInputMode::Multiline) { + report(given->path, "a multiline input shows no " + std::string{key}); + } + } + spec.mono = node.flag("mono"); + spec.wrap = spec.mode != TextInputMode::Multiline || node.flag("wrap", true); + if (spec.mode != TextInputMode::Multiline) { + spec.emphasis = node.name("emphasis") == "prominent" ? InputEmphasis::Prominent : InputEmphasis::Normal; + spec.icon = kit.onceText("icon"); + spec.align = alignOf(node.name("align")); + if (spec.align == Align::Stretch) { + spec.align = Align::Start; + } + if (node.prop("unit")) { + spec.unit = kit.textProp("unit"); + } + if (node.prop("prefix")) { + spec.prefix = kit.textProp("prefix"); + } + if (ExprPtr const places = node.prop("decimals")) { + spec.decimals = bindProp(ctx, places, -1, placesOf); + } + } + fieldOf(node, ctx, element, spec.field); + commonOf(node, ctx, element, spec.common); + kit.nameByLabel(spec.common); + kit.captionOf(spec); + return ui::textInput(std::move(spec)); + } + if (kind == "checkbox") { + Checkbox spec{ + .label = kit.textProp("label"), + .checked = slotProp([read = kit.read("checked")] { + Value const value = read(); + bool const* const flag = value.asBool(); + return flag != nullptr && *flag; + }), + }; + spec.onToggle = [this, ctx, element, onToggle = node.event("onToggle"), + onChange = node.event("onChange")](bool checked) { + // A toggle is a check box's commit, so it touches the box. + session.asUser([&] { + if (element->bound == nullptr) { + session.noteWrite(); + element->draft.set(checked); + } + element->touched.set(true); + }); + runEvent(onToggle, ctx, Value{checked}); + runEvent(onChange, ctx, Value{checked}); + }; + fieldOf(node, ctx, element, spec.field); + commonOf(node, ctx, element, spec.common); + return ui::checkbox(std::move(spec)); + } + if (kind == "select") { + Select spec; + spec.options = slotProp>( + [scope = ctx.scope, element] { return selectOptions(element->rows->get(), scope->formatting()); }); + spec.selected = slotProp>([read = kit.read("selected")] -> std::optional { + Value const selected = read(); + return selected.isNull() ? std::nullopt : std::optional{keyOf(selected)}; + }); + spec.onSelect = [this, ctx, element, onChoose = node.event("onChoose"), + onChange = node.event("onChange")](Key const& key) { + Value const chosen = valueOfKey(key); + // A choice is a select's commit, so it touches the select. + session.asUser([&] { + if (element->bound == nullptr) { + session.noteWrite(); + element->draft.set(chosen); + } + element->touched.set(true); + }); + runEvent(onChoose, ctx, chosen); + runEvent(onChange, ctx, chosen); + }; + // A computed style of no known name is reported once and drawn as a dropdown; the loader refuses a constant + // one. + if (ExprPtr const style = node.prop("style")) { + std::string const name = textOf(once(ctx, style), ctx.scope->formatting()); + if (name == "radio") { + spec.style = SelectStyle::Radio; + } else if (name == "segmented") { + spec.style = SelectStyle::Segmented; + } else if (name != "dropdown") { + report(style->path, "style is `" + name + "`; a select's style is dropdown, radio or segmented"); + } + } + fieldOf(node, ctx, element, spec.field); + commonOf(node, ctx, element, spec.common); + kit.nameByLabel(spec.common); + kit.captionOf(spec); + return ui::select(std::move(spec)); + } + if (kind == "slider") { + Slider spec; + spec.value = slotProp([read = kit.read("value"), element] { + return intOf(element->bound != nullptr ? read() : element->draft.get(), 0); + }); + spec.minimum = kit.onceInt("min", 0); + spec.maximum = kit.onceInt("max", 100); + spec.step = kit.onceInt("step", 1); + spec.onChange = [this, ctx, element, onChange = node.event("onChange")](std::int64_t value) { + session.asUser([&] { + session.noteWrite(); + element->draft.set(value); + element->edited.set(true); + if (element->bound == nullptr) { + element->committed.set(value); + } + }); + runEvent(onChange, ctx, Value{value}); + }; + spec.onCommit = [this, ctx, element, onCommit = node.event("onCommit")](std::int64_t value) { + element->touched.set(true); + runEvent(onCommit, ctx, Value{value}); + }; + fieldOf(node, ctx, element, spec.field); + commonOf(node, ctx, element, spec.common); + kit.nameByLabel(spec.common); + return ui::slider(std::move(spec)); + } + if (kind == "dateTimeInput") { + DateTimeInput spec; + DateMode const mode = kit.onceText("mode") == "date" ? DateMode::Date : DateMode::DateTime; + std::optional heldAtLoad; + if (auto const found = _doc->dateValueKinds.find(&node); found != _doc->dateValueKinds.end()) { + heldAtLoad = found->second; + } + std::string const valuePath = pointerAppend(node.path, "value"); + std::int32_t const offsetMinutes = format.utcOffsetMinutes; + spec.value = slotProp>([this, element, offsetMinutes, + valuePath] -> std::optional { + DateReading const reading = dateInstantOf(element->draft.get(), offsetMinutes); + if (!reading.readable) { + report(valuePath, "`dateTimeInput` shows a timestamp or an ISO-8601 date or date-time string"); + } + return reading.instant ? std::optional{time::Timestamp{*reading.instant}} : std::nullopt; + }); + spec.onChange = [this, ctx, element, heldAtLoad, mode, offsetMinutes, onChange = node.event("onChange"), + onCommit = node.event("onCommit")](std::optional value) { + bool asString = element->bound != nullptr && element->bound->get().asString() != nullptr; + if (heldAtLoad) { + asString = *heldAtLoad == TypeKind::String; + } + std::optional const instant = value ? value->value : std::nullopt; + Value entered; + if (!asString) { + if (instant) { + entered = Value{*instant}; + } + } else if (!instant) { + entered = Value{std::string{}}; + } else if (mode == DateMode::Date) { + entered = Value{dateTextOf(*instant, offsetMinutes)}; + } else { + entered = Value{instant->toIso8601()}; + } + element->touched.set(true); + session.asUser([&] { + session.noteWrite(); + element->draft.set(entered); + element->edited.set(true); + if (element->bound == nullptr) { + element->committed.set(entered); + } + }); + runEvent(onChange, ctx, entered); + runEvent(onCommit, ctx, entered); + }; + spec.mode = mode; + spec.offsetMinutes = offsetMinutes; + // Tracked: a locale switch changes the pattern the screen's dates are written in, and the input follows. + spec.pattern = slotProp([this, mode] { + FormatContext const& now = session.formatting(); + return mode == DateMode::Date ? now.datePattern : now.dateTimePattern; + }); + fieldOf(node, ctx, element, spec.field); + commonOf(node, ctx, element, spec.common); + kit.nameByLabel(spec.common); + kit.captionOf(spec); + return ui::dateTimeInput(std::move(spec)); + } + if (kind == "filePicker") { + FilePicker spec; + spec.path = + slotProp([this, element] { return textOf(element->draft.get(), session.formatting()); }); + spec.onPicked = [this, ctx, element, onPick = node.event("onPick")](std::string path) { + session.asUser([&] { + session.noteWrite(); + element->draft.set(Value{path}); + element->committed.set(Value{path}); + }); + runEvent(onPick, ctx, Value{path}); + }; + spec.mode = kit.onceText("mode") == "save" ? FilePickerMode::Save : FilePickerMode::Open; + fieldOf(node, ctx, element, spec.field); + commonOf(node, ctx, element, spec.common); + kit.nameByLabel(spec.common); + return ui::filePicker(std::move(spec)); + } + if (kind == "menu") { + Menu spec{.items = menuItems(node.partList("items"), ctx)}; + if (node.name("style") == "button") { + spec.style = MenuStyle::Button; + spec.label = kit.textProp("label"); + spec.icon = kit.onceText("icon"); + if (node.name("emphasis") == "primary") { + spec.emphasis = ButtonEmphasis::Primary; + } else if (node.name("emphasis") == "danger") { + spec.emphasis = ButtonEmphasis::Danger; + } else if (node.name("emphasis") == "ghost") { + spec.emphasis = ButtonEmphasis::Ghost; + } + } + commonOf(node, ctx, element, spec.common); + return ui::menu(std::move(spec)); + } + return std::nullopt; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of ui/1. +std::optional ScreenCore::lowerDisplay(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + std::string_view const kind = node.kind; + KindKit const kit{*this, node, ctx, element}; + if (kind == "banner") { + Banner spec{.tone = bindProp(ctx, node.prop("tone"), Tone::Info, toneOf)}; + if (ExprPtr const spans = node.prop("spans")) { + spec.spans = spansProp(ctx, spans); + } else { + spec.text = kit.textProp("text"); + } + spec.action = kit.actionPart(); + spec.dismissible = kit.onceBool("dismissible", false); + spec.onDismiss = kit.action("onDismiss"); + spec.actionStyle = bannerActionStyleNamed(node.name("actionStyle")).value_or(BannerActionStyle::Ghost); + spec.actionStretch = node.flag("actionStretch"); + commonOf(node, ctx, element, spec.common); + return ui::banner(std::move(spec)); + } + if (kind == "badge") { + Badge spec{ + .tone = bindProp(ctx, node.prop("tone"), Tone::Neutral, toneOf), + .text = kit.textProp("text"), + }; + spec.icon = kit.onceText("icon"); + std::string_view const style = node.name("style"); + spec.style = BadgeStyle::Filled; + if (style == "outline") { + spec.style = BadgeStyle::Outline; + } else if (style == "quiet") { + spec.style = BadgeStyle::Quiet; + } + spec.shape = shapeNamed(node.name("shape")).value_or(ControlShape::Default); + spec.mono = node.flag("mono"); + if (Commands const* const onRemove = node.event("onRemove")) { + spec.onRemove = [this, ctx, onRemove] { runEvent(onRemove, ctx, Value{}); }; + spec.removeLabel = kit.textProp("removeLabel"); + } + commonOf(node, ctx, element, spec.common); + return ui::badge(std::move(spec)); + } + if (kind == "progress") { + Progress spec; + spec.value = slotProp>( + [scope = ctx.scope, bindings = ctx.bindings, expr = node.prop("value")] -> std::optional { + Value const value = evalIn(*scope, bindings.get(), expr); + if (std::int64_t const* const number = value.asInt()) { + return static_cast(*number); + } + if (Decimal const* const number = value.asDecimal()) { + return realOf(number->value); + } + return std::nullopt; + }); + spec.label = kit.textProp("label"); + commonOf(node, ctx, element, spec.common); + return ui::progress(std::move(spec)); + } + if (kind == "steps") { + Steps spec; + spec.items = + slotProp>([scope = ctx.scope, bindings = ctx.bindings, expr = node.prop("items")] { + std::vector steps; + Value const items = evalIn(*scope, bindings.get(), expr); + if (ValueList const* const list = items.asList()) { + for (Value const& item : *list) { + Value const* const label = item.field("label"); + Value const* const state = item.field("state"); + Value const* const detail = item.field("detail"); + std::string const name = state == nullptr ? std::string{} : textOf(*state, {}); + steps.push_back(Step{ + .label = label == nullptr ? std::string{} : textOf(*label, scope->formatting()), + .state = stepStateOf(name), + .detail = detail == nullptr ? std::string{} : textOf(*detail, scope->formatting()), + }); + } + } + return steps; + }); + spec.current = slotProp>( + [scope = ctx.scope, bindings = ctx.bindings, expr = node.prop("current")] -> std::optional { + std::int64_t const index = intOf(evalIn(*scope, bindings.get(), expr), -1); + return index < 0 ? std::nullopt : std::optional{static_cast(index)}; + }); + spec.labelled = bindProp(ctx, node.prop("labelled"), true, boolOf); + commonOf(node, ctx, element, spec.common); + return ui::steps(std::move(spec)); + } + if (kind == "chart") { + return lowerChart(node, ctx, element); + } + if (kind == "keyValue") { + KeyValue spec; + spec.captions = node.name("fieldLayout") == "stacked" ? CaptionPlacement::Above : CaptionPlacement::Beside; + // The loader has checked `captionWidth` is a literal integer. + if (ExprPtr const width = node.prop("captionWidth")) { + spec.captionWidth = static_cast(*width->literal.asInt()); + } + spec.items = slotProp>( + [this, scope = ctx.scope, bindings = ctx.bindings, expr = node.prop("items")] { + std::vector out; + Value const items = evalIn(*scope, bindings.get(), expr); + if (ValueList const* const list = items.asList()) { + for (Value const& item : *list) { + out.push_back(keyValueItemOf(item, expr->path, *scope)); + } + } + return out; + }); + commonOf(node, ctx, element, spec.common); + return ui::keyValue(std::move(spec)); + } + if (kind == "emptyState") { + EmptyState spec{.title = kit.textProp("title"), .text = kit.textProp("text")}; + spec.icon = kit.onceText("icon"); + spec.action = kit.actionPart(); + commonOf(node, ctx, element, spec.common); + return ui::emptyState(std::move(spec)); + } + return std::nullopt; +} + +Node ScreenCore::lowerStack(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + std::string_view const kind = node.kind; + KindKit const kit{*this, node, ctx, element}; + int const gap = static_cast(kit.onceInt("gap", 0)); + if (std::string const arrangement = arrangedBy(node.id); !arrangement.empty()) { + return lowerArranged(node, ctx, element, arrangement, kind == "column" ? Axis::Vertical : Axis::Horizontal, + gap); + } + if (kind == "column") { + Column spec{ + .children = kit.children("children", gap), + .gap = gap, + .align = alignOf(node.name("align")), + .justify = justifyOf(node.name("justify")), + .divided = node.flag("divided"), + .padding = kit.stackPadding(), + }; + if (node.prop("selected")) { + spec.selected = bindProp(ctx, node.prop("selected"), false, boolOf); + } + commonOf(node, ctx, element, spec.common); + return ui::column(std::move(spec)); + } + Row spec{ + .children = kit.children("children"), + .gap = gap, + .align = alignOf(node.name("align")), + .justify = justifyOf(node.name("justify")), + .wrap = node.flag("wrap"), + .divided = node.flag("divided"), + .padding = kit.stackPadding(), + }; + if (node.prop("selected")) { + spec.selected = bindProp(ctx, node.prop("selected"), false, boolOf); + } + commonOf(node, ctx, element, spec.common); + return ui::row(std::move(spec)); +} + +Node ScreenCore::lowerGrid(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + KindKit const kit{*this, node, ctx, element}; + Grid spec{ + .columns = static_cast(kit.onceInt("columns", 1)), + .gap = static_cast(kit.onceInt("gap", 0)), + .align = alignOf(node.name("align")), + .minColumnWidth = static_cast(kit.onceInt("minColumnWidth", 0)), + }; + for (DocNodePtr const& track : node.partList("tracks")) { + ExprPtr const width = track->prop("width"); + spec.tracks.push_back(GridTrack{ + .width = width ? sizingOf(once(ctx, width)) : Sizing::stretch(), + .align = cellPlaceNamed(track->name("align")).value_or(Align::Start), + }); + } + for (DocNodePtr const& cell : node.nodes("children")) { + ExprPtr const span = cell->prop("span"); + spec.cells.push_back( + GridCell{.node = lower(*cell, ctx), .span = static_cast(span ? intOf(once(ctx, span), 1) : 1)}); + } + commonOf(node, ctx, element, spec.common); + return ui::grid(std::move(spec)); +} + +Node ScreenCore::lowerPanel(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + KindKit const kit{*this, node, ctx, element}; + Panel spec{.title = kit.textProp("title"), .padding = static_cast(kit.onceInt("padding", 0))}; + spec.header = kit.child("header"); + spec.child = kit.child("children", static_cast(kit.onceInt("gap", kPanelGap))); + spec.collapsible = kit.onceBool("collapsible", false); + spec.collapsed = bindProp(ctx, node.prop("collapsed"), false, boolOf); + if (Commands const* const commands = node.event("onToggle")) { + spec.onToggle = [this, ctx, commands](bool collapsed) { runEvent(commands, ctx, Value{collapsed}); }; + } + commonOf(node, ctx, element, spec.common); + return ui::panel(std::move(spec)); +} + +Node ScreenCore::lowerSplitter(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + KindKit const kit{*this, node, ctx, element}; + ExprPtr const orientation = node.prop("orientation"); + Splitter spec{ + .children = kit.children("children"), + .orientation = + orientation && axisOf(once(ctx, orientation)) == Axis::Vertical ? Axis::Vertical : Axis::Horizontal, + }; + // No `onResize`: a user's drag stays the splitter's own, and the document's sizes are where it starts. + if (ExprPtr const sizes = node.prop("sizes")) { + spec.sizes = bindProp>( + ctx, sizes, {}, [this, path = sizes->path](Value const& value, FormatContext const& /*format*/) { + std::optional> parsed = splitterSizesOf(value); + if (!parsed) { + report(path, "sizes is " + canonicalJson(value) + "; sizes is a list of numbers, one per pane"); + } + return std::move(parsed).value_or(std::vector{}); + }); + } + commonOf(node, ctx, element, spec.common); + // A literal `sizes` that matches the panes places them, so a pane's own width is not used. + if (ExprPtr const sizes = node.prop("sizes"); sizes && sizes->kind == ExprKind::Literal) { + std::optional> const given = splitterSizesOf(sizes->literal); + if (given && given->size() == spec.children.size()) { + for (std::size_t at = 0; at < spec.children.size(); ++at) { + // A stretch pane asks only to fill, which `sizes` leaves it to do; a fixed or percent pane names a + // size. + Sizing::Kind const kind = layoutHintsOf(spec.children.at(at)).width.kind; + if (spec.orientation == Axis::Horizontal && + (kind == Sizing::Kind::Fixed || kind == Sizing::Kind::Percent)) { + report(sizes->path, "this splitter's `sizes` places its panes; pane " + std::to_string(at) + + "'s sizing is not used"); + } + } + } + } + return ui::splitter(std::move(spec)); +} + +void ScreenCore::reportActionBarGaps(DocNode const& bar, LowerCtx const& ctx) { + for (DocNodePtr const& child : bar.nodes("children")) { + if (child->kind != "forEach" || child->prop("gap") == nullptr) { + continue; + } + ExprPtr const axis = child->prop("axis"); + if (axis != nullptr && axis->kind != ExprKind::Literal && axisOf(once(ctx, axis)) == Axis::Horizontal) { + report(child->path + "/gap", kActionBarGapRefusal); + } + } +} + +Node ScreenCore::lowerCollapsible(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + KindKit const kit{*this, node, ctx, element}; + Collapsible spec{.title = kit.textProp("title"), .open = bindProp(ctx, node.prop("open"), true, boolOf)}; + if (Commands const* const commands = node.event("onToggle")) { + spec.onToggle = [this, ctx, commands](bool open) { runEvent(commands, ctx, Value{open}); }; + } + spec.header = kit.child("header"); + spec.child = kit.child("children", static_cast(kit.onceInt("gap", kPanelGap))); + commonOf(node, ctx, element, spec.common); + return ui::collapsible(std::move(spec)); +} + +Node ScreenCore::lowerDropZone(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + KindKit const kit{*this, node, ctx, element}; + DropZone spec; + spec.accept = stringsOf(node.prop("accept") ? once(ctx, node.prop("accept")) : Value{}); + spec.multiple = kit.onceBool("multiple", false); + if (Commands const* const commands = node.event("onDrop")) { + spec.onDrop = [this, ctx, commands](std::vector const& paths) { + runEvent(commands, ctx, listOfStrings(paths)); + }; + } + spec.child = kit.child("children"); + commonOf(node, ctx, element, spec.common); + return ui::dropZone(std::move(spec)); +} + +Node ScreenCore::lowerPage(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + KindKit const kit{*this, node, ctx, element}; + Page spec; + spec.geometry = pageGeometryOf(node); + std::optional const outer = std::exchange(pageBeingLowered, spec.geometry); + spec.children = kit.children("children"); + pageBeingLowered = outer; + commonOf(node, ctx, element, spec.common); + return ui::page(std::move(spec)); +} + +Node ScreenCore::lowerPageRegion(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + if (!pageBeingLowered) { + report(node.path, "a page region belongs in a page"); + return ui::text(Text{.text = std::string{}, .role = TextRole::Muted}); + } + KindKit const kit{*this, node, ctx, element}; + PageRegion spec; + spec.geometry = regionGeometryOf(node, *pageBeingLowered); + std::optional const outer = std::exchange(pageBeingLowered, std::nullopt); + spec.children = kit.children("children"); + pageBeingLowered = outer; + commonOf(node, ctx, element, spec.common); + return ui::pageRegion(std::move(spec)); +} + +Node ScreenCore::lowerLocaleScope(DocNode const& node, LowerCtx const& ctx) { + auto const holder = std::make_shared(*this, ctx.scope, nullptr, ctx.scope->nodes.depth() + 2); + holder->transparent = true; + ExprPtr const locale = node.prop("locale"); + holder->localeFormat = &holder->nodes.computed([this, scope = ctx.scope, bindings = ctx.bindings, + locale] -> std::shared_ptr { + Value const value = evalIn(*scope, bindings.get(), locale); + std::string const* const tag = value.asString(); + if (tag == nullptr && !value.isNull()) { + report(locale->path, "the locale is " + canonicalJson(value) + "; a locale is a BCP 47 tag, a string"); + } + if (tag == nullptr || tag->empty()) { + return session.sharedFormatting(); + } + if (session.firstUnlistedLocale(*tag)) { + report(locale->path, "no formatting facts for locale `" + *tag + "`; numbers, money and dates use en's"); + } + return session.scopedFormatting(*tag); + }); + // The children are mounted again whenever the tag changes: a value a node reads once, as it is lowered (a + // table's column labels, a `once` property, a literal), is written in the facts at that moment, and only a new + // lowering writes it in the new ones. The key is the tag as the scope resolves it; a tag that is not known yet + // is the key `""`, apart from every tag. + std::vector content; + for (DocNodePtr const& child : node.nodes("children")) { + content.push_back(child.get()); + } + LayoutHints const hints = holderHints(content, nullptr, ctx); + Switch spec; + spec.selector = slotProp([scope = ctx.scope, bindings = ctx.bindings, locale] { + Value const value = evalIn(*scope, bindings.get(), locale); + std::string const* const tag = value.asString(); + return Key{tag == nullptr ? std::string{} : *tag}; + }); + spec.fallback = lazy( + [this, ctx, holder, content, path = node.path] -> Node { + auto const inner = std::make_shared(*this, holder, nullptr, holder->nodes.depth() + 2); + inner->transparent = true; + LowerCtx const innerCtx{.scope = inner, .bindings = ctx.bindings, .boundary = ctx.boundary, .listGap = 0}; + std::vector children; + children.reserve(content.size()); + for (DocNode const* const child : content) { + children.push_back(lower(*child, innerCtx)); + } + fillHolder(children, path); + return holding(std::move(children), inner, {}, 0); + }, + hints); + commonOf(node, ctx, nullptr, spec.common); + return ui::switchOf(std::move(spec)); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per kind of ui/1. +Node ScreenCore::lowerKind(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + std::string_view const kind = node.kind; + KindKit const kit{*this, node, ctx, element}; + if (std::optional widget = lowerWidget(node, ctx, element)) { + return std::move(*widget); + } + if (kind == "group") { + return lowerGroup(node, ctx, element, kit.children("children")); + } + if (kind == "column" || kind == "row") { + return lowerStack(node, ctx, element); + } + if (kind == "grid") { + return lowerGrid(node, ctx, element); + } + if (kind == "spacer") { + Spacer spec; + commonOf(node, ctx, element, spec.common); + return ui::spacer(std::move(spec)); + } + if (kind == "panel") { + return lowerPanel(node, ctx, element); + } + if (kind == "scroll") { + ExprPtr const axis = node.prop("axis"); + Scroll spec{.child = kit.child("children"), .axis = axis ? axisOf(once(ctx, axis)) : Axis::Vertical}; + commonOf(node, ctx, element, spec.common); + return ui::scroll(std::move(spec)); + } + if (kind == "switch") { + return lowerSwitch(node, ctx); + } + if (kind == "tabs") { + return lowerTabs(node, ctx, element); + } + if (kind == "dialog" || kind == "drawer") { + return lowerDialog(node, ctx, element); + } + if (kind == "busy") { + Busy spec{.active = bindProp(ctx, node.prop("active"), false, boolOf), .label = kit.textProp("label")}; + commonOf(node, ctx, element, spec.common); + return ui::busy(std::move(spec)); + } + if (kind == "table" && !node.partList("layoutRows").empty()) { + return lowerFixedGrid(node, ctx, element); + } + if (kind == "table" && !node.name("form").empty()) { + return lowerFormGrid(node, ctx, element); + } + if (kind == "table" && !node.name("model").empty()) { + return lowerModelTable(node, ctx, element); + } + if (kind == "forEach" || kind == "table") { + return lowerRows(node, ctx, element); + } + if (std::optional display = lowerDisplay(node, ctx, element)) { + return std::move(*display); + } + if (kind == "splitter") { + return lowerSplitter(node, ctx, element); + } + if (kind == "collapsible") { + return lowerCollapsible(node, ctx, element); + } + if (kind == "dropZone") { + return lowerDropZone(node, ctx, element); + } + if (kind == "actionBar") { + KindKit const bar{*this, node, ctx, element}; + ActionBar spec{ + .children = bar.children("children"), + .align = alignOf(node.name("align")), + .justify = justifyOf(node.name("justify")), + .wrap = node.flag("wrap"), + }; + reportActionBarGaps(node, ctx); + commonOf(node, ctx, element, spec.common); + return ui::actionBar(std::move(spec)); + } + if (kind == "page") { + return lowerPage(node, ctx, element); + } + if (kind == "pageRegion") { + return lowerPageRegion(node, ctx, element); + } + if (kind == "localeScope") { + return lowerLocaleScope(node, ctx); + } + if (kind == "boundary") { + return lowerBoundary(node, ctx); + } + if (kind == "custom") { + return lowerCustom(node, ctx); + } + if (kind == "customize") { + return lowerCustomize(node, ctx); + } + if (kind == "form") { + return lowerForm(node, ctx, element); + } + if (kind == "collection" || kind == "wizard") { + return lowerComposite(node, ctx, element); + } + report(node.path, "`" + node.kind + "` is a node kind this interpreter does not lower"); + return ui::text(Text{.text = std::string{node.kind}, .role = TextRole::Muted}); +} + +// NOLINTEND(misc-no-recursion) + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_mount.cpp b/src/ui/interpreter_mount.cpp new file mode 100644 index 000000000..f9c1a9b3f --- /dev/null +++ b/src/ui/interpreter_mount.cpp @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Mounting a document: the interpreter builds a screen or an app from it. + +#include "interpreter_table_detail.hpp" + +namespace morph::ui { + +Screen::Screen() = default; + +Screen::~Screen() { + try { + if (Commands const* const commands = lifecycleList("onUnmount")) { + runCommands(*commands); + } + } catch (...) { // NOLINT(bugprone-empty-catch): a destructor has no one to report to. + } + _core->focusElement = {}; + _core->clipboard = {}; + _core->pasteboard = {}; + _mounted.reset(); + _headActions.clear(); + _headStatus.clear(); + _headMenu.clear(); + _headTools.clear(); + _scope.reset(); +} + +Widget& Screen::root() const { + if (!_mounted) { + throw std::logic_error{"the screen is not mounted"}; + } + return _mounted->root(); +} + +std::vector Screen::headSpans(ExprPtr const& expr) const { + if (expr == nullptr) { + return {}; + } + bool dropped = false; + bool badTone = false; + std::vector spans = + detail::spansOf(detail::evalIn(*_scope, nullptr, expr), _scope->formatting(), dropped, &badTone); + if (dropped) { + _core->report(expr->path, detail::kSpansReason); + } + if (badTone) { + _core->report(expr->path, detail::kSpanToneReason); + } + return spans; +} + +DocNode const* Screen::shownRoot() const { + DocNode const* node = _core->doc().view.get(); + while (node != nullptr && node->kind == "switch") { + Value const value = detail::evalIn(*_scope, nullptr, node->prop("on")); + std::span shown = node->nodes("default"); + for (DocNodePtr const& part : node->partList("cases")) { + if (!(detail::evalIn(*_scope, nullptr, part->prop("when")) == value)) { + continue; + } + if (part->scope.has_value() && detail::declaresNames(*part->scope)) { + return nullptr; + } + shown = part->nodes("children"); + break; + } + node = shown.size() == 1 ? shown.front().get() : nullptr; + } + return node; +} + +bool Screen::pageEdge() const { + DocNode const* const node = shownRoot(); + return node != nullptr && node->flag("pageEdge"); +} + +bool Screen::headJoined() const { + DocNode const* const node = shownRoot(); + return node != nullptr && node->flag("headJoined"); +} + +LeadPlacement Screen::leadPlacement() const { + ExprPtr const& placement = _core->doc().leadPlacement; + if (placement == nullptr) { + return LeadPlacement::Below; + } + Value const value = detail::evalIn(*_scope, nullptr, placement); + if (std::string const* const name = value.asString()) { + if (*name == "inline") { + return LeadPlacement::Inline; + } + if (*name == "end") { + return LeadPlacement::End; + } + if (*name == "below") { + return LeadPlacement::Below; + } + } + if (!value.isNull()) { + _core->report(placement->path, "`leadPlacement` is `below`, `inline` or `end`"); + } + return LeadPlacement::Below; +} + +TextRole Screen::titleRole() const { + ExprPtr const& role = _core->doc().titleRole; + if (role == nullptr) { + return TextRole::Heading; + } + Value const value = detail::evalIn(*_scope, nullptr, role); + if (std::string const* const name = value.asString()) { + if (*name == "headline") { + return TextRole::Headline; + } + if (*name == "heading") { + return TextRole::Heading; + } + } + if (!value.isNull()) { + _core->report(role->path, "`titleRole` is `heading` or `headline`"); + } + return TextRole::Heading; +} + +std::string Screen::headSurface() const { + Value const value = detail::evalIn(*_scope, nullptr, _core->doc().headSurface); + std::string const* const name = value.asString(); + return name == nullptr ? std::string{} : *name; +} + +std::string Screen::pageSurface() const { + Value const value = detail::evalIn(*_scope, nullptr, _core->doc().pageSurface); + std::string const* const name = value.asString(); + return name == nullptr ? std::string{} : *name; +} + +std::vector Screen::subtitleSpans() const { return headSpans(_core->doc().subtitleSpans); } + +std::vector Screen::titleSpans() const { return headSpans(_core->doc().titleSpans); } + +std::vector Screen::eyebrowSpans() const { return headSpans(_core->doc().eyebrowSpans); } + +BorrowedModel Screen::lend(std::string_view alias) const { + detail::NameRef const* const found = _scope->find(alias); + if (found == nullptr || found->category != detail::NameCategory::Model) { + return {}; + } + detail::ModelAlias& model = *found->model; + return BorrowedModel{ + .channel = detail::channelOf(model, *_core), + .token = _core->runtime().untracked([&] { return model.token->get(); }), + }; +} + +std::expected, Refusal> Interpreter::mount(std::shared_ptr doc, + ValueRecord const& params, IViewBackend& backend, + MountOptions const& options) { + auto const refuse = [&](std::string path, std::string reason) { + return std::unexpected(Refusal{.document = doc->id, .path = std::move(path), .reason = std::move(reason)}); + }; + if (!doc->view) { + return refuse("", "the document has no view"); + } + ValueRecord given; + for (auto const& [name, type] : doc->params) { + auto const found = params.find(name); + Value value = found == params.end() ? Value{} : found->second; + if (!type.admits(value)) { + return refuse(pointerAppend("/params", name), value.isNull() + ? "param `" + name + "` is missing" + : "param `" + name + "` is not a " + type.name()); + } + given.insert_or_assign(name, std::move(value)); + } + for (ModelDecl const& model : doc->scope.models) { + if (model.instance == InstanceMode::Borrowed && !options.borrowed.contains(model.name)) { + return refuse(model.path, "alias `" + model.name + "` borrows a model its opener did not lend"); + } + } + reactive::Runtime& runtime = _session->runtime(); + std::unique_ptr screen{new Screen{}}; + screen->_core = std::make_unique(doc, *_session, *_dispatcher, _options, options); + detail::ScreenCore& core = *screen->_core; + if (options.keepStateOf != nullptr) { + core.keptStates = options.keepStateOf->ownState(); + } + screen->_scope = std::make_shared(core, nullptr, nullptr, options.depth); + core.rootScope = screen->_scope; + detail::RtScope& scope = *screen->_scope; + scope.submitted = &core.submitted; + scope.showErrors = doc->showErrors; + for (auto const& [name, value] : given) { + detail::NameRef ref; + ref.category = detail::NameCategory::Param; + ref.param = value; + scope.names.insert_or_assign(name, std::move(ref)); + } + std::vector lists; + for (auto const& [key, commands] : doc->lifecycle) { + static_cast(key); + lists.push_back(&commands); + } + for (auto const& [chord, commands] : doc->keys) { + static_cast(chord); + lists.push_back(&commands); + } + detail::headCommandLists(*doc, lists); + Node root = runtime.untracked([&] { + core.declare(scope, &doc->scope, {doc->view.get()}, lists); + detail::LowerCtx const ctx{ + .scope = screen->_scope, + .bindings = std::make_shared(), + .boundary = nullptr, + }; + Node lowered = core.lower(*doc->view, ctx); + screen->_headStatus = core.lowerBadgeParts(doc->status, ctx); + screen->_headActions = core.lowerActionParts(doc->actions, ctx); + screen->_headMenu = core.lowerHeadMenu(doc->menu, ctx); + screen->_headTools = core.lowerHeadTools(doc->tools, ctx); + if (!doc->keys.empty()) { + std::vector keys; + for (auto const& [chord, commands] : doc->keys) { + keys.push_back(KeyBinding{ + .chord = chord, + .onPress = [&core, ctx, list = &commands] { core.runEvent(list, ctx, Value{}); }, + }); + } + Column column{.children = {std::move(lowered)}}; + column.common.keys = std::move(keys); + lowered = ui::column(std::move(column)); + } + return lowered; + }); + screen->_mounted = std::make_unique(runtime, backend, std::move(root), options.parent, options.depth + 1); + screen->_core->focusElement = [mounted = screen->_mounted.get()](std::string_view element) { + return mounted->focus(element); + }; + screen->_core->clipboard = [&backend](std::string_view text) { return backend.copyText(text); }; + screen->_core->pasteboard = [&backend] { return backend.pasteText(); }; + screen->runLifecycle("onMount"); + return screen; +} + +namespace { + +// The texts of a tour evaluated in the app scope. +Tour lowerTour(detail::RtScope& scope, TourDecl const& declared) { + auto const textOf = [&scope](ExprPtr const& expr) { + return expr == nullptr ? std::string{} + : detail::textOf(detail::evalIn(scope, nullptr, expr), scope.formatting()); + }; + Tour tour{.id = declared.id, + .screen = declared.screen, + .title = textOf(declared.title), + .summary = textOf(declared.summary), + .steps = {}, + .revision = declared.revision}; + for (TourStepDecl const& step : declared.steps) { + tour.steps.push_back(TourStep{.title = textOf(step.title), + .body = textOf(step.body), + .screen = step.screen, + .params = step.params, + .target = step.target, + .advanceOn = step.advanceOn}); + } + return tour; +} + +// The app document's tours, then the runtime ones. A runtime tour with one of the app document's ids is left out, +// since the server refuses one and an old list may still hold it. +std::vector lowerTours(Document const& doc, detail::RtScope& scope, std::vector const& runtime) { + std::vector out; + out.reserve(doc.tours.size()); + for (TourDecl const& declared : doc.tours) { + out.push_back(lowerTour(scope, declared)); + } + for (TourDecl const& declared : runtime) { + if (std::ranges::none_of(out, [&declared](Tour const& kept) { return kept.id == declared.id; })) { + out.push_back(lowerTour(scope, declared)); + } + } + return out; +} + +} // namespace + +std::expected, Refusal> Interpreter::mountApp(std::shared_ptr doc) { + if (doc->id != "app") { + return std::unexpected( + Refusal{.document = doc->id, .path = "/id", .reason = "the app document's id is `app`"}); + } + if (_session->appScope() != nullptr) { + return std::unexpected( + Refusal{.document = doc->id, .path = {}, .reason = "an app document is already mounted on the session"}); + } + std::unique_ptr root{new AppRoot{}}; + root->_core = std::make_unique(doc, *_session, *_dispatcher, _options, MountOptions{}); + detail::ScreenCore& core = *root->_core; + root->_scope = std::make_shared(core, nullptr, nullptr, 0); + core.rootScope = root->_scope; + std::vector lists; + for (auto const& [key, commands] : doc->lifecycle) { + static_cast(key); + lists.push_back(&commands); + } + _session->runtime().untracked([&] { + core.declare(*root->_scope, &doc->scope, {}, lists); + detail::LowerCtx const ctx{ + .scope = root->_scope, + .bindings = std::make_shared(), + .boundary = nullptr, + }; + std::vector badges = core.lowerBadgeParts(doc->navigation, ctx); + for (std::size_t index = 0; index < badges.size(); ++index) { + root->_navigation.push_back(AppRoot::PlacedBadge{ + .screen = std::string{doc->navigation.at(index)->name("screen")}, + .badge = std::move(badges.at(index)), + }); + } + }); + root->_navigationBadges = std::make_unique>>( + _session->runtime(), [placed = &root->_navigation] { + std::vector shown; + for (AppRoot::PlacedBadge const& entry : *placed) { + if (entry.badge.visible.evaluate()) { + shown.push_back(NavigationBadge{ + .screen = entry.screen, + .text = entry.badge.text.evaluate(), + .tone = entry.badge.tone.evaluate(), + }); + } + } + return shown; + }); + // One computed value for every tour: the texts are few, and a change of locale changes all of them at once. + root->_runtimeTours = std::make_unique const>>>( + _session->runtime(), std::make_shared const>()); + root->_tours = std::make_unique>>( + _session->runtime(), [doc, scope = root->_scope.get(), runtime = root->_runtimeTours.get()] { + return lowerTours(*doc, *scope, *runtime->get()); + }); + // The app document's date patterns are the application's: every screen of the bundle shows and reads dates so. + if (!doc->datePattern.empty() || !doc->dateTimePattern.empty()) { + _session->setDatePatterns(doc->datePattern, doc->dateTimePattern); + } + _session->setAppScope(root->_scope.get()); + if (auto const found = doc->lifecycle.find("onMount"); found != doc->lifecycle.end()) { + root->runCommands(found->second); + } + return root; +} + +} // namespace morph::ui diff --git a/src/ui/interpreter_rows.cpp b/src/ui/interpreter_rows.cpp new file mode 100644 index 000000000..808c2bf15 --- /dev/null +++ b/src/ui/interpreter_rows.cpp @@ -0,0 +1,1019 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Lowering tables over rows and collections. + +#include "interpreter_grid_detail.hpp" + +namespace morph::ui { + +std::shared_ptr detail::makeTableStates(Session& session, reactive::Runtime const& runtime, + SessionOptions const& options) { + if (options.tableState == nullptr) { + return nullptr; + } + // A save the server refuses for its open uploads is sent again after the session's `tableStateTimeout`, on the + // session's timers; a store with none would send it again on the owner's next turn, a burst of retries. + if (auto* const preferences = dynamic_cast(options.tableState.get()); + preferences != nullptr && options.scheduler != nullptr) { + preferences->retryOn(*options.scheduler, options.tableStateTimeout); + } + auto states = std::make_shared(options.tableState, runtime.owner(), options.scheduler, + options.tableStateDebounce); + states->onSaveFailed([&session](table::TableStateKey const& key, table::SaveResult const& result) { + session.tableSaveFailed(key, result); + }); + return states; +} + +void Session::tableSaveFailed(table::TableStateKey const& key, table::SaveResult const& result) { + // A screen a message unmounts is passed over; one it does not stays attached. + std::vector const screens = _screens; + for (detail::ScreenCore* const screen : screens) { + if (std::ranges::find(_screens, screen) != _screens.end()) { + screen->tableSaveFailed(key, result); + } + } +} + +namespace detail { + +TableConfig::TableConfig(reactive::Runtime& runtime) + : version{runtime, 0}, + chooserOpen{runtime, false}, + sortOpen{runtime, false}, + groupDraft{runtime, GroupDraft{}}, + filterMenu{std::make_unique(runtime)}, + viewDialog{runtime, ViewDialog{}} {} + +ElementState::ElementState(reactive::Runtime& runtime) + : draft{runtime}, + committed{runtime}, + edited{runtime, false}, + touched{runtime, false}, + focused{runtime, false}, + open{runtime, false}, + submitted{runtime, false}, + selection{runtime, Value{ValueList{}}}, + sort{runtime, Value{ValueList{}}}, + activeKey{runtime}, + checksVersion{runtime, 0}, + inner{runtime, nullptr} {} + +ElementState::~ElementState() = default; + +ScreenCore::ScreenCore(std::shared_ptr doc, Session& owner, Dispatcher& calls, + InterpreterOptions const& options, MountOptions const& mount) + : session{owner}, + dispatcher{calls}, + host{options.host}, + onDiagnostic{options.diagnostics}, + borrowed{mount.borrowed}, + depth{mount.depth}, + prefs{session.runtime()}, + submitted{session.runtime(), false}, + pendingWork{session.runtime(), 0}, + recording{owner.options().developmentTools == DevelopmentTools::On}, + _doc{std::move(doc)} { + ValueRecord defaults; + for (auto const& [name, point] : _doc->customize) { + defaults.insert_or_assign(name, point.defaultValue); + } + prefDefaults = defaults; + prefs.set(std::move(defaults)); + session.attachScreen(*this); +} + +RtScope::~RtScope() { + // A grid of a form calls back into its form's session, an element declared before it. + for (auto const& element : elements) { + element->fieldGrids.clear(); + element->gridTable.reset(); + } + if (core.recording) { + std::erase(core.scopes, this); + } + if (owner != nullptr) { + core.addPending(-1); + if (owner->inner.peek() == this) { + owner->inner.set(nullptr); + } + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): lowers one `rows` table: its columns, groups, summaries, selection and options in document order, each reading the element and config the previous set up +Node ScreenCore::lowerRows(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + ExprPtr const rowsExpr = node.prop("rows"); + if (!rowsExpr) { + report(node.path, "a model-backed `table` needs the table engine, which this interpreter does not lower yet"); + return ui::text(Text{.text = std::string{"table"}, .role = TextRole::Muted}); + } + std::function()> rows = [scope = ctx.scope, bindings = ctx.bindings, rowsExpr] { + Value const value = evalIn(*scope, bindings.get(), rowsExpr); + ValueList const* const items = value.asList(); + return items == nullptr ? std::vector{} : std::vector{items->begin(), items->end()}; + }; + auto keyFn = [scope = ctx.scope, bindings = ctx.bindings, keyExpr = node.prop("key")](Value const& row) -> Key { + if (Value const* const heading = row.field(kGroupHeadingField); heading != nullptr && heading->asString()) { + return Key{*heading->asString()}; + } + if (!keyExpr) { + Value const rowKey = rowId(row); + return keyOf(rowKey.isNull() ? row : rowKey); + } + ScopeEnv const env{*scope, bindings.get(), &row}; + return keyOf(evaluate(*keyExpr, env)); + }; + if (node.kind == "forEach") { + std::vector content; + for (DocNodePtr const& child : node.nodes("children")) { + content.push_back(child.get()); + } + auto rowView = [this, ctx, &node, content, keyFn](reactive::Signal const& row) -> Node { + std::string key = runtime().untracked([&] { return canonicalJson(valueOfKey(keyFn(row.peek()))); }); + auto const scope = rowScope(node, ctx, row, content, std::move(key)); + LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; + std::vector children; + children.reserve(content.size()); + for (DocNode const* const child : content) { + children.push_back(lower(*child, rowCtx)); + } + return holding(std::move(children), scope); + }; + ExprPtr const axis = node.prop("axis"); + ExprPtr const gap = node.prop("gap"); + Common common; + commonOf(node, ctx, element, common); + Axis const along = axis ? axisOf(once(ctx, axis)) : Axis::Vertical; + bool wrap = node.flag("wrap"); + if (wrap && along != Axis::Horizontal) { + // Only a computed axis gets here: the loader refuses a literal one that is not horizontal. + report(node.path + "/wrap", + "`wrap` fills lines along a row; this `forEach`'s `axis` is not \"horizontal\""); + wrap = false; + } + bool divided = node.flag("divided"); + if (divided && along != Axis::Vertical) { + report(node.path + "/divided", + "`divided` draws rules between rows of a column; this `forEach`'s `axis` is \"horizontal\""); + divided = false; + } + return ui::forEach(std::move(rows), std::move(keyFn), std::move(rowView), along, + gap ? static_cast(intOf(once(ctx, gap), 0)) : 0, common, wrap, divided); + } + // The table's rows on the engine: the element's own, which its element values read too, unless names bound + // where the table is lowered (a component's `props`) reach its rows, which the element cannot see; then one of + // the lowering's own, kept by the mount. + RowsTable* table = element == nullptr ? nullptr : element->rowsTable.get(); + std::shared_ptr own; + if (element != nullptr && ctx.bindings != nullptr && !ctx.bindings->empty()) { + own = makeRowsTable(*element, ctx.bindings, false); + table = own.get(); + } + if (table == nullptr) { + report(node.path, "a table over `rows` keeps its rows in its element, and this one has none"); + return ui::text(Text{.text = std::string{"table"}, .role = TextRole::Muted}); + } + reactive::Computed const* const view = table->view.get(); + std::vector columns; + std::vector cells; + std::vector fields; + // One entry per column, in the same order as `cells`/`fields`, each column's role for its default cell. + std::vector roles; + FormatContext const& format = ctx.scope->formatting(); + // The table's `valign` is the default of every column that gives none; the loader checked both names. + Align const tableValign = cellPlaceNamed(node.name("valign")).value_or(Align::Center); + if (ExprPtr const derived = node.prop("columns")) { + Value const list = once(ctx, derived); + // A computed place that names none is reported once for the table, whichever column and key it was. + bool placeReported = false; + auto const placeOf = [&](Value const& item, std::string_view key, Align fallback) { + Value const* const given = item.field(key); + if (given == nullptr || given->isNull()) { + return fallback; + } + std::string const* const name = given->asString(); + std::optional const placed = name == nullptr ? std::nullopt : cellPlaceNamed(*name); + if (!placed && !placeReported) { + placeReported = true; + report(derived->path, "a column's `" + std::string{key} + "` is " + canonicalJson(*given) + + "; a cell's place is start, center or end"); + } + return placed.value_or(fallback); + }; + if (ValueList const* const items = list.asList()) { + for (Value const& item : *items) { + Value const* const field = item.field("id"); + Value const* const label = item.field("label"); + fields.push_back(field == nullptr ? std::string{} : textOf(*field, format)); + columns.push_back(TableColumn{ + .label = textOf(label != nullptr ? *label : Value{fields.back()}, format), + .align = placeOf(item, "align", Align::Start), + .valign = placeOf(item, "valign", tableValign), + }); + cells.push_back(nullptr); + roles.push_back(TextRole::Normal); + } + } + } + for (DocNodePtr const& part : node.partList("columns")) { + ExprPtr const label = part->prop("label"); + ExprPtr const width = part->prop("width"); + ExprPtr const role = part->prop("role"); + TextRole columnRole = TextRole::Normal; + if (role) { + // Read once, with the rest of the column; a value that names no role is reported, as a text's is. + Value const value = once(ctx, role); + std::optional const named = roleNamed(textOf(value, format)); + if (!named) { + report(role->path, "role is " + canonicalJson(value) + "; " + std::string{kRoleNames}); + } + columnRole = named.value_or(TextRole::Normal); + } + bool const shrink = part->flag("shrink"); + Sizing const sized = width ? sizingOf(once(ctx, width)) : Sizing::content(); + if (shrink && sized.kind != Sizing::Kind::Stretch) { + report(part->path + "/shrink", + "`shrink` lets a stretch column go narrower than its header; this column's width does not stretch"); + } + columns.push_back(TableColumn{ + .label = label ? textOf(once(ctx, label), format) : std::string{}, + .width = sized, + .role = columnRole, + .align = cellPlaceNamed(part->name("align")).value_or(Align::Start), + .valign = cellPlaceNamed(part->name("valign")).value_or(tableValign), + .sortable = part->flag("sortable"), + .unit = std::string{part->name("unit")}, + .wrap = part->flag("wrap", true), + .shrink = shrink && sized.kind == Sizing::Kind::Stretch, + }); + // A cell's accent comes from a model's table: a rows table's cells draw no tone or tooltip. + for (std::string_view const key : {"tone", "tooltip"}) { + if (part->prop(key) != nullptr) { + report(pointerAppend(part->path, key), + "`" + std::string{key} + + "` is drawn on a model-backed table's cells; a table over `rows` " + "draws none"); + } + } + cells.push_back(part.get()); + fields.emplace_back(part->id); + roles.push_back(columnRole); + } + // A column's display parts, read once; a rows table's columns have no other source of them. + std::vector> displays; + displays.reserve(cells.size()); + for (DocNode const* const column : cells) { + displays.push_back( + column != nullptr && givesDisplay(*column) + ? std::optional{displayOf(*column, {}, [&](ExprPtr const& expr) { return once(ctx, expr); })} + : std::nullopt); + } + // A column's filter menu: a column part's values, of the kind its cells infer, shown by its display parts. A + // derived column and one whose part says `filterable: false` have none. + table->config.beginMount(); + table->config.filterTarget = [table, cells, displays](std::string const& columnId) -> std::optional { + std::vector const& arranged = table->config.columns; + auto const found = std::ranges::find(arranged, columnId, &LayoutColumn::id); + if (found == arranged.end() || table->source == nullptr) { + return std::nullopt; + } + auto const index = static_cast(found - arranged.begin()); + DocNode const* const part = index < cells.size() ? cells.at(index) : nullptr; + if (part == nullptr || part->id.empty() || !part->flag("filterable", true)) { + return std::nullopt; + } + std::span const infos = table->source->columns(); + auto const info = std::ranges::find(infos, columnId, &table::ColumnInfo::id); + if (info == infos.end()) { + return std::nullopt; + } + FilterTarget target; + target.column = columnId; + target.label = found->label; + target.shown = + table::TableColumn{.info = *info, .display = displays.at(index).value_or(table::ColumnDisplay{})}; + target.listed = true; + return target; + }; + // The row scopes `onActivate` runs in, by the row's canonical key, and the count kept at the last prune. + struct Registry { + std::map, std::less<>> scopes; + std::size_t kept = 64; + }; + auto const registry = std::make_shared(); + // A value that names no tone is reported once for the table, whichever row and value it was. + auto const toneReported = std::make_shared(false); + // Likewise for a `rowSpans` value that is no list of spans. + auto const spansReported = std::make_shared(false); + // Every cell's content is declared in its row's one scope, as a row's own parts are; the mount builds a row's + // parts before its cells, which find that scope in the registry by the row's key. + std::vector cellContent; + for (DocNode const* const column : cells) { + if (column != nullptr) { + for (DocNodePtr const& cell : column->nodes("cell")) { + cellContent.push_back(cell.get()); + } + } + } + auto const keyText = [this, keyFn](Value const& row) { + return runtime().untracked([&] { return canonicalJson(valueOfKey(keyFn(row))); }); + }; + TableSource source; + source.rows = table->rows; + source.alwaysWindowed = false; + // A column with its own `cell` content is lowered in its row's scope; a plain column reads the record alone. + source.rowScopedCells.reserve(cells.size()); + for (DocNode const* const column : cells) { + source.rowScopedCells.push_back(column != nullptr && !column->nodes("cell").empty()); + } + source.rowView = [this, ctx, &node, cellContent, registry, keyText, toneReported, spansReported, fields, own, + table](reactive::Signal const& row) -> TableRowLook { + std::string key = keyText(row.peek()); + if (row.peek().field(kGroupHeadingField) != nullptr) { + return headingRow(node, ctx, row, std::move(key)); + } + auto const scope = rowScope(node, ctx, row, cellContent, key); + registry->scopes[std::move(key)] = scope; + // The scopes that went are dropped once the registry doubles, so a pass that realizes n rows costs O(n). + if (registry->scopes.size() >= 2 * registry->kept) { + std::erase_if(registry->scopes, [](auto const& entry) { return entry.second.expired(); }); + registry->kept = std::max(registry->scopes.size(), 64); + } + LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; + TableRowLook look; + look.keep = scope; + // The row's name, in its own scope: what its select box and assistive technology read. + if (ExprPtr const labelExpr = node.prop("rowLabel")) { + look.label = bindProp(rowCtx, labelExpr, std::string{}, stringOf); + } + if (ExprPtr const toneExpr = node.prop("rowTone")) { + look.tone = slotProp>( + [this, scope, bindings = ctx.bindings, toneExpr, toneReported] -> std::optional { + return rowToneOf(evalIn(*scope, bindings.get(), toneExpr), toneExpr->path, *toneReported); + }); + } + if (ExprPtr const spansExpr = node.prop("rowSpans")) { + look.spans = slotProp>( + [this, scope, bindings = ctx.bindings, spansExpr, spansReported, fields, table] { + std::vector spans = + rowSpansOf(evalIn(*scope, bindings.get(), spansExpr), fields, spansExpr->path, *spansReported); + // A span across a column the user moved away or hid is cut at that column. + std::vector visible = fields; + if (table != nullptr) { + TableConfig const& config = table->config; + visible = layoutOver(config.columns, config.declaredHidden, layoutNow(config)).visible(); + } + std::erase_if(spans, [&](RowSpan& span) { + span.columns = cutColumns( + CellSpan{.column = fields.at(span.column), .rows = span.rows, .columns = span.columns}, + fields, visible); + return span.columns == 0; + }); + return spans; + }); + } + return look; + }; + // A field's text as a column's default cell shows it: by the column's display parts, of the kind the value has, + // or the value's own text. A copy writes it for every column, one with its own `cell` too. + auto const plainText = [](Value const* value, std::optional const& display, + FormatContext const& formatting) { + if (display) { + Value const shown = value == nullptr ? Value{} : *value; + table::TableColumn const kind = columnFor(shown, *display); + table::Cell const cell = cellOfRecord(value, kind, nullptr); + std::string text = formatCell(cell, kind, formatting); + // A quantity keeps its unit after its formatted amount, as its own text writes it; a label's text stands + // for the value whole and takes none. + std::optional const operand = operandOf(cell, kind); + bool const labelled = operand && std::ranges::any_of(display->labels, [&](table::ValueLabel const& label) { + return detail::cells::sameOperand(label.operand, *operand, kind.info.kind); + }); + if (Quantity const* const quantity = shown.asQuantity(); + quantity != nullptr && !text.empty() && !labelled) { + auto const unit = formatting.units.find(quantity->unit); + bool const named = unit != formatting.units.end() && !unit->second.display.empty(); + text += " " + (named ? unit->second.display : quantity->unit); + } + return text; + } + return value == nullptr ? std::string{} : textOf(*value, formatting); + }; + source.cellView = [this, ctx, &node, cells, fields, roles, keyText, registry, displays, plainText]( + std::size_t column, reactive::Signal const& row) -> Node { + DocNode const* const part = column < cells.size() ? cells.at(column) : nullptr; + auto const nodes = part == nullptr ? std::span{} : part->nodes("cell"); + if (nodes.empty()) { + return ui::text(Text{ + .text = slotProp( + [scope = ctx.scope, &row, field = fields.at(column), display = displays.at(column), plainText] { + return plainText(row.get().field(field), display, scope->formatting()); + }), + .role = roles.at(column), + }); + } + std::string key = keyText(row.peek()); + auto const found = registry->scopes.find(key); + std::shared_ptr scope = found == registry->scopes.end() ? nullptr : found->second.lock(); + if (scope == nullptr) { + std::vector cellNodes; + for (DocNodePtr const& cell : nodes) { + cellNodes.push_back(cell.get()); + } + scope = rowScope(node, ctx, row, cellNodes, std::move(key)); + } + LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; + // The cell owns its row's scope as long as its node lives. + auto const owner = + std::make_shared> const>(lowerAll(nodes, rowCtx), scope); + return Node{owner, owner->first.get()}; + }; + // Summary rows: the table's `summaries` before or after its page's rows and each run's after the run, rows of a + // decorator the table keeps over the page's entries. A summary reads every row of the view, or its run's, not + // the page's alone. Every column's cells are built per row, so a data cell is never rebound to a summary row. + std::vector tableSummaries = summarySpecsOf(node.partList("summaries")); + std::span const groupParts = node.partList("group"); + std::vector runSummaries = + groupParts.empty() ? std::vector{} : summarySpecsOf(groupParts.front()->partList("summaries")); + if (!tableSummaries.empty() || !runSummaries.empty()) { + if (table->summaries == nullptr) { + SummaryRows::Runs runs; + if (!groupParts.empty()) { + runs = [table] { return rowsRuns(*table); }; + } + table->summaries = std::make_shared(table->rows, std::move(tableSummaries), + std::move(runSummaries), std::move(runs)); + } + source.rows = table->summaries; + source.rowScopedCells.assign(fields.size(), true); + source.cellView = [this, ctx, &node, table, fields, displays, plainText, inner = source.cellView]( + std::size_t column, reactive::Signal const& row) -> Node { + Value const& record = row.peek(); + if (record.field(kSummaryField) == nullptr) { + return inner(column, row); + } + std::string const columnId = column < fields.size() ? fields.at(column) : std::string{}; + Text text; + text.common.testId = summaryTestId(record, columnId); + text.text = slotProp( + [this, &node, ctx, table, record = &row, columnId, display = displays.at(column), plainText] { + Value const& now = record->get(); + std::optional const value = + summaryValue(node, now, columnId, ctx, rowsSummaryScope(*table, now)); + return value ? plainText(&*value, display, ctx.scope->formatting()) : std::string{}; + }); + return ui::text(std::move(text)); + }; + source.rowView = [this, ctx, &node, + inner = source.rowView](reactive::Signal const& row) -> TableRowLook { + if (row.peek().field(kSummaryField) != nullptr) { + return summaryLook(node, ctx, row.peek()); + } + return inner(row); + }; + } + TableOptions options; + options.showHeader = node.flag("showHeader", true); + options.bands = bandsOf(node.partList("bands")); + options.selectColumn = node.flag("selectColumn"); + if (ExprPtr const selectAll = node.prop("selectAllLabel")) { + options.selectAllLabel = bindProp(ctx, selectAll, std::string{}, stringOf); + } + if (ExprPtr const threshold = node.prop("virtualizeThreshold")) { + options.virtualize.threshold = + static_cast(std::max(0, intOf(once(ctx, threshold), 2000))); + } + if (ExprPtr const overscan = node.prop("virtualizeOverscan")) { + options.virtualize.overscan = + static_cast(std::max(0, intOf(once(ctx, overscan), 10))); + } + std::string const mode = + node.prop("selectionMode") ? textOf(once(ctx, node.prop("selectionMode")), format) : std::string{}; + options.selectionMode = SelectionMode::None; + if (mode == "single") { + options.selectionMode = SelectionMode::Single; + } else if (mode == "multiple") { + options.selectionMode = SelectionMode::Multiple; + } + // The status line: its counts, and the latest message; it takes space while it has something to say, or always + // or never as a literal `status` says. + options.status = slotProp([element, table, scope = ctx.scope] { + static_cast(table->version.get()); + TableStatus status; + Value const selectedValue = tableSelection(*element); + ValueList const* const selected = selectedValue.asList(); + status.counts = + countsText(table->rows->counts(), selected == nullptr ? 0 : static_cast(selected->size()), + scope->formatting()); + status.message = table->status == false ? std::string{} : table->message.get(); + status.shown = table->status.value_or(!status.state.empty() || !status.message.empty()); + return status; + }); + // The selection the table shows: the bound `selection`, or the table's own. A slot even for a literal list, so + // a bound selection is fixed until the document writes it, and a user's change the document leaves unwritten + // snaps back. A bound value that is neither a list nor `null` is reported once. + auto const selectionReported = std::make_shared(false); + options.selection = slotProp>([this, element, selectionReported, path = node.path] { + std::vector keys; + if (element->bound != nullptr) { + Value const bound = element->bound->get(); + if (!bound.isNull() && bound.asList() == nullptr && !*selectionReported) { + *selectionReported = true; + report(pointerAppend(path, "selection"), + "selection is " + canonicalJson(bound) + "; a table's selection is a list of keys"); + } + } + Value const selection = tableSelection(*element); + if (ValueList const* const items = selection.asList()) { + for (Value const& item : *items) { + keys.push_back(keyOf(item)); + } + } + return keys; + }); + // A user's change: the table's own selection takes it when no key binds one, then `onSelectionChange` runs with + // `event` the new selection, in the table's scope, in the same batch. The backend holds one page: a `Replace` + // is the whole new selection, and an `Extend` keeps the selected keys of the rows on other pages, before the + // reported ones. A key whose row `rows` no longer has drops on any user change. + options.onSelectionChange = [this, ctx, element, view, keyFn, own, commands = node.event("onSelectionChange")]( + std::vector const& keys, SelectionChange change) { + ValueList items; + if (change == SelectionChange::Extend) { + items = runtime().untracked([&] { return selectedOffPage(view->get(), tableSelection(*element), keyFn); }); + } + // A heading is never selected. A virtualized backend knows the keys of rows it has not realized but not + // which of them are headings, so its Ctrl+A or range can name one. + for (Key const& key : keys) { + if (std::string const* const text = std::get_if(&key); + text != nullptr && text->starts_with("\x1Fgroup:")) { + continue; + } + items.push_back(valueOfKey(key)); + } + Value const selected{std::move(items)}; + runtime().batch([&] { + if (element->bound == nullptr) { + session.asUser([&] { + session.noteWrite(); + element->selection.set(selected); + }); + } + runEvent(commands, ctx, selected); + }); + }; + // Select-all selects the engine's view, every page, through the table's selection; when every row of the view + // is selected already it clears them, as a short table's Ctrl+A does. + if (options.selectionMode == SelectionMode::Multiple) { + options.onSelectAll = [this, ctx, element, table, own, commands = node.event("onSelectionChange")] { + auto selection = table::Selection::create(table::SelectionOptions{.mode = table::SelectionMode::Multiple, + .pruneOnFilter = false, + .tableMode = table::TableMode::Client}); + if (!selection || !selection->selectAll(table->engine->engine())) { + return; + } + std::unordered_set held; + runtime().untracked([&] { + if (Value const itemsValue = tableSelection(*element); + ValueList const* const items = itemsValue.asList()) { + for (Value const& item : *items) { + held.insert(keyOf(item)); + } + } + }); + bool const every = std::ranges::all_of(selection->keys(), + [&held](table::RowId const& key) { return held.contains(key); }); + ValueList items; + if (!every) { + for (table::RowId const& key : selection->keys()) { + items.push_back(valueOfKey(key)); + } + } + Value const selected{std::move(items)}; + runtime().batch([&] { + if (element->bound == nullptr) { + session.asUser([&] { + session.noteWrite(); + element->selection.set(selected); + }); + } + runEvent(commands, ctx, selected); + }); + }; + } + // A copy reads the view, which holds every row; the focus names a column by its layout id. + for (std::size_t at = 0; at < columns.size() && at < table->config.columns.size(); ++at) { + columns.at(at).id = table->config.columns.at(at).id; + } + auto const headers = std::make_shared>(); + for (TableColumn const& column : columns) { + headers->push_back(headerText(column.label, column.unit)); + } + // A cell a menu opens on, read as its column's filter reads it: by the kind the column's cells infer and the + // column's display parts. + table->config.heldCell = [table, fields, displays](Key const& key, + std::string const& columnId) -> std::optional { + std::vector const& arranged = table->config.columns; + auto const found = std::ranges::find(arranged, columnId, &LayoutColumn::id); + auto const index = static_cast(found - arranged.begin()); + if (found == arranged.end() || index >= fields.size() || table->source == nullptr || + table->engine == nullptr) { + return std::nullopt; + } + std::span const infos = table->source->columns(); + auto const info = std::ranges::find(infos, columnId, &table::ColumnInfo::id); + if (info == infos.end()) { + return std::nullopt; + } + table::TableColumn const shown{.info = *info, .display = displays.at(index).value_or(table::ColumnDisplay{})}; + EngineRows const& engineRows = *table->engine; + std::int64_t const total = engineRows.total().rows; + for (std::int64_t row = 0; row < total; ++row) { + std::optional const ref = engineRows.row(row); + if (ref && ref->key == key) { + return HeldCell{.record = ref->row, + .cell = cellOfRecord(ref->row.field(fields.at(index)), shown, nullptr), + .shown = shown, + .units = {}, + .keep = nullptr}; + } + } + return std::nullopt; + }; + // The engine's view holds every row, its record the row as `rows` gave it. + table->config.gather = [table, fields, displays, plainText, headers, scope = ctx.scope]( + std::vector keys, std::vector const& ids, CopyDone const& done) { + std::vector places; + CopyGathered gathered; + std::vector const& arranged = table->config.columns; + for (std::string const& columnId : ids) { + auto const found = std::ranges::find(arranged, columnId, &LayoutColumn::id); + auto const place = static_cast(found - arranged.begin()); + if (found != arranged.end() && place < fields.size() && place < headers->size()) { + places.push_back(place); + gathered.headers.push_back(headers->at(place)); + } + } + FormatContext const& formatting = scope->formatting(); + std::unordered_set wanted{keys.begin(), keys.end()}; + EngineRows const& engineRows = *table->engine; + std::int64_t const total = engineRows.total().rows; + for (std::int64_t at = 0; at < total && !wanted.empty(); ++at) { + std::optional const ref = engineRows.row(at); + if (!ref || wanted.erase(ref->key) == 0) { + continue; + } + CopyRow copied{.viewRow = at, .cells = {}}; + for (std::size_t const place : places) { + copied.cells.emplace_back(plainText(ref->row.field(fields.at(place)), displays.at(place), formatting)); + } + gathered.rows.push_back(std::move(copied)); + } + done(std::move(gathered)); + }; + // The header's sort chain and menus, and the columns' arrangement; the column chooser and the sort dialog. + Node dialogs = configureTable(table->config, ctx, options, own); + markFilterable(table->config, columns, options); + options.onActivate = [this, ctx, element, registry, commands = node.event("onActivate")](Key const& key) { + Value const activated = valueOfKey(key); + session.asUser([&] { + session.noteWrite(); + element->activeKey.set(activated); + }); + auto const found = registry->scopes.find(canonicalJson(activated)); + std::shared_ptr const scope = found == registry->scopes.end() ? nullptr : found->second.lock(); + LowerCtx const rowCtx{.scope = scope ? scope : ctx.scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; + runEvent(commands, rowCtx, activated); + }; + commonOf(node, ctx, element, options.common); + std::span const empty = node.nodes("empty"); + if (empty.empty()) { + return besideDialogs(options.common, std::move(dialogs), + [&] { return ui::table(std::move(columns), std::move(source), std::move(options)); }); + } + // With `empty`, a column holds the table and the content shown in its place while `rows` is an empty list; a + // `null` (a query not answered yet) shows the table. The column is placed as the table would be: it takes the + // node's visibility and layout, and every other common property stays on the table, so its test id and the + // element id `focus` finds name the table. + auto const listed = [scope = ctx.scope, bindings = ctx.bindings, rowsExpr] { + Value const itemsValue = evalIn(*scope, bindings.get(), rowsExpr); + ValueList const* const items = itemsValue.asList(); + return items == nullptr || !items->empty(); + }; + Column wrapper; + wrapper.common.visible = std::move(options.common.visible); + wrapper.common.layout = options.common.layout; + options.common.layout = wrappedTableLayout(options.common.layout); + options.common.visible = slotProp(listed); + Column content{.children = {lowerAll(empty, ctx)}}; + content.common.visible = slotProp([listed] { return !listed(); }); + wrapper.children.push_back(ui::table(std::move(columns), std::move(source), std::move(options))); + wrapper.children.push_back(ui::column(std::move(content))); + wrapper.children.push_back(std::move(dialogs)); + return ui::column(std::move(wrapper)); +} + +[[nodiscard]] SortChain sortChainOf(Value const& value) { + SortChain chain; + ValueList const* const keys = value.asList(); + if (keys == nullptr) { + return chain; + } + for (Value const& key : *keys) { + Value const* const column = key.field("column"); + if (column == nullptr || column->asString() == nullptr) { + continue; + } + Value const* const direction = key.field("direction"); + bool const descending = + direction != nullptr && direction->asString() != nullptr && *direction->asString() == "desc"; + chain.push_back( + table::SortKey{.column = *column->asString(), + .dir = descending ? table::SortDirection::Descending : table::SortDirection::Ascending}); + } + return chain; +} + +[[nodiscard]] Value sortValueOf(SortChain const& chain) { + ValueList keys; + for (table::SortKey const& key : chain) { + ValueRecord entry; + entry.insert_or_assign("column", Value{key.column}); + entry.insert_or_assign("direction", + Value{std::string{key.dir == table::SortDirection::Descending ? "desc" : "asc"}}); + keys.emplace_back(std::move(entry)); + } + return Value{std::move(keys)}; +} + +// NOLINTBEGIN(misc-no-recursion): an expression, a command list and a document nest, and each walk follows its own +// nesting. +void rowReadsOf(Expr const& expr, RowReads& out, bool readFrom) { + // A cell menu's entries also name their row `row`. + if (expr.kind == ExprKind::Ref && expr.name == "row") { + if (!expr.fieldPath.empty()) { + out.ids.insert(expr.fieldPath.front()); + } else if (!readFrom) { + out.whole = true; + } + return; + } + if (expr.kind == ExprKind::Row) { + if (!expr.fieldPath.empty()) { + out.ids.insert(expr.fieldPath.front()); + } else if (!readFrom) { + out.whole = true; + } + return; + } + if (expr.kind == ExprKind::Get) { + rowReadsOf(*expr.args.at(0), out, true); + return; + } + for (ExprPtr const& arg : expr.args) { + if (arg) { + rowReadsOf(*arg, out); + } + } + for (auto const& [name, field] : expr.fields) { + static_cast(name); + if (field) { + rowReadsOf(*field, out); + } + } +} + +void rowReadsOf(Commands const& commands, RowReads& out) { + for (Command const& command : commands) { + for (ExprPtr const* const expr : {&command.value, &command.extra, &command.mediaType}) { + if (*expr) { + rowReadsOf(**expr, out); + } + } + rowReadsOf(command.commands, out); + rowReadsOf(command.alternative, out); + } +} + +void rowReadsOf(DocNode const& node, RowReads& out) { + for (auto const& [key, expr] : node.props) { + static_cast(key); + if (expr) { + rowReadsOf(*expr, out); + } + } + for (auto const& [key, commands] : node.events) { + static_cast(key); + rowReadsOf(commands, out); + } + for (auto const& [key, nodes] : node.children) { + static_cast(key); + for (DocNodePtr const& child : nodes) { + rowReadsOf(*child, out); + } + } + for (auto const& [key, parts] : node.parts) { + static_cast(key); + for (DocNodePtr const& part : parts) { + rowReadsOf(*part, out); + } + } +} +// NOLINTEND(misc-no-recursion) + +[[nodiscard]] std::string levelWords(std::string level) { + if (!level.empty() && level.front() >= 'a' && level.front() <= 'z') { + level.front() = static_cast(level.front() - 'a' + 'A'); + } + return level; +} + +[[nodiscard]] std::optional columnKindNamed(std::string_view name) { + static constexpr std::array, 7> kKinds = {{ + {"text", table::ColumnKind::Text}, + {"integer", table::ColumnKind::Integer}, + {"decimal", table::ColumnKind::Decimal}, + {"number", table::ColumnKind::Number}, + {"date", table::ColumnKind::Date}, + {"dateTime", table::ColumnKind::DateTime}, + {"bool", table::ColumnKind::Bool}, + }}; + // NOLINTNEXTLINE(readability-qualified-auto): an array iterator is a pointer on some standard libraries only. + auto const found = std::ranges::find(kKinds, name, &std::pair::first); + return found == kKinds.end() ? std::nullopt : std::optional{found->second}; +} + +namespace { + +/// @brief The registry a table over `rows` reads its quantities' units from: each unit of the screen's table in the +/// dimension of its canonical unit, each canonical unit the table names but does not list, and each unit the +/// rows brought that the table does not know, which is its own canonical unit, as an expression reads it. +/// @param units The screen's units. +/// @param seen The units the rows brought. +/// @return The registry. +[[nodiscard]] std::shared_ptr registryOfUnits( + UnitTable const& units, std::set> const& seen) { + table::UnitRegistryBuilder builder; + auto const add = [&builder](std::string const& columnId, std::string const& canonical, math::Rational factor) { + std::ignore = (builder.add(table::UnitInfo{ + .id = columnId, .symbol = columnId, .dimension = canonical, .toBase = factor, .decimals = 0})); + }; + for (auto const& [unitId, info] : units) { + add(unitId, info.canonical.empty() ? unitId : info.canonical, info.toCanonical); + } + for (auto const& [unitId, info] : units) { + if (!info.canonical.empty() && !units.contains(info.canonical)) { + add(info.canonical, info.canonical, math::Rational{1, math::DecimalPlaces{0}}); + } + } + // A unit already added (a canonical one) is refused by the builder and keeps its first entry. + for (std::string const& columnId : seen) { + if (!units.contains(columnId)) { + add(columnId, columnId, math::Rational{1, math::DecimalPlaces{0}}); + } + } + return std::move(builder).build(); +} + +} // namespace + +void startRowsEngine(RowsTable& table, reactive::Runtime& runtime) { + auto const registry = registryOfUnits(table.units, table.unitsSeen); + auto source = std::make_shared(runtime, table.columns, table.keyOfRow, registry); + source->setGroups(table.groups); + // The runs are the leading key of every sort the engine is given, a column the engine knows from its start. + if (table.byOf) { + source->setGroup(table.byOf, table.units); + } + table::EngineOptions options; + options.owner = &runtime.owner(); + options.worker = nullptr; + options.frameBudget = std::chrono::milliseconds{4}; + options.services.collator = std::make_shared(); + options.services.units = registry; + auto const engine = + std::make_shared(source, morph::ui::ValueRowsSource::recordOf(), std::move(options)); + bool const restoring = table.engine != nullptr && table.engine->restoring(); + table::FilterSpec const filter = table.engine != nullptr ? table.engine->engine().filter() : table::FilterSpec{}; + if (table.engine != nullptr) { + table.engine->onChange({}); + for (std::string const& column : table.used) { + table.source->unuse(column); + } + if (table.byOf) { + table.source->setGroup({}, {}); + } + } + for (std::string const& column : table.used) { + source->use(column); + } + engine->setRestoring(restoring); + table.source = std::move(source); + table.engine = engine; + if (table.rows != nullptr) { + table.rows->setEngine(engine); + } else { + table.rows = std::make_shared(engine, runtime.owner()); + } + if (table.elementOwn) { + table.element->tableRows = engine; + } + engine->onChange(table.heard); + SortChain ordered; + if (table.byOf) { + ordered.push_back( + table::SortKey{.column = std::string{kGroupRunColumn}, .dir = table::SortDirection::Ascending}); + } + ordered.insert(ordered.end(), table.sort.begin(), table.sort.end()); + std::ignore = (engine->setSort(std::move(ordered))); + if (!filter.empty()) { + std::ignore = (engine->setFilter(filter)); + } +} + +[[nodiscard]] std::vector usedColumns(RowsTable const& table, SortChain const& sort, + table::FilterSpec const& filter) { + std::vector out; + auto const add = [&out](std::string const& columnId) { + if (!std::ranges::contains(out, columnId)) { + out.push_back(columnId); + } + }; + for (table::SortKey const& key : sort) { + add(key.column); + } + for (auto const& [columnId, column] : filter.columns) { + static_cast(column); + add(columnId); + } + for (table::GroupFilter const& group : filter.groups) { + auto const declared = std::ranges::find(table.groups, group.group, &table::ColumnGroupInfo::id); + std::vector const members = + !group.group.empty() && declared != table.groups.end() ? declared->columns : group.columns; + for (std::string const& columnId : members) { + add(columnId); + } + } + for (std::string const& columnId : table.listedColumns) { + add(columnId); + } + return out; +} + +void useColumns(RowsTable& table, std::vector next) { + for (std::string const& column : next) { + if (!std::ranges::contains(table.used, column)) { + table.source->use(column); + } + } + for (std::string const& column : table.used) { + if (!std::ranges::contains(next, column)) { + table.source->unuse(column); + } + } + table.used = std::move(next); +} + +[[nodiscard]] std::string groupedCount(std::size_t count) { + std::string digits = std::to_string(count); + for (auto at = static_cast(digits.size()) - 3; at > 0; at -= 3) { + digits.insert(static_cast(at), ","); + } + return digits; +} + +void loadStateAndViews(TableStates& states, table::TableStateKey const& key, TableViews& views, + async::CallbackScope const& scope, + std::function const&, std::string const&)> done) { + struct Joined { + int waiting = 2; + std::optional json; + std::string failure; + std::function const&, std::string const&)> done; + }; + auto const joined = + std::make_shared(Joined{.waiting = 2, .json = {}, .failure = {}, .done = std::move(done)}); + auto const arrive = [joined] { + if (--joined->waiting == 0) { + joined->done(joined->json, joined->failure); + } + }; + views.load() + .then(scope, [arrive](TableViews::Result const&) { arrive(); }) + .onError(scope, [arrive](std::exception_ptr const&) { arrive(); }); + states.load(key) + .then(scope, + [joined, arrive](std::optional const& stored) { + if (stored) { + joined->json = stored->json; + } + arrive(); + }) + .onError(scope, [joined, arrive](std::exception_ptr const& error) { + joined->failure = failureText(error); + arrive(); + }); +} + +} // namespace detail + +} // namespace morph::ui diff --git a/src/ui/interpreter_table_actions.cpp b/src/ui/interpreter_table_actions.cpp new file mode 100644 index 000000000..8aeaddf0a --- /dev/null +++ b/src/ui/interpreter_table_actions.cpp @@ -0,0 +1,1629 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Tables over an action's rows and over a model. + +#include "interpreter_grid_detail.hpp" + +namespace morph::ui::detail { + +namespace { + +/// What a table over a typed list action is built from: its description, the columns whose kind its first reply +/// decides, the request member its query goes in, the records it watches, and what stops it being paged. +struct ActionTable { + table::TableDescription description; + std::vector inferKinds; + std::string queryMember; + std::vector records; + /// Empty when the table can be paged. + std::string problem; + /// Empty when the node's `key`, if any, reads one row field. + std::string keyProblem; + /// What the view document's units say that is not taken: a factor of zero or less, or a unit two columns + /// declare differently. + std::vector unitProblems; +}; + +/// One `v-columns` entry of a view document, as a table over the action reads it. +struct ViewColumn { + std::string label; + std::optional kind; + bool hidden = false; + /// The units the column's quantities are in: its `ExtUnits` and each `x-unitAlternatives` entry. + std::vector units; +}; + +/// The units a `v-columns` entry declares: its `ExtUnits` (`unitAscii` the id, `unitUnicode` the symbol) as the +/// canonical unit, at `x-decimalPlaces`, and each `x-unitAlternatives` entry (`id`, `display`, `decimals`, and +/// `num`/`den`, its factor to the canonical unit, 1 when absent), all in one dimension named by the canonical unit's +/// id. An alternative whose factor is zero or less is left out and said in @p problems. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): reads each `v-columns` entry's canonical unit and its alternatives into one dimension, in the order the schema lists them +std::vector viewUnitsOf(Json::object_t const& fields, std::vector& problems) { + std::vector out; + auto const member = [](Json::object_t const& object, std::string_view name) -> Json const* { + const auto* const found = object.find(name); + return found == object.end() ? nullptr : &found->second; + }; + auto const textOf = [&member](Json::object_t const& object, std::string_view name) -> std::string const* { + Json const* const value = member(object, name); + return value == nullptr ? nullptr : std::get_if(&value->data); + }; + auto const integerOf = [&member](Json::object_t const& object, + std::string_view name) -> std::optional { + Json const* const value = member(object, name); + if (value == nullptr) { + return std::nullopt; + } + if (auto const* const signedValue = std::get_if(&value->data)) { + return *signedValue; + } + if (auto const* const unsignedValue = std::get_if(&value->data); + unsignedValue != nullptr && *unsignedValue <= static_cast(INT64_MAX)) { + return static_cast(*unsignedValue); + } + return std::nullopt; + }; + auto const places = [](std::optional value) { + return static_cast(std::clamp(value.value_or(0), 0, math::kMaxDecimalPlaces)); + }; + Json const* const ext = member(fields, "ExtUnits"); + auto const* const extFields = ext != nullptr ? std::get_if(&ext->data) : nullptr; + std::string const* const ascii = extFields != nullptr ? textOf(*extFields, "unitAscii") : nullptr; + if (ascii == nullptr || ascii->empty()) { + return out; + } + std::string const* const unicode = textOf(*extFields, "unitUnicode"); + out.push_back(table::UnitInfo{.id = *ascii, + .symbol = unicode != nullptr && !unicode->empty() ? *unicode : *ascii, + .dimension = *ascii, + .toBase = math::Rational{1, math::DecimalPlaces{0}}, + .decimals = places(integerOf(fields, "x-decimalPlaces"))}); + Json const* const alternatives = member(fields, "x-unitAlternatives"); + auto const* const entries = alternatives != nullptr ? std::get_if(&alternatives->data) : nullptr; + for (Json const& entry : entries != nullptr ? std::span{*entries} : std::span{}) { + auto const* const alternative = std::get_if(&entry.data); + std::string const* const columnId = alternative != nullptr ? textOf(*alternative, "id") : nullptr; + if (columnId == nullptr || columnId->empty() || std::ranges::contains(out, *columnId, &table::UnitInfo::id)) { + continue; + } + auto const num = integerOf(*alternative, "num").value_or(1); + auto const den = integerOf(*alternative, "den").value_or(1); + if (num <= 0 || den <= 0) { + problems.push_back("the unit `" + *columnId + "` has a factor of zero or less; it is not listed"); + continue; + } + std::string const* const display = textOf(*alternative, "display"); + out.push_back(table::UnitInfo{.id = *columnId, + .symbol = display != nullptr && !display->empty() ? *display : *columnId, + .dimension = *ascii, + .toBase = math::Rational{math::Numerator{num}, math::Denominator{den}, + math::DecimalPlaces{math::kMaxDecimalPlaces}}, + .decimals = places(integerOf(*alternative, "decimals"))}); + } + return out; +} + +/// Lists one column's units beside the units listed already, so the order of the columns does not matter: a column +/// one of whose units is listed joins that unit's dimension, its factors scaled through that unit; any other starts +/// its own. A unit listed already with another dimension or factor is said in @p problems and kept as first listed. +void listViewUnits(std::span column, std::vector& listed, + std::vector& problems) { + if (column.empty()) { + return; + } + std::string dimension = column.front().dimension; + math::Rational scale{1, math::DecimalPlaces{0}}; + for (table::UnitInfo const& unit : column) { + auto const found = std::ranges::find(listed, unit.id, &table::UnitInfo::id); + if (found != listed.end()) { + dimension = found->dimension; + scale = (found->toBase / unit.toBase).value_or(scale); + break; + } + } + for (table::UnitInfo unit : column) { + unit.dimension = dimension; + unit.toBase = unit.toBase * scale; + auto const found = std::ranges::find(listed, unit.id, &table::UnitInfo::id); + if (found == listed.end()) { + listed.push_back(std::move(unit)); + } else if (found->dimension != unit.dimension || found->toBase != unit.toBase) { + problems.push_back("the unit `" + unit.id + "` is declared differently by two columns; the first is kept"); + } + } +} + +/// The table a typed list action's node describes. The columns are the node's `columns` parts, else the view +/// document's `v-columns`; the key is the node's `key` when it reads one row field, else the view document's +/// `v-rowKey`, else `id`; a column's kind is the part's literal `kind`, else its `v-columns` entry's, else the first +/// reply's. A catalog carries no reply schema, so nothing else can say what the rows hold. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): the schema, the view document, then the columns. +ActionTable actionTableOf(DocNode const& node, Catalog const& catalog) { + ActionTable out; + std::string const action{node.name("action")}; + if (catalog.action) { + if (std::optional const info = catalog.action(action)) { + for (ActionRecordInfo const& record : info->records) { + out.records.push_back(record.record); + } + } + } + if (catalog.schema) { + if (std::optional const schema = catalog.schema(action)) { + std::vector const members = tableQueryMembers(*schema); + if (members.size() == 1) { + out.queryMember = members.front(); + } + } + } + if (out.queryMember.empty()) { + out.problem = "a table over an action needs a query member marked x-table"; + out.queryMember = "query"; + } + std::vector> viewColumns; + std::string viewKey; + std::optional const view = catalog.view ? catalog.view(action) : std::nullopt; + if (view) { + auto const json = parseJson(*view); + auto const* const object = json ? std::get_if(&json->data) : nullptr; + if (object != nullptr) { + if (const auto* const key = object->find("v-rowKey"); key != object->end()) { + if (auto const* const text = std::get_if(&key->second.data)) { + viewKey = *text; + } + } + const auto* const columns = object->find("v-columns"); + auto const* const entries = + columns != object->end() ? std::get_if(&columns->second.data) : nullptr; + for (Json const& entry : entries != nullptr ? std::span{*entries} : std::span{}) { + auto const* const fields = std::get_if(&entry.data); + auto const text = [fields](std::string_view name) -> std::string const* { + const auto* const found = fields->find(name); + return found == fields->end() ? nullptr : std::get_if(&found->second.data); + }; + std::string const* const field = fields != nullptr ? text("field") : nullptr; + if (field == nullptr) { + continue; + } + ViewColumn column; + std::string const* const label = text("label"); + column.label = label != nullptr ? *label : *field; + if (std::string const* const kind = text("kind")) { + table::ColumnKind parsed{}; + if (!glz::read_json(parsed, "\"" + *kind + "\"")) { + column.kind = parsed; + } + } + const auto* const hidden = fields->find("v-hidden"); + column.hidden = hidden != fields->end() && std::get_if(&hidden->second.data) != nullptr && + *std::get_if(&hidden->second.data); + // A column of quantities with units is read as measures, each cell naming its unit. + column.units = viewUnitsOf(*fields, out.unitProblems); + if (!column.units.empty() && column.kind == table::ColumnKind::Quantity) { + column.kind = table::ColumnKind::Measure; + } + viewColumns.emplace_back(*field, std::move(column)); + } + } + } + auto const viewColumn = [&viewColumns](std::string_view columnId) -> ViewColumn const* { + auto const found = + std::ranges::find(viewColumns, columnId, [](auto const& entry) -> auto const& { return entry.first; }); + return found == viewColumns.end() ? nullptr : &found->second; + }; + auto const add = [&out](std::string columnId, std::string label, std::optional kind, bool shown, + ViewColumn const* described) { + listViewUnits(described != nullptr ? std::span{described->units} + : std::span{}, + out.description.units, out.unitProblems); + if (!kind) { + out.inferKinds.push_back(columnId); + } + out.description.columns.push_back( + table::TableColumn{.info = table::ColumnInfo{.id = std::move(columnId), + .kind = kind.value_or(table::ColumnKind::Text), + .comparator = {}, + .format = {}, + .level = {}}, + .label = std::move(label), + .group = {}, + .sortable = true, + .filterable = true, + .shown = shown}); + }; + if (auto const parts = node.partList("columns"); !parts.empty()) { + for (DocNodePtr const& part : parts) { + ViewColumn const* const described = viewColumn(part->id); + std::optional kind = columnKindNamed(part->name("kind")); + if (!kind && described != nullptr) { + kind = described->kind; + } + add(part->id, described != nullptr ? described->label : part->id, kind, true, described); + } + } else if (view) { + for (auto const& [columnId, column] : viewColumns) { + add(columnId, column.label, column.kind, !column.hidden, &column); + } + } else if (out.problem.empty()) { + out.problem = "a table over an action needs its columns, or a view document for the action"; + } + ExprPtr const key = node.prop("key"); + if (key && key->kind == ExprKind::Row && key->fieldPath.size() == 1) { + out.description.key = key->fieldPath.front(); + } else { + out.description.key = viewKey.empty() ? std::string{"id"} : viewKey; + if (key) { + out.keyProblem = R"(the key of a table over an action is one row field, {"row": ""}; `)" + + out.description.key + "` is used"; + } + } + out.description.id = action; + return out; +} + +/// @brief Keeps a model table's selection of the view true to its rows after they changed: a selection of another +/// filter than the rows hold ends, the description's new revision having dropped a filter included, and a +/// key of `except` a reply left out of the view is dropped from it. +/// @param core The screen. +/// @param element The table's element. +/// @param model The table. +void fitViewSelection(ScreenCore& core, ElementState& element, ModelTable& model) { + std::optional const& current = model.viewSelection.peek(); + if (!current || !current->view) { + return; + } + if (model.window->filter() != current->view->filters) { + core.runtime().batch([&] { + model.viewSelection.set(std::nullopt); + if (element.bound == nullptr) { + core.session.asUser([&] { + core.session.noteWrite(); + element.selection.set(Value{ValueList{}}); + }); + } + }); + return; + } + TableSelection next = *current; + auto const dropped = + std::erase_if(next.except, [&model](table::RowId const& key) { return model.rows->leftView(key); }); + if (dropped > 0) { + model.viewSelection.set(std::move(next)); + } +} + +/// @brief A model table's ear on the session's runs: the rows a run works on are busy until it settles, the rows its +/// reply could not change are marked failed, a row it gave a new key keeps what this session held by its old +/// one, and a run refused because the rows of its selection of this table's view changed is offered again, on +/// the view as it is now, through the status line. +/// +/// Holds the table and its element by reference: the table owns it and removes it before either goes. The screen's +/// scope is held weakly, so the observer keeps nothing of the screen alive. +// A row's key changed: the rows, the drafts and, while an editable table is mounted, its held cells and its focus +// move what they hold by it. +void moveRowKey(ModelTable& model, Key const& from, Key const& target) { + if (std::shared_ptr const grid = model.editGrid.lock()) { + grid->moveKey(from, target); + return; + } + model.rows->moveKey(from, target); + if (model.edits != nullptr) { + model.edits->moveRow(from, target); + } +} + +class TableRuns final : public RunObserver { +public: + TableRuns(ScreenCore& core, ElementState& element, ModelTable& model) + : _core{&core}, _element{&element}, _model{&model} {} + + // The rows the run's input names become busy, and their failed marks go. A run of an action that declares an + // effect on the table's record defers the drop of selected keys that leave the view until it settles, and on a + // table with `retainChanged` holds the refetches its change events cause. + void started(RunStarted const& run) override { + if (_model->rows == nullptr) { + return; + } + markBusy(run); + auto const& catalog = _core->session.options().catalog; + std::optional const info = catalog.action ? catalog.action(run.action) : std::nullopt; + if (!info || !info->effects) { + return; + } + std::string const record = recordName(); + if (std::ranges::none_of(*info->effects, [&record](ActionEffect const& effect) { + return effect.record && *effect.record == record; + })) { + return; + } + _changing.insert(run.run); + if (_model->retainChanged) { + _held.insert(run.run); + _model->rows->holdRefetches(run.run); + } + } + + // A selected key that left the view is dropped from the selection and its failed mark goes; while a run that + // changes the table is in flight the drop waits for it to settle, since its reply may name the key as a row's + // old key, and its own change event can come before it. + void rowsChanged() { + if (_model->rows == nullptr || _model->viewSelection.peek()) { + return; + } + std::vector left; + for (Key const& key : selectedKeys()) { + if (_model->rows->leftView(key)) { + left.push_back(key); + } + } + if (left.empty()) { + return; + } + if (!_changing.empty()) { + _deferred.insert(left.begin(), left.end()); + return; + } + drop(left); + } + + // NOLINTNEXTLINE(readability-function-cognitive-complexity): handles a settled run: its refusal, field errors, failed rows and replies in the order the run reports them + void settled(RunSettled const& run) override { + bool const held = _held.erase(run.run) > 0; + if (_model->rows != nullptr) { + _model->rows->states().settle(run.run); + std::vector moved; + if (run.succeeded) { + applyReply(run, moved); + } + if (held) { + keepChanged(run); + } + if (_changing.erase(run.run) > 0 && _changing.empty()) { + std::vector left; + for (Key const& key : std::exchange(_deferred, {})) { + if (_model->rows->leftView(key) && !std::ranges::contains(moved, key)) { + left.push_back(key); + } + } + drop(left); + } + _model->marksRevision.set(_model->marksRevision.peek() + 1); + if (held) { + _model->rows->releaseRefetches(run.run); + } + } + if (run.refusalCode != "morph.table.viewChanged" || _model->rows == nullptr) { + return; + } + auto const& catalog = _core->session.options().catalog; + std::optional const schema = catalog.schema ? catalog.schema(run.action) : std::nullopt; + ValueRecord const* const body = run.body.asRecord(); + if (!schema || body == nullptr) { + return; + } + std::string const record = _model->modelType + "." + _model->id; + for (TableInput const& input : tableInputsOf(*schema)) { + if (input.kind != TableInputKind::Selection || input.record != record) { + continue; + } + auto const member = body->find(input.member); + Value const* const view = member == body->end() ? nullptr : member->second.field("view"); + if (view == nullptr || view->isNull()) { + continue; + } + // Offered only by a table whose view is the one refused: another table of the record, or this one + // under another filter now, would run the action over rows the user did not select for it. + table::FilterSpec refused; + Value const* const filters = view->field("filters"); + if (filters == nullptr || glz::read_json(refused, canonicalJson(*filters)) || + refused != _model->window->filter()) { + continue; + } + auto taken = _model->rows->selectView(); + if (!taken) { + continue; + } + TableSelection again{.keys = {}, .view = std::move(*taken), .except = {}}; + if (Value const* const except = member->second.field("except"); except != nullptr) { + if (ValueList const* const keys = except->asList()) { + for (Value const& key : *keys) { + again.except.push_back(keyOf(key)); + } + } + } + auto const json = parseJson(selectionJsonOf(again)); + auto selection = json ? valueFromJson(*json) : std::expected{Value{}}; + if (!selection) { + return; + } + ValueRecord nextBody = *body; + nextBody.insert_or_assign(input.member, std::move(*selection)); + std::int64_t const rows = _model->rows->selectedCount(again).rows; + std::string const runId = "rerun." + std::to_string(run.run); + auto const rerun = [model = _model, again, rerun = run.rerun, nextBody = Value{std::move(nextBody)}] { + model->viewSelection.set(again); + rerun(nextBody); + }; + _core->tableMessage( + *_element, + "The rows changed since you selected them: " + + render::formatCanonicalNumber(std::to_string(rows), _core->session.formatting().numeric) + + (rows == 1 ? " row now. Run on these?" : " rows now. Run on these?"), + {{StatusEntry{.id = runId, .label = "Run on these"}, rerun}}); + return; + } + } + +private: + // Retains the rows the run's reply says it changed, all or none: past the bound none is, and the status line + // says so. + void keepChanged(RunSettled const& run) { + if (!run.succeeded) { + return; + } + auto const& catalog = _core->session.options().catalog; + std::optional const info = catalog.action ? catalog.action(run.action) : std::nullopt; + if (!info) { + return; + } + ChangedRowsValue const changed = changedRowsOf(run.reply, *info, _model->modelType + "." + _model->id); + std::vector keys; + keys.reserve(changed.rows.size()); + for (table::ChangedRow const& row : changed.rows) { + keys.push_back(row.key); + } + if (keys.empty() || _model->rows->retain(keys) != RetainResult::OverBound) { + return; + } + std::string const bound = render::formatCanonicalNumber(std::to_string(table::QueryLimits{}.maxRetained), + _core->session.formatting().numeric); + _core->tableMessage(*_element, "The changed rows are not kept in view: a table keeps at most " + bound); + } + + [[nodiscard]] std::string recordName() const { return _model->modelType + "." + _model->id; } + + // The selected keys, while the selection is keys. + [[nodiscard]] std::vector selectedKeys() const { + std::vector out; + Value const selected = _core->runtime().untracked([&] { return tableSelection(*_element); }); + if (ValueList const* const items = selected.asList()) { + for (Value const& item : *items) { + out.push_back(keyOf(item)); + } + } + return out; + } + + // Selects @p keys as the user's selection does. + void select(std::vector const& keys) { + if (_model->config.selectKeys) { + _model->config.selectKeys(keys); + } + } + + // Drops keys that left the view from the selection and from the failed marks. + void drop(std::vector const& left) { + if (left.empty()) { + return; + } + _model->rows->states().clearFailed(left); + std::vector kept = selectedKeys(); + if (std::erase_if(kept, [&left](Key const& key) { return std::ranges::contains(left, key); }) > 0) { + select(kept); + } + _model->marksRevision.set(_model->marksRevision.peek() + 1); + } + + // The keys a member of a run's input names, as a key list or a row's key. + [[nodiscard]] static std::vector keysIn(Value const* list) { + std::vector out; + if (ValueList const* const items = list == nullptr ? nullptr : list->asList()) { + for (Value const& item : *items) { + out.push_back(keyOf(item)); + } + } + return out; + } + + // The rows a run's input names for this table become busy for it: a `RowSelection` member's keys, or every row + // of its view but `except`, and a `RowRef` member's row. Their failed marks go. + void markBusy(RunStarted const& run) { + auto const& catalog = _core->session.options().catalog; + std::optional const schema = catalog.schema ? catalog.schema(run.action) : std::nullopt; + ValueRecord const* const body = run.body.asRecord(); + if (!schema || body == nullptr) { + return; + } + std::string const record = recordName(); + RowStates& states = _model->rows->states(); + bool marked = false; + for (TableInput const& input : tableInputsOf(*schema)) { + auto const member = body->find(input.member); + if (input.record != record || member == body->end() || member->second.isNull()) { + continue; + } + Value const& named = member->second; + if (input.kind == TableInputKind::Row || input.kind == TableInputKind::CellEdit) { + std::vector const one{keyOf(named)}; + states.clearFailed(one); + states.busyKeys(run.run, one); + } else if (Value const* const view = named.field("view"); view != nullptr && !view->isNull()) { + std::vector except = keysIn(named.field("except")); + std::int64_t const count = + _model->rows->selectedCount(TableSelection{.keys = {}, .view = ViewSelection{}, .except = except}) + .rows; + std::vector marks = states.failedKeys(); + std::erase_if(marks, [&except](Key const& key) { return std::ranges::contains(except, key); }); + states.clearFailed(marks); + states.busyView(run.run, std::move(except), count); + } else { + std::vector keys = keysIn(named.field("keys")); + states.clearFailed(keys); + states.busyKeys(run.run, std::move(keys)); + } + marked = true; + } + if (marked) { + _model->marksRevision.set(_model->marksRevision.peek() + 1); + } + } + + // Whether this session holds anything by a key: the selection, the focus, a retained row, a busy or failed state, + // or a drop waiting for the runs to settle. + [[nodiscard]] bool holds(Key const& key) const { + RowStates const& states = _model->rows->states(); + std::optional const& view = _model->viewSelection.peek(); + bool const selected = + view ? std::ranges::contains(view->except, key) : std::ranges::contains(selectedKeys(), key); + return selected || (_model->config.focused && _model->config.focused->key == key) || + std::ranges::contains(_model->window->retained(), key) || states.isBusy(key) || + states.failure(key).has_value() || _deferred.contains(key) || + (_model->edits != nullptr && _model->edits->rowEdited(key)); + } + + // A reply's failed rows are marked, and each changed row with a `from` this session holds moves what it holds + // from that key to the new one: the selection, the retained rows and the states. Every `from` goes to the mount, + // which moves its focus and highlight by its own keys: focus the action's own event already moved off the old row + // is held only there. @p moved gets each old key moved here. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): applies a reply: failed rows are marked, then each changed row with a `from` moves what the session holds; the second step reads the first's marks + void applyReply(RunSettled const& run, std::vector& moved) { + auto const& catalog = _core->session.options().catalog; + std::optional const info = catalog.action ? catalog.action(run.action) : std::nullopt; + if (!info) { + return; + } + ChangedRowsValue const changed = changedRowsOf(run.reply, *info, recordName()); + _model->rows->states().fail(changed.failed); + std::vector> moves; + std::vector> told; + for (table::ChangedRow const& row : changed.rows) { + if (!row.from || *row.from == row.key) { + continue; + } + told.emplace_back(*row.from, row.key); + if (holds(*row.from)) { + moves.emplace_back(*row.from, row.key); + } + } + // The mount is told after the selection is rewritten: a handler reading both in one turn sees them agree. + auto const tell = [this, &told] { + if (!told.empty()) { + _model->keyMoves.set( + KeyMoves{.generation = _model->keyMoves.peek().generation + 1, .moves = std::move(told)}); + } + }; + if (moves.empty()) { + tell(); + return; + } + std::optional view = _model->viewSelection.peek(); + std::vector keys = view ? std::vector{} : selectedKeys(); + bool reselect = false; + for (auto const& [from, target] : moves) { + moved.push_back(from); + _deferred.erase(from); + moveRowKey(*_model, from, target); + if (view) { + // A key left out of the view's selection leaves its new key out; a selected one selects it. + if (auto const out = std::ranges::find(view->except, from); out != view->except.end()) { + if (std::ranges::contains(view->except, target)) { + view->except.erase(out); + } else { + *out = target; + } + } else { + std::erase(view->except, target); + } + } else if (auto const found = std::ranges::find(keys, from); found != keys.end()) { + reselect = true; + if (std::ranges::contains(keys, target)) { + keys.erase(found); + } else { + *found = target; + } + } + } + if (view) { + _model->viewSelection.set(std::move(view)); + } else if (reselect) { + select(keys); + } + tell(); + } + + ScreenCore* _core; + ElementState* _element; + ModelTable* _model; + // The runs holding the rows' refetches. + std::set _held; + // The runs in flight of actions that change the table's record, and the selected keys that left the view while + // one was: dropped when the last settles, unless a reply named them as a row's old key. + std::set _changing; + std::set _deferred; +}; + +// The field errors a reply names in its reserved `errors` member: the first message of each entry, by the name the +// action's input gives the field, `value`, or a member of `values` without its prefix. +std::vector editErrorsOf(Value const& reply) { + std::vector out; + ValueRecord const* const errors = reply.field("errors") != nullptr ? reply.field("errors")->asRecord() : nullptr; + if (errors == nullptr) { + return out; + } + for (auto const& [path, entry] : *errors) { + std::string message; + if (std::string const* const text = entry.asString()) { + message = *text; + } else if (ValueList const* const list = entry.asList(); + list != nullptr && !list->empty() && list->front().asString() != nullptr) { + message = *list->front().asString(); + } + if (message.empty()) { + continue; + } + constexpr std::string_view kValues = "values."; + std::string name = path.starts_with(kValues) ? path.substr(kValues.size()) : path; + out.push_back(table::FieldError{.column = std::move(name), .message = std::move(message)}); + } + return out; +} + +// What a refused or failed call of an edit action says: its sentence. +std::string editFailureOf(std::exception_ptr const& error) { + try { + std::rethrow_exception(error); + } catch (std::exception const& failed) { + return failed.what(); + } catch (...) { + return "The edit could not be saved"; + } +} + +// Sends a row commit of a model's table through the table's alias, not as a run of the session, so no row is busy for +// it: a call per `CellEdit` cell, and one per `RowEdit` action with every cell of the request it edits. The commit +// settles once every call has: refused with each call's field errors, a failed row or a failure's sentence, else +// succeeded. A changed row with a `from` moves what the table holds by key. A success whose replies name the row as +// changed waits for the change event's refetch; one that names it nowhere changed nothing the window would fetch, so +// the row counts as fetched at once. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): sends one row commit: a call per cell and per action, settled once every call has, merging each call's outcome in order +void sendRowEdit(ScreenCore& core, ModelTable& model, table::RowEditRequest const& request, table::RowEditDone done) { + table::TableDescription const* const description = model.window->description(); + std::string const key = std::visit( + [](auto const& value) -> std::string { + if constexpr (std::is_same_v, std::string>) { + return glz::write_json(value).value_or("\"\""); + } else { + return std::to_string(value); + } + }, + request.row); + struct Call { + std::string action; + std::string body; + std::vector names; + }; + std::vector calls; + std::vector refused; + std::map> rowEdits; + std::map, std::less<>> rowNames; + for (table::EditCell const& cell : request.cells) { + table::EditInfo const* edit = nullptr; + if (description != nullptr) { + auto const found = std::ranges::find_if( + description->columns, [&](table::TableColumn const& column) { return column.info.id == cell.column; }); + edit = found != description->columns.end() && found->edit ? &*found->edit : nullptr; + } + if (edit == nullptr) { + refused.push_back(table::FieldError{.column = cell.member.empty() ? cell.column : cell.member, + .message = "This column is not edited here any more"}); + } else if (edit->member.empty()) { + calls.push_back(Call{.action = edit->action, + .body = R"({"key":)" + key + R"(,"value":)" + cell.json + "}", + .names = {cell.member.empty() ? cell.column : cell.member}}); + } else { + rowNames[edit->action].push_back(cell.member.empty() ? cell.column : cell.member); + std::string& values = rowEdits[edit->action]; + values += (values.empty() ? "" : ",") + glz::write_json(edit->member).value_or("\"\"") + ":" + cell.json; + } + } + for (auto const& [action, values] : rowEdits) { + calls.push_back(Call{ + .action = action, + // NOLINTNEXTLINE(performance-inefficient-string-concatenation): builds one request body from four pieces, once per call, on a path that waits on the network + .body = R"({"key":)" + key + R"(,"values":{)" + values + "}}", + .names = rowNames[action]}); + } + if (!calls.empty() && !model.calls) { + refused.push_back(table::FieldError{.column = {}, .message = "This table cannot save edits"}); + } + if (calls.empty() || !model.calls) { + done(refused.empty() ? std::expected>{} : std::unexpected(refused)); + return; + } + struct Settling { + std::size_t remaining = 0; + std::vector errors; + bool named = false; + table::RowId row; + table::RowEditDone done; + }; + auto const settling = std::make_shared(Settling{.remaining = calls.size(), + .errors = std::move(refused), + .named = false, + .row = request.row, + .done = std::move(done)}); + auto const finish = [&model, settling] { + if (--settling->remaining > 0) { + return; + } + table::RowEditDone const settle = std::move(settling->done); + if (!settling->errors.empty()) { + settle(std::unexpected(std::move(settling->errors))); + return; + } + settle({}); + if (!settling->named && model.edits != nullptr) { + model.edits->rowFetched(settling->row); + if (std::shared_ptr const grid = model.editGrid.lock()) { + grid->touch(); + } + } + }; + std::string const record = model.modelType + "." + model.id; + for (Call const& call : calls) { + // A refusal that names no cell is this call's cells': a request of several calls settles as one, and another + // call's cells may have been saved. + auto const unnamed = [settling, names = calls.size() > 1 ? call.names : std::vector{}]( + std::string const& message) { + if (names.empty()) { + settling->errors.push_back(table::FieldError{.column = {}, .message = message}); + } + for (std::string const& name : names) { + settling->errors.push_back(table::FieldError{.column = name, .message = message}); + } + }; + model.calls(call.action, call.body) + .then(model.scope, + [&core, &model, settling, finish, unnamed, record, action = call.action](std::string const& text) { + auto const json = parseJson(text); + Value const reply = json ? valueFromJson(*json).value_or(Value{}) : Value{}; + std::vector errors = editErrorsOf(reply); + if (!errors.empty()) { + std::ranges::move(errors, std::back_inserter(settling->errors)); + finish(); + return; + } + Catalog const& catalog = core.session.options().catalog; + std::optional const info = catalog.action ? catalog.action(action) : std::nullopt; + if (info) { + ChangedRowsValue const changed = changedRowsOf(reply, *info, record); + for (table::FailedRow const& failed : changed.failed) { + if (failed.key == settling->row) { + unnamed(failed.message); + } + } + std::vector> moves; + for (table::ChangedRow const& row : changed.rows) { + bool const moved = row.from && *row.from == settling->row && row.key != settling->row; + settling->named = settling->named || row.key == settling->row || moved; + if (moved) { + moves.emplace_back(*row.from, row.key); + } + } + for (auto const& [from, target] : moves) { + moveRowKey(model, from, target); + settling->row = target; + } + if (!moves.empty()) { + model.keyMoves.set(KeyMoves{.generation = model.keyMoves.peek().generation + 1, + .moves = std::move(moves)}); + } + } + finish(); + }) + .onError(model.scope, [finish, unnamed](std::exception_ptr const& error) { + unnamed(editFailureOf(error)); + finish(); + }); + } +} + +} // namespace + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): wires a model's table: rows, runs, states, selection and actions, each taking the config and element the previous stage set up +void ScreenCore::wireModelTable(ElementState& element) { + DocNode const& node = *element.node; + RtScope& scope = *element.scope; + auto made = std::make_unique(runtime()); + ModelTable& model = *made; + element.modelTable = std::move(made); + model.core = this; + model.element = &element; + modelTables.push_back(&element); + NameRef const* const named = scope.find(node.name("model")); + ModelAlias* const alias = named != nullptr && named->category == NameCategory::Model ? named->model : nullptr; + if (alias == nullptr) { + report(node.path, "the table's `model` names no model alias of this scope"); + return; + } + std::string const action{node.name("action")}; + model.id = action.empty() ? std::string{node.name("table")} : action; + model.modelType = alias->decl->type; + model.statusShown = node.flag("status", true); + model.retainChanged = node.flag("retainChanged"); + TableConfig& config = model.config; + config.element = &element; + auto const [allowed, menus] = configurableOf(node); + config.allowed = allowed; + config.menus = menus; + // The bound the server's `limits` set, which the description carries. + config.maxSortKeys = [&model] { + table::TableDescription const* const description = model.window->description(); + return description == nullptr ? std::size_t{8} : std::size_t{description->capabilities.maxSortKeys}; + }; + config.message = [this, &element](std::string text) { tableMessage(element, std::move(text)); }; + config.touch = [this, &element] { tableGesture(element); }; + config.save = [&model](table::StateDocument const& document, StateParts parts) { + if (model.stateKey) { + model.states->changed(*model.stateKey, document, parts); + } + }; + // The filters the rows hold; the user's go to the rows through `ObservedRows`, which marks them the user's. + config.filters = [&model] { + static_cast(model.version.get()); + return model.filter; + }; + config.setFilters = [this, &model, &element](table::FilterSpec const& filter) { + if (auto const set = model.rows->setFilter(filter); !set) { + tableMessage(element, "The filter is refused: " + set.error().message); + return false; + } + model.filter = filter; + model.heldFilter.reset(); + model.bump(); + return true; + }; + config.rows = [&model]() -> TableRows* { return model.rows.get(); }; + config.declaredGroups = [&model] { + table::TableDescription const* const description = model.window->description(); + return description == nullptr ? std::vector{} : description->groups; + }; + config.description = [&model]() -> std::optional { + table::TableDescription const* const description = model.window->description(); + return description == nullptr ? std::nullopt : std::optional{*description}; + }; + // A bound layout is controlled, as a bound sort is: any expression but a literal `null` binds it. + if (ExprPtr const layout = node.prop("layout"); + layout && (layout->kind != ExprKind::Literal || !layout->literal.isNull())) { + config.bound = &scope.nodes.computed([&scope, layout] { return evalIn(scope, nullptr, layout); }); + } + std::string qualifier = _doc->id; + bool persists = true; + if (ExprPtr const persist = node.prop("persist"); persist && persist->kind == ExprKind::Literal) { + if (bool const* const flag = persist->literal.asBool()) { + persists = *flag; + } else if (std::string const* const name = persist->literal.asString()) { + qualifier = *name; + } + } + model.states = session.tableStates(); + if (persists && model.states != nullptr) { + model.stateKey = table::TableStateKey{.application = session.options().application, + .model = model.modelType, + .table = model.id, + .qualifier = std::move(qualifier), + .part = "state"}; + } + // A model's table is described by its `describe` action; a typed list action by the client, from the node's + // columns or the action's view document. + std::optional typed; + if (action.empty()) { + model.describeDecl = QueryDecl{.name = {}, + .path = node.path, + .model = std::string{node.name("model")}, + .action = "Table." + model.id + ".describe", + .evaluate = false, + .body = nullptr, + .when = nullptr, + .debounce = 0, + .refreshEvery = 0, + .staleTime = 0}; + model.describe = std::make_unique(model.describeDecl, scope, alias); + } else { + typed = actionTableOf(node, session.options().catalog); + if (!typed->problem.empty()) { + report(node.path, typed->problem); + } + if (!typed->keyProblem.empty()) { + report(pointerAppend(node.path, "key"), typed->keyProblem); + } + for (std::string const& problem : typed->unitProblems) { + report(node.path, problem); + } + } + Value const body = + node.prop("body") ? runtime().untracked([&] { return evalIn(scope, nullptr, node.prop("body")); }) : Value{}; + // The table owns these members of the query; a body that gives one has it replaced, which is said, since the + // body is the query's fixed part and the author may have meant it to restrict the rows. + if (ValueRecord const* const fixed = body.asRecord()) { + if (auto const query = fixed->find("query"); query != fixed->end() && query->second.asRecord() != nullptr) { + for (std::string_view const owned : {"sort", "filters", "page", "columns", "keys", "retry"}) { + if (query->second.asRecord()->contains(owned)) { + report(pointerAppend(pointerAppend(pointerAppend(node.path, "body"), "query"), owned), + "`" + std::string{owned} + "` is the table's own; the body's is not used"); + } + } + } + } + model.waiting = model.stateKey.has_value(); + model.window = std::make_shared( + session, WindowRowsOptions{ + .channel = channelOf(*alias, *this), + .table = typed ? std::string{} : model.id, + .action = action, + .queryMember = typed ? typed->queryMember : std::string{}, + .inferKinds = typed ? typed->inferKinds : std::vector{}, + .records = typed ? typed->records : std::vector{model.modelType + "." + model.id}, + .body = body, + .pageSize = 200, + .maxPages = 8, + .maxKeys = 1000, + .maxColumns = 96, + .restoring = model.waiting}); + element.tableWindow = model.window; + model.rows = std::make_shared( + model.window, model.scope.token().guard([this, &model, &element] { + model.bump(); + model.marksRevision.set(model.marksRevision.peek() + 1); + fitViewSelection(*this, element, model); + if (model.runs != nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast): `model.runs` is created as a `TableRuns` by this table's own wiring, so the downcast cannot fail + static_cast(*model.runs).rowsChanged(); + } + }), + model.scope.token().guard([this, &element] { tableGesture(element); }), + model.scope.token().guard([&model] { model.resets.set(model.resets.peek() + 1); }), + model.scope.token().guard([this, &model, &element] { + model.userFiltered = true; + tableGesture(element); + })); + element.tableRows = model.rows; + model.calls = aliasCalls(alias); + model.edits = std::make_unique( + [this, &model](table::RowEditRequest const& request, table::RowEditDone done) { + sendRowEdit(*this, model, request, std::move(done)); + }); + // A keyed refetch that found no row for a key: the row was deleted or left the filter, and its drafts go. + model.window->onRowsAbsent(model.scope.token().guard([&model](std::span keys) { + if (std::shared_ptr const grid = model.editGrid.lock()) { + grid->rowsAbsent(keys); + return; + } + for (table::RowId const& key : keys) { + model.edits->rowAbsent(key); + } + })); + model.runs = std::make_unique(*this, element, model); + session.addRunObserver(model.runs.get()); + if (model.describe != nullptr) { + model.window->onStaleDescription(model.scope.token().guard([&model] { model.describe->invalidate(); })); + } + // Heard while the first reply is read: the filter held meanwhile goes once that reply is taken. + model.window->onInferred(model.scope.token().guard([this, &model, &element] { + runtime().owner().post(model.scope.token().guard([this, &element] { inferredTable(element); })); + })); + // Called inside a binding, where no signal may be written: the misses of one turn are fetched by one task. + model.onMissing = [this, &model](std::string_view field) { + bool const first = model.missing.empty(); + model.missing.emplace(field); + if (!first) { + return; + } + // A field no column of the description has is dropped by the rows, which never name it to the server. + runtime().owner().post(model.scope.token().guard([&model] { + std::set> const missed = std::exchange(model.missing, {}); + model.rows->fetchAlso(std::vector{missed.begin(), missed.end()}); + })); + }; + // A literal sort is the default a stored one replaces; any other expression binds it. + // NOLINTNEXTLINE(readability-simplify-boolean-expr): the literal-null test is kept as written so the comment above it reads as the condition + if (ExprPtr const sort = node.prop("sort"); sort && !(sort->kind == ExprKind::Literal && sort->literal.isNull())) { + if (sort->kind == ExprKind::Literal) { + element.sort.set(sort->literal); + } else { + element.sortBound = &scope.nodes.computed([&scope, sort] { return evalIn(scope, nullptr, sort); }); + } + } + if (ExprPtr const selection = node.prop("selection"); + selection && (selection->kind != ExprKind::Literal || !selection->literal.isNull())) { + element.bound = &scope.nodes.computed([&scope, selection] { return evalIn(scope, nullptr, selection); }); + } + // A literal filter is the default a stored one replaces; an expression binds the filters. + if (std::string_view const literal = node.name("filters"); !literal.empty()) { + table::FilterSpec filter; + if (!glz::read_json(filter, literal)) { + if (model.window->inferring()) { + model.heldFilter = std::move(filter); + } else { + model.filter = filter; + std::ignore = (model.window->setFilter(std::move(filter))); + } + } + } else if (ExprPtr const filters = node.prop("filters")) { + model.filtersBound = true; + config.filtersBound = true; + scope.nodes.effect([this, &scope, &element, filters] { + Value const value = evalIn(scope, nullptr, filters); + runtime().untracked([&] { + ModelTable& table = *element.modelTable; + table::FilterSpec filter; + if (!value.isNull()) { + std::string const text = canonicalJson(value); + if (auto const failed = glz::read_json(filter, text)) { + report(pointerAppend(element.node->path, "filters"), + "`filters` is not a filter: " + glz::format_error(failed, text)); + return; + } + } + if (table.window->inferring()) { + table.heldFilter = std::move(filter); + table.heldStored = false; + return; + } + if (filter == table.filter) { + return; + } + if (auto const set = table.window->setFilter(filter); !set) { + report(pointerAppend(element.node->path, "filters"), + "the filter is refused: " + set.error().message); + return; + } + table.filter = std::move(filter); + }); + }); + } + if (model.describe != nullptr) { + model.describe->start(); + } + // The sort the table shows: the bound one, or the table's own, which a header click and a stored state set. + scope.nodes.effect([this, &element] { + Value const value = tableSort(element); + runtime().untracked([&] { + ModelTable& table = *element.modelTable; + SortChain chain = sortChainOf(value); + if (chain == table.sort) { + return; + } + if (auto const set = table.window->setSort(chain); !set) { + report(pointerAppend(element.node->path, "sort"), "the sort is refused: " + set.error().message); + return; + } + table.sort = std::move(chain); + }); + }); + if (typed) { + model.window->setDescription(std::move(typed->description)); + if (table::TableDescription const* const now = model.window->description()) { + model.keyColumn = now->key; + for (table::TableColumn const& column : now->columns) { + model.described.insert(column.info.id); + } + } + modelLayoutColumns(element); + model.bump(); + } else { + scope.nodes.effect([this, &element] { + Value const described = element.modelTable->describe->value(); + runtime().untracked([&] { describedTable(element, described); }); + }); + } + // A highlight: each non-null key, once a description is held, is located in the view by a keyed fetch naming no + // columns, which stops the one an earlier key still has in flight; a key the view lacks, or null, marks nothing. + // A typed list action's description is held from here on. + if (ExprPtr const highlight = node.prop("highlightKey")) { + scope.nodes.effect([this, &scope, &element, highlight, typedTable = typed.has_value()] { + Value const key = evalIn(scope, nullptr, highlight); + bool const described = typedTable || !element.modelTable->revision.get().empty(); + // A new query (sort, filter) moves the row: located again, the mark cleared meanwhile. + static_cast(element.modelTable->resets.get()); + runtime().untracked([&] { + ModelTable& table = *element.modelTable; + if (key.isNull() || !described) { + table.window->stopLocating(); + table.highlight.set(std::nullopt); + return; + } + Key const shown = keyOf(key); + table.highlight.set(std::nullopt); + table.window->locate( + std::visit([](auto const& value) { return table::RowId{value}; }, shown), + [&table, shown](std::optional index) { + table.highlight.set(index && *index >= 0 + ? std::optional{TableHighlight{ + .key = shown, .row = static_cast(*index)}} + : std::nullopt); + }); + }); + }); + } + if (!model.stateKey) { + return; + } + // The first query waits for the stored state, at most `tableStateTimeout`; a state that comes later is applied + // unless the user changed the table meanwhile. + if (reactive::Scheduler* const scheduler = session.options().scheduler) { + model.loadTimer = scheduler->after(session.options().tableStateTimeout, + model.scope.token().guard([&model] { model.release(); })); + } + model.views = std::make_unique(*model.states, *model.stateKey, runtime().owner()); + model.config.views = model.views.get(); + loadStateAndViews(*model.states, *model.stateKey, *model.views, model.scope, + [this, &element](std::optional const& json, std::string const& failure) { + storedTableState(element, json, failure); + }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): applies a stored table state to a model table: layout, sort, filter and groups each fit to the description and report their own refusal +void ScreenCore::storedTableState(ElementState& element, std::optional const& json, + std::string const& failure) { + ModelTable& model = *element.modelTable; + DocNode const& node = *element.node; + bool const late = !model.waiting; + if (!failure.empty()) { + report(node.path, "the stored state of table `" + node.id + "` could not be loaded: " + failure); + model.release(); + return; + } + std::optional stored; + if (json) { + auto read = table::readState(*json); + if (!read) { + report(node.path, "the stored state of table `" + node.id + "` is not used: " + read.error()); + model.release(); + return; + } + stored = std::move(*read); + } + // The default view stands in for a state never stored, and its sort and filters for the stored ones when the + // user starts from it. + std::optional start = + model.views != nullptr ? stateAtMount(std::move(stored), model.views->own()) : std::move(stored); + if (!start) { + model.release(); + return; + } + if (late && model.touched) { + return; + } + table::StateDocument document = std::move(*start); + // Kinds still to be inferred are placeholders: the stored filters are fitted to the kinds the first reply gives. + if (model.window->inferring()) { + if (!model.filtersBound && document.filters) { + model.heldFilter = std::exchange(document.filters, std::nullopt); + model.heldStored = true; + } + } + if (table::TableDescription const* const description = model.window->description()) { + table::FitReport fitted; + document = table::fitState(std::move(document), *description, fitted); + for (table::FitDrop const& drop : fitted.dropped) { + if (drop.what == table::FitDrop::What::Filter || drop.what == table::FitDrop::What::GroupFilter) { + report(node.path, + "the stored filter on `" + drop.id + "` is not applied: the table has no such column"); + } + } + } + // A table started from the default view, with nothing stored, holds it as its state: the next change saves on + // top of it rather than over nothing. + if (!json && model.states != nullptr && model.stateKey) { + model.states->start(*model.stateKey, document); + } + if (element.sortBound == nullptr && document.sort) { + if (model.window->setSort(*document.sort)) { + model.sort = *document.sort; + element.sort.set(sortValueOf(model.sort)); + } + } + if (!model.filtersBound && document.filters) { + if (model.window->setFilter(*document.filters)) { + model.filter = *document.filters; + model.heldFilter.reset(); + } + } + // A bound layout is the document's: the stored one is neither applied nor saved over it. + bool const arranged = document.layout && model.config.bound == nullptr; + if (arranged) { + model.config.held = std::move(document.layout); + model.config.version.set(model.config.version.peek() + 1); + } + if (document.view) { + model.config.savedView = std::move(document.view); + model.config.viewShared = false; + } + tablePoints(element); + if (late || !arranged) { + model.release(); + return; + } + // A mounted table takes the new arrangement in a pass of its own, which tells the rows the columns it shows: the + // first query goes after it, so it names those columns. + runtime().owner().post(model.scope.token().guard([&model] { model.release(); })); +} + +void ScreenCore::describedTable(ElementState& element, Value const& described) { + ModelTable& model = *element.modelTable; + if (described.isNull()) { + return; + } + table::TableDescription const* const held = model.window->description(); + std::string const before = held != nullptr ? held->revision : std::string{}; + // The filters a new revision drops are said once, at the table; a dropped sort key is not. + if (held != nullptr) { + table::TableDescription next; + std::string const text = canonicalJson(described); + if (!glz::read(next, text) && next.revision != before) { + table::FitReport fitted; + static_cast(table::fitState(table::StateDocument{.version = table::kStateVersion, + .layout = {}, + .sort = model.sort, + .filters = model.filter, + .view = {}, + .carried = {}}, + next, fitted)); + for (table::FitDrop const& drop : fitted.dropped) { + if (drop.what == table::FitDrop::What::Filter || drop.what == table::FitDrop::What::GroupFilter || + drop.what == table::FitDrop::What::Unit) { + report(element.node->path, "the filter on `" + drop.id + + "` is dropped: the table's new description has no such column"); + } + } + } + } + model.window->setDescription(described); + table::TableDescription const* const now = model.window->description(); + if (now == nullptr) { + model.bump(); + return; + } + model.keyColumn = now->key; + model.described.clear(); + for (table::TableColumn const& column : now->columns) { + model.described.insert(column.info.id); + } + modelLayoutColumns(element); + // The fitted sort and filters are what the rows hold now. + table::FitReport ignored; + table::StateDocument const fitted = table::fitState(table::StateDocument{.version = table::kStateVersion, + .layout = {}, + .sort = model.sort, + .filters = model.filter, + .view = {}, + .carried = {}}, + *now, ignored); + model.sort = fitted.sort.value_or(SortChain{}); + model.filter = fitted.filters.value_or(table::FilterSpec{}); + if (element.sortBound == nullptr) { + element.sort.set(sortValueOf(model.sort)); + } + model.revision.set(now->revision); + model.bump(); +} + +void ScreenCore::inferredTable(ElementState& element) { + ModelTable& model = *element.modelTable; + table::TableDescription const* const description = model.window->description(); + if (description == nullptr) { + return; + } + // The held filter, unless the user filtered meanwhile: a bound filter is the document's and always wins; a + // literal or a stored one gives way only to a filter the user set, since a stored state held here arrived in + // time and a sort or a scroll since does not undo it. Without one, the filter the rows hold, which may have been + // compiled against the placeholders, is fitted again. + std::optional held = std::exchange(model.heldFilter, std::nullopt); + bool const stored = std::exchange(model.heldStored, false); + bool const yields = !model.filtersBound && model.userFiltered; + if (held && yields) { + held.reset(); + } + table::FilterSpec filter = held ? *held : model.window->filter(); + bool const fromStore = held && stored; + table::FitReport fitted; + table::StateDocument const document = table::fitState( + table::StateDocument{ + .version = table::kStateVersion, .layout = {}, .sort = {}, .filters = filter, .view = {}, .carried = {}}, + *description, fitted); + for (table::FitDrop const& drop : fitted.dropped) { + if (drop.what == table::FitDrop::What::Filter || drop.what == table::FitDrop::What::GroupFilter) { + report(element.node->path, + std::string{fromStore ? "the stored filter" : "the filter"} + " on `" + drop.id + + "` is not applied: " + + (drop.carried ? "the table has no such column" : "it does not apply to the column's kind")); + } + } + filter = document.filters.value_or(table::FilterSpec{}); + if (filter == model.window->filter()) { + model.filter = std::move(filter); + return; + } + if (auto const set = model.window->setFilter(filter); !set) { + report(pointerAppend(element.node->path, "filters"), "the filter is refused: " + set.error().message); + return; + } + model.filter = std::move(filter); +} + +void ScreenCore::tableGesture(ElementState& element) { + if (element.rowsTable != nullptr) { + element.rowsTable->touched = true; + tableMessage(element, {}); + return; + } + if (element.modelTable == nullptr) { + return; + } + element.modelTable->touched = true; + tableMessage(element, {}); +} + +void ScreenCore::rowsTableMessage(RowsTable& rows, std::string text) const { + if (text.empty()) { + rows.messageTimer.cancel(); + rows.message.set({}); + return; + } + if (rows.status == false) { + if (host != nullptr) { + static_cast(host->notify(text, "warning")); + } + return; + } + rows.message.set(text); + rows.messageTimer.cancel(); + if (reactive::Scheduler* const scheduler = session.options().scheduler) { + rows.messageTimer = + scheduler->after(kStatusMessageHold, rows.scope.token().guard([&rows, shown = std::move(text)] { + if (rows.message.peek() == shown) { + rows.message.set({}); + } + })); + } +} + +void ScreenCore::tableMessage(ElementState& table, std::string text) { + if (RowsTable* const rows = table.rowsTable.get()) { + rowsTableMessage(*rows, std::move(text)); + return; + } + if (GridTable* const grid = table.gridTable.get()) { + grid->entryHandlers.clear(); + grid->entries.set({}); + grid->messageTimer.cancel(); + grid->message.set(text); + if (reactive::Scheduler* const scheduler = session.options().scheduler; + scheduler != nullptr && !text.empty()) { + grid->messageTimer = scheduler->after(kStatusMessageHold, grid->scope.token().guard([grid, shown = text] { + if (grid->message.peek() == shown) { + grid->message.set({}); + grid->entries.set({}); + grid->entryHandlers.clear(); + } + })); + } + return; + } + ModelTable* const model = table.modelTable.get(); + if (model == nullptr) { + return; + } + model->entryHandlers.clear(); + model->entries.set({}); + if (text.empty()) { + model->messageTimer.cancel(); + model->message.set({}); + return; + } + if (!model->statusShown) { + if (host != nullptr) { + static_cast(host->notify(text, "warning")); + } + return; + } + model->message.set(text); + model->messageTimer.cancel(); + if (reactive::Scheduler* const scheduler = session.options().scheduler) { + model->messageTimer = + scheduler->after(kStatusMessageHold, model->scope.token().guard([model, shown = std::move(text)] { + if (model->message.peek() == shown) { + model->message.set({}); + model->entries.set({}); + model->entryHandlers.clear(); + } + })); + } +} + +void ScreenCore::tableMessage(ElementState& table, std::string text, + std::vector>> entries) { + tableMessage(table, std::move(text)); + if (GridTable* const grid = table.gridTable.get()) { + if (grid->message.peek().empty()) { + return; + } + std::vector shown; + for (auto& [entry, handler] : entries) { + grid->entryHandlers.insert_or_assign(entry.id, std::move(handler)); + shown.push_back(std::move(entry)); + } + grid->entries.set(std::move(shown)); + return; + } + ModelTable* const model = table.modelTable.get(); + if (model == nullptr || !model->statusShown || model->message.peek().empty()) { + return; + } + std::vector shown; + for (auto& [entry, handler] : entries) { + model->entryHandlers.insert_or_assign(entry.id, std::move(handler)); + shown.push_back(std::move(entry)); + } + model->entries.set(std::move(shown)); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): derives each point of a table element in document order, each reading the element's config and engine +void ScreenCore::tablePoints(ElementState& table) { + ModelTable const* const model = table.modelTable.get(); + // A table over `rows` that keeps a state shows its layout at a `columns` point and its saved view's name at a + // `saved` one, as a model-backed table does. + RowsTable const* const rows = model == nullptr && table.rowsTable != nullptr && table.rowsTable->stateKey && + table.node != nullptr && table.node->kind == "table" + ? table.rowsTable.get() + : nullptr; + if ((model == nullptr && rows == nullptr) || table.node == nullptr) { + return; + } + TableConfig const& config = model != nullptr ? model->config : rows->config; + ValueRecord next = prefs.peek(); + bool changed = false; + for (auto const& [name, point] : doc().customize) { + // A point without `of` names no table, an id-less one included. + if (point.of.empty() || point.of != table.node->id || (point.kind != "columns" && point.kind != "saved")) { + continue; + } + Value value; + if (point.kind == "saved") { + value = config.savedView ? Value{*config.savedView} : Value{}; + } else if (config.held) { + auto const json = parseJson(glz::write_json(*config.held).value_or("null")); + auto read = json ? valueFromJson(*json) : std::expected{Value{}}; + value = read ? std::move(*read) : Value{}; + } else { + continue; + } + if (auto const held = next.find(name); held == next.end() || held->second != value) { + next.insert_or_assign(name, std::move(value)); + changed = true; + } + } + if (changed) { + prefs.set(std::move(next)); + } +} + +std::optional ScreenCore::tablePoint(CustomizePoint const& point, Value const& value) { + if (point.kind != "columns" && point.kind != "saved") { + return std::nullopt; + } + // A point without `of` names no table. A model-backed table, and a table over `rows` that keeps a state, hold both + // points' values in that state. + if (point.of.empty()) { + return std::nullopt; + } + auto const found = std::ranges::find_if(modelTables, [&point](ElementState const* element) { + if (element->node == nullptr || element->node->id != point.of) { + return false; + } + return element->modelTable != nullptr || + (element->rowsTable != nullptr && element->rowsTable->stateKey && element->node->kind == "table"); + }); + if (found == modelTables.end()) { + return std::nullopt; + } + ModelTable* const model = (*found)->modelTable.get(); + RowsTable* const rows = model == nullptr ? (*found)->rowsTable.get() : nullptr; + TableConfig& config = model != nullptr ? model->config : rows->config; + table::StateDocument changed; + StateParts part = StateParts::Layout; + if (point.kind == "saved") { + std::string const* const name = value.asString(); + if (name == nullptr && !value.isNull()) { + return false; + } + config.savedView = name == nullptr ? std::nullopt : std::optional{*name}; + config.viewShared = false; + changed.view = config.savedView; + part = StateParts::View; + } else { + table::ColumnLayoutValue layout; + if (glz::read_json(layout, canonicalJson(value))) { + return false; + } + config.held = std::move(layout); + config.version.set(config.version.peek() + 1); + changed.layout = config.held; + } + std::optional const& key = model != nullptr ? model->stateKey : rows->stateKey; + TableStates* const states = model != nullptr ? model->states : rows->states; + (model != nullptr ? model->touched : rows->touched) = true; + if (key) { + states->changed(*key, changed, part); + } + return true; +} + +std::size_t ScreenCore::tableRowScopes(ElementState const& table) { + return table.modelTable == nullptr ? 0 : table.modelTable->rowScopes.size(); +} + +void ScreenCore::tableSaveFailed(table::TableStateKey const& key, table::SaveResult const& result) { + std::string const text = result.reason.empty() ? std::string{"The table's arrangement could not be saved"} + : "The table's arrangement could not be saved: " + result.reason; + std::vector tables; + for (ElementState* const element : modelTables) { + std::optional const* const held = + element->modelTable != nullptr ? &element->modelTable->stateKey + // NOLINTNEXTLINE(readability-avoid-nested-conditional-operator): a two-way fall-through over the element's table kinds, in the order they are wired + : element->rowsTable != nullptr ? &element->rowsTable->stateKey + : nullptr; + if (held != nullptr && *held == key) { + tables.push_back(element); + } + } + for (ElementState* const table : tables) { + tableMessage(*table, text); + } +} + +[[nodiscard]] std::vector arrangedColumns(DocNode const& node, + table::TableDescription const& description) { + std::vector const companions = table::companionColumns(description); + std::vector out; + if (auto const parts = node.partList("columns"); !parts.empty()) { + for (DocNodePtr const& part : parts) { + auto const found = + std::ranges::find(description.columns, part->id, + [](table::TableColumn const& column) -> auto const& { return column.info.id; }); + if (found != description.columns.end() && !std::ranges::binary_search(companions, part->id)) { + out.push_back(&*found); + } + } + return out; + } + for (table::TableColumn const& column : description.columns) { + if (!std::ranges::binary_search(companions, column.info.id)) { + out.push_back(&column); + } + } + return out; +} + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_table_detail.hpp b/src/ui/interpreter_table_detail.hpp new file mode 100644 index 000000000..f96d35923 --- /dev/null +++ b/src/ui/interpreter_table_detail.hpp @@ -0,0 +1,836 @@ +// SPDX-License-Identifier: Apache-2.0 + +// What the interpreter's table lowering shares: the table structs and the helpers over them. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "interpreter_detail.hpp" + +namespace morph::ui { + +class SummaryRows; +struct SummarySpec; + +namespace detail { + +/// The rows a model-backed table's mount reads: its `WindowRows`, with what the table hears of them. A change of the +/// rows, or of their counts and error, bumps the table's version, which its status line, its `empty` content and its +/// element values read. A `visible` call other than a new mount's first is the user's scroll. The fields the table's +/// row bindings read and the rows lacked are named to every `visible` call after the mount's own columns. +class ObservedRows final : public TableRows { +public: + ObservedRows(std::shared_ptr inner, std::function changed, std::function scrolled, + std::function reset, std::function filtered) + : _inner{std::move(inner)}, + _changed{std::move(changed)}, + _scrolled{std::move(scrolled)}, + _reset{std::move(reset)}, + _filtered{std::move(filtered)} { + _inner->onChange([this](table::ViewChange const& change) { + if (_handler) { + _handler(change); + } + _changed(); + // A new query moves every row: what is found by key is found again. + if (change.isReset() && _reset) { + _reset(); + } + }); + _inner->onStatus([this] { _changed(); }); + } + + ObservedRows(ObservedRows const&) = delete; + ObservedRows& operator=(ObservedRows const&) = delete; + ObservedRows(ObservedRows&&) = delete; + ObservedRows& operator=(ObservedRows&&) = delete; + ~ObservedRows() override { + _inner->onChange({}); + _inner->onStatus({}); + } + + [[nodiscard]] TableTotal total() const override { return _inner->total(); } + [[nodiscard]] std::optional row(std::int64_t index) const override { return _inner->row(index); } + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override { + return _inner->unloadedLevels(index); + } + void visible(std::int64_t first, std::int64_t count, std::span columns) override { + _first = first; + _count = count; + _columns.assign(columns.begin(), columns.end()); + if (!std::exchange(_mounting, false)) { + _scrolled(); + } + send(); + } + async::Completion, table::TableError>> keysOf( + std::int64_t first, std::int64_t count) override { + return _inner->keysOf(first, count); + } + void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) override { + _inner->locateRow(std::move(key), std::move(stop), std::move(done)); + } + async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) override { + return _inner->fetchRows(std::move(keys), std::move(columns)); + } + std::expected setSort(SortChain sort) override { + return _inner->setSort(std::move(sort)); + } + /// A filter set here is the user's, from the table's own gestures. + std::expected setFilter(table::FilterSpec filter) override { + auto set = _inner->setFilter(std::move(filter)); + if (set) { + _filtered(); + } + return set; + } + async::Completion> distinctValues( + table::DistinctRequest request) override { + return _inner->distinctValues(std::move(request)); + } + [[nodiscard]] TableCountsView counts() const override { return _inner->counts(); } + [[nodiscard]] std::expected selectView() const override { + return _inner->selectView(); + } + [[nodiscard]] SelectedCount selectedCount(TableSelection const& selection) const override { + return _inner->selectedCount(selection); + } + [[nodiscard]] bool leftView(table::RowId const& key) const override { return _inner->leftView(key); } + [[nodiscard]] RetainResult retain(std::span keys) override { return _inner->retain(keys); } + void clearRetained() override { _inner->clearRetained(); } + [[nodiscard]] bool unmatched(table::RowId const& key) const override { return _inner->unmatched(key); } + void holdRefetches(std::uint64_t run) override { _inner->holdRefetches(run); } + void releaseRefetches(std::uint64_t run) override { _inner->releaseRefetches(run); } + [[nodiscard]] RowStates& states() override { return _inner->states(); } + [[nodiscard]] RowStates const& states() const override { return _inner->states(); } + void moveKey(table::RowId const& from, table::RowId const& target) override { _inner->moveKey(from, target); } + [[nodiscard]] std::vector> heldRanges() const override { + return _inner->heldRanges(); + } + async::Completion, table::TableError>> rowsOf( + std::int64_t first, std::int64_t count, std::span columns) override { + return _inner->rowsOf(first, count, columns); + } + void onChange(std::function handler) override { _handler = std::move(handler); } + + /// The next `visible` call is a new mount's first, not a scroll. + void mounting() { _mounting = true; } + + /// The view rows the mount last named in or near view: the rows a backend holds. + [[nodiscard]] std::pair shownRange() const { return {_first, _count}; } + + /// Sets what widens the columns the mount names into those fetched: each with its companions. + void companions(std::function(std::span)> widen) { + _companions = std::move(widen); + } + + /// Names @p id to every later `visible` call, and fetches it now for the rows in view; an id named already is + /// not added again. + void fetchAlso(std::span ids) { + bool added = false; + for (std::string const& columnId : ids) { + if (!std::ranges::contains(_extra, columnId)) { + _extra.push_back(columnId); + added = true; + } + } + if (added) { + send(); + } + } + +private: + void send() { + std::vector named = _companions ? _companions(_columns) : _columns; + for (std::string const& columnId : _extra) { + if (!std::ranges::contains(named, columnId)) { + named.push_back(columnId); + } + } + _inner->visible(_first, _count, named); + } + + std::shared_ptr _inner; + std::function _changed; + std::function _scrolled; + std::function _reset; + std::function _filtered; + std::function _handler; + std::int64_t _first = 0; + std::int64_t _count = 0; + std::vector _columns; + std::vector _extra; + std::function(std::span)> _companions; + bool _mounting = false; +}; + +/// What a table keeps of its configuring across every mount of it: the columns its layout arranges, in the order of +/// `Table::columns`, what the user may change of them, the layout it holds, and what a change does beyond that. +/// +/// The slots a mount sets (`filterTarget`, `dimensions`, `gather`, `heldCell`) belong to that mount: `beginMount` +/// starts one, and the token `mountSlots` gives clears them when the mount's handlers go, unless a later mount has set +/// them since. A slot may then hold the mount's scope: the element keeps the configuring, so a slot that outlived its +/// mount would keep the scope that keeps the element. +struct TableConfig { + // Defined out of line, in one translation unit: inlined into every table's constructor, `FilterMenu`'s constructor + // makes GCC at -O3 report its temporary state's strings as maybe-uninitialized. + explicit TableConfig(reactive::Runtime& runtime); + + /// The table's element, whose sort, status line and commands the gestures reach. + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes): TableConfig is the table's configuring state: the mount, the menus and the document's wiring read and assign these slots directly, each slot set by whichever mount owns it + ElementState* element = nullptr; + /// The columns, each with its id, label, lock and kind; those declared hidden; and which of them sort. + std::vector columns; + std::vector declaredHidden; + std::vector sortable; + /// What `configurable` lets the user change, and whether the table has menus (`configurable: false` has none). + Configure allowed = Configure::All; + bool menus = true; + /// The table's own layout, as the user or the stored state left it; none: as declared. + std::optional held; + /// The document's `layout`; null while the table holds its own. + reactive::Computed* bound = nullptr; + /// Bumped on every change of the columns or of the held layout. + reactive::Signal version; + /// The bound on the sort chain, read at each gesture: a model's table has it from the description it holds. + std::function maxSortKeys; + /// Shows a message in the table's status line, or clears it with an empty one. + std::function message; + /// Marks the table as changed by its user, so a stored state that arrives later is not applied over it, and + /// clears its status line's message. + std::function touch; + /// Saves parts of the arrangement; empty for a table that persists nothing. + std::function save; + /// Whether the column chooser and the sort dialog are open, and the group "Group columns…" is forming: kept + /// here, so a new mount of the table (a model's new revision) keeps them. + reactive::Signal chooserOpen; + reactive::Signal sortOpen; + reactive::Signal groupDraft; + /// The filters the table holds, tracked; empty for a table that filters nothing. + std::function filters; + /// Gives the rows the user's filters and holds them; returns whether the rows took them, a refusal said in the + /// status line. Not called while the document binds the filters. + std::function setFilters; + /// Whether the document binds the filters: a user's change runs `onFiltersChange` and is neither held nor saved. + bool filtersBound = false; + /// The rows a filter menu's values are asked of. + std::function rows; + /// A column as a filter menu edits it, by id: its kind, its display and its units; none for a column that is not + /// filterable. Set by each mount, with what it shows. + std::function(std::string const&)> filterTarget; + /// The groups the table declares: a `rows` table's `groups`, a model's table's description's. + std::function()> declaredGroups; + /// A `Measure` column's dimensions and the units each can show, by id; none for another column. + std::function(std::string const&)> dimensions; + /// The columns an open values list reads, which a table over `rows` keeps in use; empty when it closes. + std::function const&)> listing; + /// The filter menu, kept here so a new mount of the table keeps it open. + std::unique_ptr filterMenu; + /// The cell keyboard focus is on, as the mount last told it; none before any. + std::optional focused; + /// Gathers the rows of these keys, by the column ids given, each cell as the table shows it; a key the rows do + /// not have is left out. Set by each mount, with what it shows. + std::function, std::vector const&, CopyDone)> gather; + /// A held row's cell, by the row's key and the column's id; none while the rows do not hold the row, and empty for + /// a table whose cells have no menu. Set by each mount, with what it shows. + std::function(Key const&, std::string const&)> heldCell; + /// The latest copy: a copy whose rows arrive after a later one started writes nothing. + std::uint64_t copies = 0; + /// The rows a selection of the view holds, while the selection is one; none while it is keys. Set by each mount + /// of a model's table. + std::function()> viewSelected; + /// Gathers the rows of the selection of the view, in view order, by the column ids given. Set by each mount of a + /// model's table. + std::function const&, CopyDone)> gatherView; + /// Selects these keys as a user's selection does: held by the element, or given to `onSelectionChange` where the + /// document binds the selection. Set by each mount of a model's table. + std::function const&)> selectKeys; + /// The saved view the arrangement was taken from, the state's `view`, and whether it is a shared one applied from + /// "Shared views"; a stored `view` names one of the user's own. + std::optional savedView; + bool viewShared = false; + /// The table's saved views, which the table's element holds beside this; null for a table that keeps no state. + TableViews* views = nullptr; + /// The description a saved view is fitted to, as a stored state is; none while the table has none. + std::function()> description; + /// Readies the columns a state or a view sorts and filters by before it is fitted: a table over `rows` knows a + /// column's kind only while it is in use, so a filter on another would be fitted to the wrong kind and dropped. + /// Empty for a table whose description holds its kinds. + std::function prepare; + /// The view name dialog, kept here so a new mount of the table keeps it open. + reactive::Signal viewDialog; + /// What a views change answers into: nothing once the configuring is gone. + async::CallbackScope viewsScope; + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes) + + /// Starts a mount: the slots it sets are its own until a later mount starts. + void beginMount() { ++_mount; } + + /// A token for the mount begun last: when the last copy of it goes, the slots that mount set are cleared, unless a + /// later mount has begun or the configuring is gone. + /// @return The token, for the mount's handlers to hold. + [[nodiscard]] std::shared_ptr mountSlots() { + struct Slots { + TableConfig* config; + std::weak_ptr alive; + std::uint64_t mount; + Slots(TableConfig* owner, std::weak_ptr token, std::uint64_t serial) + : config{owner}, alive{std::move(token)}, mount{serial} {} + Slots(Slots const&) = delete; + Slots& operator=(Slots const&) = delete; + Slots(Slots&&) = delete; + Slots& operator=(Slots&&) = delete; + ~Slots() { + if (alive.lock() != nullptr && config->_mount == mount) { + config->filterTarget = {}; + config->dimensions = {}; + config->gather = {}; + config->heldCell = {}; + config->viewSelected = {}; + config->gatherView = {}; + config->selectKeys = {}; + } + } + }; + return std::make_shared(this, _alive, _mount); + } + +private: + std::uint64_t _mount = 0; + std::shared_ptr _alive = std::make_shared(0); +}; + +/// What a table's literal `configurable` lets its user change, and whether it has menus: `true` and an absent key +/// allow everything, `false` nothing and offers no menu, a list what it names. The loader refused any other value. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): reads the `configurable` literal: true, false or a list of names, each name adding a bit to the allowed set +[[nodiscard]] std::pair configurableOf(DocNode const& node); + +/// The layout of a table's columns: as declared, fitted to @p value when one is given. +[[nodiscard]] table::ColumnLayout layoutOver(std::span columns, + std::vector const& declaredHidden, + std::optional const& value); + +/// A layout as the `layout` element value and `onLayoutChange`'s event hold it: `order`, `hidden`, `pinned` and +/// `widths`, and `groups` and `units` while they hold anything. +[[nodiscard]] Value layoutValueOf(table::ColumnLayoutValue const& layout); + +/// Filters as the `filters` element value and `onFiltersChange`'s event hold them: the filter's JSON, each group +/// filter naming its declared group or its columns, never an empty one of the two. +[[nodiscard]] Value filtersValueOf(table::FilterSpec const& filters); + +/// The layout a table holds now: the document's, when it binds one, else the table's own. Tracked. +[[nodiscard]] std::optional layoutNow(TableConfig const& config); + +/// Draws a filter button on each column a filter menu edits. +/// @param config The table's configuring, whose `filterTarget` says which columns filter. +/// @param columns The mount's columns, in the order of `config.columns`. +/// @param options The table's options; without `onFilter` no column draws a button. +void markFilterable(TableConfig const& config, std::vector& columns, TableOptions const& options); + +/// What a model-backed table keeps in its element, across every mount of it: its rows and the query of its +/// description, the arrangement it gave the rows, its persisted state's key and load, and its status line's message. +// NOLINTNEXTLINE(clang-analyzer-optin.performance.Padding): the fields are grouped and commented by role, and the callback scope is declared last so it is destroyed first; a size-ordered layout would break both +struct ModelTable { + explicit ModelTable(reactive::Runtime& runtime) + : version{runtime, 0}, + resets{runtime, 0}, + revision{runtime, std::string{}}, + highlight{runtime, std::nullopt}, + message{runtime, std::string{}}, + entries{runtime, std::vector{}}, + viewSelection{runtime, std::nullopt}, + marksRevision{runtime, 0}, + keyMoves{runtime, KeyMoves{}}, + config{runtime} {} + + ModelTable(ModelTable const&) = delete; + ModelTable& operator=(ModelTable const&) = delete; + ModelTable(ModelTable&&) = delete; + ModelTable& operator=(ModelTable&&) = delete; + + /// A change not yet saved is saved at once: the table is unmounting. + // NOLINTNEXTLINE(bugprone-exception-escape): the table's teardown has no recovery if unlinking the runs observer or flushing the state throws, so terminating is the outcome + ~ModelTable() { + if (core != nullptr) { + std::erase(core->modelTables, element); + if (runs != nullptr) { + core->session.removeRunObserver(runs.get()); + } + } + if (states != nullptr && stateKey) { + states->flush(*stateKey); + } + } + + /// Lets the rows send their first query, with the sort and filters set meanwhile; once. + void release() { + if (std::exchange(waiting, false)) { + loadTimer.cancel(); + window->release(); + } + } + + /// Tells every reader of the rows' counts and error that they may have changed. + void bump() { version.set(version.peek() + 1); } + + /// The screen, which lists the table while it lives, and the table's element. + ScreenCore* core = nullptr; + ElementState* element = nullptr; + /// The table's id among its model's tables. + std::string id; + /// The model's type. + std::string modelType; + /// The description's key column. + std::string keyColumn; + /// The query of `Table..describe`, and its declaration. + QueryDecl describeDecl; + std::unique_ptr describe; + std::shared_ptr window; + std::shared_ptr rows; + /// Bumped on every change of the rows, their counts or their error. + reactive::Signal version; + /// Bumped on every reset of the rows (a new query): a row found by key is located again. + reactive::Signal resets; + /// The held description's revision; empty while none is held. + reactive::Signal revision; + /// The highlighted row: the key `highlightKey` names and the view row a keyed fetch found it at. + reactive::Signal> highlight; + /// The status line's message, the choices it offers, and what each choice runs, by its id. + reactive::Signal message; + reactive::Signal> entries; + std::map, std::less<>> entryHandlers; + reactive::TimerHandle messageTimer; + /// The selection while it is of the view (`view` engaged): the element's `selection` is then empty. + reactive::Signal> viewSelection; + /// Read first by every row's marks: the rows' retained and unmatched state is not reactive, so this is bumped + /// after every change of it, and a row that becomes unmatched is drawn again. + reactive::Signal marksRevision; + /// The rows an action of this session gave new keys, for the mount's focus and highlight to follow. + reactive::Signal keyMoves; + /// The node's `retainChanged`: the rows an action of this session changed stay in view. + bool retainChanged = false; + /// Hears the session's runs while the table lives, to offer a refused selection of the view again. + std::unique_ptr runs; + /// Whether the status line takes space; `status: false` sends messages to the host instead. + bool statusShown = true; + /// The persisted state's key, and the states it is loaded from and saved to; none without persistence. + std::optional stateKey; + TableStates* states = nullptr; + /// Whether the rows wait for the stored state before their first query. + bool waiting = false; + reactive::TimerHandle loadTimer; + /// Whether the user scrolled, selected or changed the arrangement: a stored state that arrives later is not + /// applied over it. + bool touched = false; + /// The sort and filters the rows were given, so a new description's fitting can name what it drops. + SortChain sort; + table::FilterSpec filter; + /// The column layout, which the stored state, a `columns` point and the user's gestures set, and the saved + /// view's name, as the stored state, a `saved` point or the "Views" menu gave it. + TableConfig config; + /// Whether the document binds the filters: they are neither restored nor saved. + bool filtersBound = false; + /// A filter set while the kinds of a typed list action's columns wait for its first reply, applied once they + /// are fixed; and whether it is the stored one, fitted and reported as stored state is. + std::optional heldFilter; + bool heldStored = false; + /// Whether the user set the filter through the table's own gestures: a held literal or stored filter does not + /// replace it. + bool userFiltered = false; + /// The described columns' ids. + std::set> described; + /// The fields the row bindings missed this turn; one task fetches them all. + std::set> missing; + std::function onMissing; + /// The row scopes `onActivate` runs in, by the row's canonical key. + std::map, std::less<>> rowScopes; + /// The table's saved views; none without persistence. + std::unique_ptr views; + /// The calls of the table's model alias: what the table's own edits are sent through, and a choice's options + /// fetched with. + forms::Submitter calls; + /// The drafts, errors, marks and commits of the table's editable cells, held by row key for as long as the table: + /// a new description's mount finds them where they were. + std::unique_ptr edits; + /// The mounted table's cells as a grid, while an editable table is mounted. + std::weak_ptr editGrid; + /// Last, so it is the first to go: no load, timer or post reaches a half-destroyed table. + async::CallbackScope scope; +}; + +/// The rows a table over `rows` shows its mount: the page of its engine's view, each group's heading entry before +/// the first of its rows the page holds, so a group split across pages gets its heading on both. The table sets the +/// entries after each change of the view or the page; while the engine's rows are held back, so are these. +class PageRows final : public TableRows { +public: + /// One row the page shows: a data row, or a group's heading whose record is its run's. + struct Entry { + table::RowId key; + Value row; + }; + + PageRows(std::shared_ptr engine, exec::IExecutor& owner) + : _engine{std::move(engine)}, _owner{&owner} {} + + PageRows(PageRows const&) = delete; + PageRows& operator=(PageRows const&) = delete; + PageRows(PageRows&&) = delete; + PageRows& operator=(PageRows&&) = delete; + ~PageRows() override = default; + + /// Reads a new engine's rows from now on: the table made one for units its rows brought. + void setEngine(std::shared_ptr engine) { _engine = std::move(engine); } + + /// Takes the page's new entries and tells the mount how the view changed. + void show(std::vector entries, table::ViewChange const& change) { + _entries = std::move(entries); + if (_handler) { + _handler(change); + } + } + + /// Tells the mount the whole view changed, the entries kept: the engine's rows changed under a page that did + /// not, such as while they are held back. + void reset() { + if (_handler) { + table::ViewChange change; + change.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}); + _handler(change); + } + } + + [[nodiscard]] TableTotal total() const override { + if (_engine->restoring()) { + return _engine->total(); + } + return TableTotal{ + .rows = static_cast(_entries.size()), .kind = table::TotalKind::Exact, .known = true}; + } + [[nodiscard]] std::optional row(std::int64_t index) const override { + if (_engine->restoring() || index < 0 || static_cast(index) >= _entries.size()) { + return std::nullopt; + } + Entry const& entry = _entries.at(static_cast(index)); + return TableRowRef{.key = entry.key, .row = entry.row}; + } + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override { + static_cast(index); + return {}; + } + void visible(std::int64_t first, std::int64_t count, std::span columns) override { + static_cast(first); + static_cast(count); + static_cast(columns); + } + /// The keys of a range of the page's entries, headings included, at once. + async::Completion, table::TableError>> keysOf( + std::int64_t first, std::int64_t count) override { + using Result = std::expected, table::TableError>; + auto [completion, promise] = async::Completion::makeSettleable(_owner); + auto const size = static_cast(_entries.size()); + if (first < 0 || count < 0 || count > size - first) { + promise.resolve(Result{std::unexpected(table::TableError{ + .code = table::TableErrorCode::InvalidSpec, + .column = {}, + .message = std::format("{} rows from row {} are not in a page of {}", count, first, size)})}); + return std::move(completion); + } + std::vector keys; + keys.reserve(static_cast(count)); + for (std::int64_t at = first; at < first + count; ++at) { + keys.push_back(_entries.at(static_cast(at)).key); + } + promise.resolve(Result{std::move(keys)}); + return std::move(completion); + } + /// Where the key is among the page's entries, answered on the owner: a row of the engine's view the page does + /// not hold is not in the view the mount sees. + void locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) override { + auto const hit = std::ranges::find(_entries, key, &Entry::key); + // Assigned, not cast: the iterator difference is `std::ptrdiff_t`, which is `std::int64_t` only on some + // targets. + std::int64_t const index = hit - _entries.begin(); + RowLocation const found{hit == _entries.end() ? std::nullopt : std::optional{index}}; + _owner->post([stop = std::move(stop), done = std::move(done), found] { + if (!stop.stop_requested()) { + done(found); + } + }); + } + /// The engine's rows: a key's view index is its place in the engine's view, not among the page's entries. + async::Completion, table::TableError>> fetchRows( + std::vector keys, std::vector columns) override { + return _engine->fetchRows(std::move(keys), std::move(columns)); + } + std::expected setSort(SortChain sort) override { + return _engine->setSort(std::move(sort)); + } + std::expected setFilter(table::FilterSpec filter) override { + return _engine->setFilter(std::move(filter)); + } + async::Completion> distinctValues( + table::DistinctRequest request) override { + return _engine->distinctValues(std::move(request)); + } + /// The engine's counts: the view's rows, not the page's entries, and nothing known while held back. + [[nodiscard]] TableCountsView counts() const override { return _engine->counts(); } + void onChange(std::function handler) override { _handler = std::move(handler); } + [[nodiscard]] RowStates& states() override { return _engine->states(); } + [[nodiscard]] RowStates const& states() const override { return _engine->states(); } + void moveKey(table::RowId const& from, table::RowId const& target) override { _engine->moveKey(from, target); } + +private: + std::shared_ptr _engine; + exec::IExecutor* _owner; + std::vector _entries; + std::function _handler; +}; + +/// What a table over `rows` keeps in its element, across every mount of it: its rows on the engine and the page of +/// them it shows, the arrangement it gave them, its persisted state's key and load, and its status line's message. +/// A table lowered where names its element cannot see are bound has one of its own, kept by its mount, which +/// persists nothing. A collection's table is one too, without a source or a page: its engine is over the session's +/// source, and its mounts read the engine's rows through the element's `tableRows`. +// NOLINTNEXTLINE(clang-analyzer-optin.performance.Padding): the fields are grouped and commented by role, and the callback scope is declared last so it is destroyed first; a size-ordered layout would break both +struct RowsTable { + explicit RowsTable(reactive::Runtime& runtime) + : version{runtime, 0}, message{runtime, std::string{}}, config{runtime} {} + + RowsTable(RowsTable const&) = delete; + RowsTable& operator=(RowsTable const&) = delete; + RowsTable(RowsTable&&) = delete; + RowsTable& operator=(RowsTable&&) = delete; + + /// Its computations stop first; then the columns' tracked `sortBy`s and the `group`'s `by`, which read the + /// table's scope, leave the source, which the mount may keep longer; a change not yet saved is saved at once. + // NOLINTNEXTLINE(bugprone-exception-escape): the table's teardown has no recovery if unlinking the engine, the source or the state store throws, so terminating is the outcome + ~RowsTable() { + effects.clear(); + if (engine != nullptr) { + engine->onChange({}); + } + if (source != nullptr) { + for (std::string const& column : used) { + source->unuse(column); + } + if (grouped) { + source->setGroup({}, {}); + } + } + if (core != nullptr && listed) { + std::erase(core->modelTables, element); + } + if (states != nullptr && stateKey) { + states->flush(*stateKey); + } + } + + /// Tells every reader of the view, its counts and its page that they may have changed. + void bump() { version.set(version.peek() + 1); } + + /// Lets the rows through, once: the stored arrangement is in place, or it will not come in time. + void release() { + loadTimer.cancel(); + waiting = false; + engine->setRestoring(false); + } + + /// The screen, and the table's element and node. + ScreenCore* core = nullptr; + ElementState* element = nullptr; + DocNode const* node = nullptr; + RtScope* where = nullptr; + /// The names bound where the table is lowered; null for the element's own. + std::shared_ptr bindings; + /// Whether the screen lists the table among those that keep a state. + bool listed = false; + /// Whether the table is its element's own, whose `tableRows` reads its engine. + bool elementOwn = false; + std::shared_ptr source; + std::shared_ptr engine; + std::shared_ptr rows; + /// The summary rows over the page's entries, which the mount is handed in their place; null with no summaries. + std::shared_ptr summaries; + /// Each run of the page by ordinal: its heading's key, by which its rows are found in the view. + std::vector runHeadings; + /// Bumped on every change of the engine's view. + reactive::Signal version; + /// The rows in view order and the page shown. + std::unique_ptr> view; + /// The status line's message, and the literal `status`: shown always, never, or while it has something to say. + reactive::Signal message; + reactive::TimerHandle messageTimer; + std::optional status; + /// The column layout and what its user may change. + TableConfig config; + /// The persisted state's key, and the states it is loaded from and saved to; none without persistence. + std::optional stateKey; + TableStates* states = nullptr; + /// Whether the rows are held back for the stored state; whether they are let through once the engine settles. + bool waiting = false; + bool releasing = false; + reactive::TimerHandle loadTimer; + /// Whether the user changed the arrangement or the selection: a stored state that arrives later is not applied. + bool touched = false; + /// The sort the engine was given, without the group's key; the filters it was given; the columns an open values + /// list reads; and the columns in use for all three. + SortChain sort; + table::FilterSpec filter; + std::vector listedColumns; + std::vector used; + bool grouped = false; + /// The column groups the node declares (`groups`), which the source declares to the engine. + std::vector groups; + /// What has been reported once: the list over the client's bound, and an invalid cell of a sort column. + bool boundReported = false; + bool invalidReported = false; + /// The page last shown: the `version` of the view it was cut from, and its place in it. + struct Shown { + std::uint64_t version = 0; + std::size_t first = 0; + std::size_t last = 0; + bool any = false; + } shown; + /// What a new source and engine are made from: the columns, a row's key, the `group`'s `by`, the screen's unit + /// table and the units the rows brought that it does not list. + std::vector columns; + std::function keyOfRow; + std::function byOf; + UnitTable units; + std::set> unitsSeen; + /// What the table does on each change of its engine's view. + std::function heard; + /// Shows a page of the view to the mount, passing on the engine's change when it may. + std::function showPage; + std::vector> effects; + /// The table's saved views; none without persistence. + std::unique_ptr views; + /// Last, so it is the first to go: no load, timer or post reaches a half-destroyed table. + async::CallbackScope scope; +}; + +/// A table's `bands` parts as bands: each part's label, unit, literal list of column ids and bands one level down. The +/// loader refused any other shape. +// NOLINTNEXTLINE(misc-no-recursion): a band's bands are bands one level down. +[[nodiscard]] std::vector bandsOf(std::span parts); + +/// A table's or a group's `summaries` parts as the decorator takes them: each key, and whether it is drawn on top. +[[nodiscard]] std::vector summarySpecsOf(std::span parts); + +/// @brief One key of a table's sort: the column part that orders the rows, and whether it is descending. +struct SortKey { + /// @brief The sortable column. + DocNode const* column = nullptr; + /// @brief Whether the key sorts descending. + bool descending = false; +}; + +/// @brief A table's sort read as its keys: a list of `{"column", "direction"}` records naming sortable columns. +/// @param table The table. +/// @param sort The sort; `null` is the source order, as `[]` is. +/// @return The keys, most significant first; `nullopt` when @p sort is not such a list. +[[nodiscard]] std::optional> sortKeysOf(DocNode const& table, Value const& sort); + +/// @brief A table's selection as an action takes it: the selection of the view while a model's table holds one, +/// else the selected keys. Tracked. +/// @param element The table's element. +/// @return The selection. +[[nodiscard]] TableSelection selectionNow(ElementState const& element); + +/// A column's display with a column part's display parts over it, member by member. +/// @param part The column part. +/// @param display The display the part overrides. +/// @param read Reads one of the part's expressions once. +[[nodiscard]] table::ColumnDisplay displayOf(DocNode const& part, table::ColumnDisplay display, + std::function const& read); + +/// A record's field as a cell of its column: what `formatCell` reads. The record holds a `Date` as `YYYY-MM-DD`, a +/// `DateTime` as a timestamp and a measure as a `Quantity` named by its unit's id, and holds `null` for an empty +/// cell and for an unloaded one alike: the placeholder of an unloaded cell is the mount's (`setCellLoad`). +/// @param value The field; null when the record lacks it. +/// @param column The column. +/// @param units The registry a measure's unit is found in; null for none. +[[nodiscard]] table::Cell cellOfRecord(Value const* value, table::TableColumn const& column, + table::UnitRegistry const* units); + +/// What a rows table's column shows for a value, by the kind the value has: a rows table declares no kinds. +[[nodiscard]] table::TableColumn columnFor(Value const& value, table::ColumnDisplay const& display); + +/// @brief A sort as a table's element value holds it, a list of `{column, direction}`, as a sort chain; an entry +/// that names no column is left out. +/// @param value The list. +/// @return The chain. +[[nodiscard]] SortChain sortChainOf(Value const& value); + +/// @brief A sort chain as a table's element value holds it. +/// @param chain The chain. +/// @return The list of `{column, direction}`. +[[nodiscard]] Value sortValueOf(SortChain const& chain); + +/// @brief The column kind a column part's literal `kind` names. +/// @param name The name; empty for none. +/// @return The kind; nothing for no name, which infers the kind from the cells. +[[nodiscard]] std::optional columnKindNamed(std::string_view name); + +/// @brief Gives a table over `rows` a new source and engine over the units known now. The columns in use, the +/// groups, the sort and whether the rows are held back carry over from the ones they replace; the caller +/// assigns the rows. +/// @param table The table. +/// @param runtime The screen's runtime. +void startRowsEngine(RowsTable& table, reactive::Runtime& runtime); + +/// @brief The columns a table over `rows` keeps in use: those a sort, filters and an open values list read, each once. +/// @param table The table, whose declared groups and open list are read. +/// @param sort The sort. +/// @param filter The filters. +/// @return The columns' ids. +[[nodiscard]] std::vector usedColumns(RowsTable const& table, SortChain const& sort, + table::FilterSpec const& filter); + +/// @brief Puts columns in use and takes the others out: the new ones first, so a column both read keeps its cells. +/// @param table The table. +/// @param next The columns in use from now. +void useColumns(RowsTable& table, std::vector next); + +/// @brief Loads a table's state and its saved views in the same turn, so a store that batches reads them in one call, +/// and calls @p done once both have answered: the default view decides what a table with no stored state +/// starts from. Views that cannot be read are left unsaid. +/// @param states The session's table states. +/// @param key The table's state key. +/// @param views The table's saved views. +/// @param scope The table's scope: nothing is called once it is gone. +/// @param done Called with the stored state's text, none when nothing is stored, and the reason its load failed, +/// empty when it did not. +void loadStateAndViews(TableStates& states, table::TableStateKey const& key, TableViews& views, + async::CallbackScope const& scope, + std::function const&, std::string const&)> done); + +// The rows a grid with summaries or a group is mounted over: the decorator's, a data row's cell as the grid draws it, +// a summary row's cell its part's expression for the column read with `rows` the records of the data rows in its +// scope and `column` the column's id, shown at the column's places, and a heading row its group's heading. Every +// column's cells are built per row, so a cell built for a data row is never rebound to a summary row. + +std::vector> rowsRuns(RowsTable& table); + +ValueList rowsSummaryScope(RowsTable const& table, Value const& record); + +} // namespace detail + +} // namespace morph::ui diff --git a/src/ui/interpreter_table_layout.cpp b/src/ui/interpreter_table_layout.cpp new file mode 100644 index 000000000..b247170b3 --- /dev/null +++ b/src/ui/interpreter_table_layout.cpp @@ -0,0 +1,1344 @@ +// SPDX-License-Identifier: Apache-2.0 + +// A model-backed table's columns and configuration. + +#include "interpreter_table_detail.hpp" + +namespace morph::ui::detail { + +namespace { + +/// Makes each of a table's menu entries clear the status line's message before it runs, as every gesture on the table +/// does. +// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. +void clearsMessageFirst(TableConfig& config, std::vector& items) { + for (MenuItem& item : items) { + clearsMessageFirst(config, item.items); + if (item.onSelect) { + item.onSelect = [&config, run = std::move(item.onSelect)] { + if (config.message) { + config.message({}); + } + run(); + }; + } + } +} + +/// The chords menu entry parts declare in `keys`, their submenus' included, each once. +// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. +std::vector chordsOf(std::span parts, std::vector out = {}) { + for (DocNodePtr const& part : parts) { + if (std::string const chord{part->name("keys")}; !chord.empty() && !std::ranges::contains(out, chord)) { + out.push_back(chord); + } + out = chordsOf(part->partList("items"), std::move(out)); + } + return out; +} + +} // namespace + +[[nodiscard]] Value layoutValueOf(table::ColumnLayoutValue const& layout) { + auto const ids = [](std::span list) { + ValueList out; + for (std::string const& columnId : list) { + out.emplace_back(columnId); + } + return Value{std::move(out)}; + }; + ValueRecord out; + out.insert_or_assign("order", ids(layout.order)); + out.insert_or_assign("hidden", ids(layout.hidden)); + out.insert_or_assign("pinned", Value{static_cast(layout.pinned)}); + ValueRecord widths; + for (auto const& [columnId, width] : layout.widths) { + widths.insert_or_assign(columnId, Value{static_cast(width)}); + } + out.insert_or_assign("widths", Value{std::move(widths)}); + if (!layout.groups.empty() || !layout.units.empty()) { + auto const json = parseJson(glz::write_json(layout).value_or("null")); + auto read = json ? valueFromJson(*json) : std::expected{Value{}}; + if (ValueRecord const* const whole = read ? read->asRecord() : nullptr) { + if (auto const groups = whole->find("groups"); groups != whole->end() && !layout.groups.empty()) { + out.insert_or_assign("groups", groups->second); + } + if (auto const units = whole->find("units"); units != whole->end() && !layout.units.empty()) { + out.insert_or_assign("units", units->second); + } + } + } + return Value{std::move(out)}; +} + +namespace { + +/// The arrangement a mount takes from a layout, by index into @p columns; the default one while the layout is the +/// declared order with every column shown, none pinned and no width set, so such a table is laid out as one with +/// no layout is. +[[nodiscard]] TableArrangement arrangementOf(std::span columns, + table::ColumnLayout const& layout) { + std::vector const visible = layout.visible(); + bool plain = visible.size() == columns.size() && layout.pinned() == 0 && layout.widths().empty(); + for (std::size_t at = 0; plain && at < visible.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `at` is below `visible.size()` and `columns.size()` by the loop condition above + plain = visible[at] == columns[at].id; + } + TableArrangement out; + if (plain) { + return out; + } + auto const indexOf = [columns](std::string const& columnId) -> std::optional { + auto const found = std::ranges::find(columns, columnId, &LayoutColumn::id); + return found == columns.end() ? std::nullopt + : std::optional{static_cast(found - columns.begin())}; + }; + for (std::string const& columnId : visible) { + if (std::optional const index = indexOf(columnId)) { + out.visible.push_back(*index); + } + } + out.pinned = layout.pinned(); + for (auto const& [columnId, width] : layout.widths()) { + if (std::optional const index = indexOf(columnId)) { + out.widths.insert_or_assign(*index, width); + } + } + return out; +} + +/// The entries of a menu whose commands the lowering carries out: the sort, filter and arranging entries, "Display +/// unit", "Clear all filters", "Reset columns", "Columns…", "Sort…", "Copy", "Copy with headers", and an entry that +/// does nothing itself ("Views", whose views commands `Table::onMenu` carries out). Any other is not offered; a +/// separator left at either end or beside another goes with it. +[[nodiscard]] std::vector offeredEntries(std::vector entries) { + auto const offered = [](TableMenuEntry const& entry) { + if (entry.entry.separator || entry.command == MenuCommand::None) { + return true; + } + switch (entry.command) { + case MenuCommand::SortAscending: + case MenuCommand::SortDescending: + case MenuCommand::AddToSort: + case MenuCommand::RemoveFromSort: + case MenuCommand::MoveLeft: + case MenuCommand::MoveRight: + case MenuCommand::PinColumn: + case MenuCommand::UnpinColumn: + case MenuCommand::HideColumn: + case MenuCommand::ResetColumns: + case MenuCommand::Columns: + case MenuCommand::SortDialog: + case MenuCommand::Filter: + case MenuCommand::FilterGroup: + case MenuCommand::ClearAllFilters: + case MenuCommand::DisplayUnit: + case MenuCommand::Copy: + case MenuCommand::CopyWithHeaders: + return true; + case MenuCommand::ApplyView: + case MenuCommand::SaveView: + case MenuCommand::RenameView: + case MenuCommand::RemoveView: + case MenuCommand::SetDefaultView: + case MenuCommand::DefaultOnMount: + case MenuCommand::ApplySharedView: + case MenuCommand::PublishView: + case MenuCommand::SaveAsMyView: + case MenuCommand::None: + default: + return false; + } + }; + std::vector kept; + for (TableMenuEntry& entry : entries) { + if (!offered(entry) || (entry.entry.separator && (kept.empty() || kept.back().entry.separator))) { + continue; + } + kept.push_back(std::move(entry)); + } + if (!kept.empty() && kept.back().entry.separator) { + kept.pop_back(); + } + return kept; +} + +} // namespace + +void ScreenCore::modelLayoutColumns(ElementState& element) const { + ModelTable& model = *element.modelTable; + TableConfig& config = model.config; + DocNode const& node = *element.node; + RtScope& scope = *element.scope; + auto const parts = node.partList("columns"); + config.columns.clear(); + config.declaredHidden.clear(); + config.sortable.clear(); + if (table::TableDescription const* const description = model.window->description()) { + for (table::TableColumn const* const column : arrangedColumns(node, *description)) { + auto const part = std::ranges::find(parts, column->info.id, + [](DocNodePtr const& given) -> auto const& { return given->id; }); + bool const named = part != parts.end(); + std::string label = column->label.empty() ? column->info.id : column->label; + if (ExprPtr const given = named ? (*part)->prop("label") : nullptr) { + label = runtime().untracked([&] { return textOf(evalIn(scope, nullptr, given), scope.formatting()); }); + } + config.columns.push_back(LayoutColumn{.id = column->info.id, + .label = std::move(label), + .locked = named && (*part)->flag("locked"), + .kind = column->info.kind}); + config.sortable.push_back(column->sortable); + // A column the description does not show starts hidden; a column part shows the column it names. + if (!named && !column->shown) { + config.declaredHidden.push_back(column->info.id); + } + } + } + config.version.set(config.version.peek() + 1); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity, readability-function-size): the sort, the layout, then the menus that reach both; each option wires a handler that reads the same config and nodes +Node ScreenCore::configureTable(TableConfig& config, LowerCtx const& ctx, TableOptions& options, + std::shared_ptr const& keep) { + ElementState& element = *config.element; + DocNode const& node = *element.node; + // This mount's columns: a new description mounts the table again, with its own. + auto const columns = std::make_shared const>(config.columns); + auto const sortable = std::make_shared const>(config.sortable); + auto const hidden = std::make_shared const>(config.declaredHidden); + auto const layoutHeld = [&config, columns, hidden] { return layoutOver(*columns, *hidden, layoutNow(config)); }; + // Every key of the chain marks its header, in the chain's order; a sort that is not a list of keys naming + // sortable columns, each with a direction, marks none, as the rows keep their order under it. + options.sort = slotProp>([&element, columns, sortable] { + std::vector out; + Value const sort = tableSort(element); + if (sort.isNull()) { + return out; + } + ValueList const* const keys = sort.asList(); + if (keys == nullptr) { + return out; + } + for (Value const& key : *keys) { + Value const* const column = key.field("column"); + Value const* const direction = key.field("direction"); + std::string const* const columnId = column == nullptr ? nullptr : column->asString(); + std::string const* const way = direction == nullptr ? nullptr : direction->asString(); + auto const found = + columnId == nullptr ? columns->end() : std::ranges::find(*columns, *columnId, &LayoutColumn::id); + if (found == columns->end() || way == nullptr || (*way != "asc" && *way != "desc")) { + return std::vector{}; + } + auto const index = static_cast(found - columns->begin()); + if (!sortable->at(index)) { + return std::vector{}; + } + out.push_back(TableSort{ + .column = index, .direction = *way == "desc" ? SortDirection::Descending : SortDirection::Ascending}); + } + return out; + }); + options.arrangement = + slotProp([columns, layoutHeld] { return arrangementOf(*columns, layoutHeld()); }); + // A copy: the selected rows in view order by the visible columns in layout order, or with no row selected the + // focused cell alone; over `maxCopyRows` keys it is refused and nothing is copied. The rows say how each cell + // shows; an unloaded cell is copied as empty and counted in the message. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): a copy: the selected rows in view order by the visible columns in layout order, or the focused cell alone, refusing past the key limit + auto const copy = [this, &config, &element, layoutHeld, keep, slots = config.mountSlots(), + scope = ctx.scope](bool headers) { + static_cast(keep); + static_cast(slots); + if (!config.gather) { + return; + } + std::vector keys; + std::vector copyColumns = runtime().untracked([&] { + if (Value const itemsValue = tableSelection(element); ValueList const* const items = itemsValue.asList()) { + for (Value const& item : *items) { + keys.push_back(keyOf(item)); + } + } + return layoutHeld().visible(); + }); + std::string separator{scope->formatting().numeric.groupSeparator}; + std::size_t const bound = session.options().maxCopyRows; + std::optional const viewing = + config.viewSelected ? runtime().untracked([&] { return config.viewSelected(); }) : std::nullopt; + if (keys.size() > bound || (viewing && std::cmp_greater(*viewing, bound))) { + config.message(tableText::copyBound(bound, separator)); + return; + } + if (keys.empty() && !viewing) { + if (!config.focused || !std::ranges::contains(copyColumns, config.focused->column)) { + return; + } + keys.push_back(config.focused->key); + copyColumns = {config.focused->column}; + } + // A copy started after this one wins: this one's rows, arriving late, write nothing. + std::uint64_t const started = ++config.copies; + auto gather = [&config, viewing, keys = std::move(keys)](std::vector const& named, + CopyDone done) mutable { + if (viewing && config.gatherView) { + config.gatherView(named, std::move(done)); + } else { + config.gather(std::move(keys), named, std::move(done)); + } + }; + gather(copyColumns, [this, &config, &element, headers, started, + separator = std::move(separator)](std::expected gathered) { + if (started != config.copies) { + return; + } + if (!gathered) { + tableMessage(element, std::move(gathered.error())); + return; + } + // None of the rows is in the view any more: the clipboard keeps what it had. + if (gathered->rows.empty()) { + return; + } + std::ranges::stable_sort(gathered->rows, {}, &CopyRow::viewRow); + std::vector>> rows; + rows.reserve(gathered->rows.size()); + for (CopyRow& row : gathered->rows) { + rows.push_back(std::move(row.cells)); + } + CopiedText const text = ui::copyText(headers ? gathered->headers : std::vector{}, rows); + if (!clipboard || !clipboard(text.text)) { + tableMessage(element, "The rows could not be copied: there is no clipboard"); + return; + } + tableMessage(element, tableText::copied(rows.size(), text.unloaded, separator)); + }); + }; + options.onCopy = [&config, copy] { + config.touch(); + copy(false); + }; + options.onFocusCell = [&config](std::optional cell) { config.focused = std::move(cell); }; + // A sort gesture: held to the table's bound, a key past it refused in the status line and the chain kept. The + // table's own sort takes the new chain when no key binds one, and is saved; then `onSortChange` runs with + // `event` the new sort. + auto const resort = [this, ctx, &config, &element, keep, commands = node.event("onSortChange")]( + std::function const& gesture) { + static_cast(keep); + SortChain const current = runtime().untracked([&] { return sortChainOf(tableSort(element)); }); + SortChange const change = gesture(current); + if (change.refusal) { + config.message(*change.refusal); + return; + } + if (change.chain == current) { + return; + } + Value const next = sortValueOf(change.chain); + runtime().batch([&] { + if (element.sortBound == nullptr) { + session.asUser([&] { + session.noteWrite(); + element.sort.set(next); + }); + if (config.save) { + table::StateDocument changed; + changed.sort = change.chain; + config.save(changed, StateParts::Sort); + } + } + runEvent(commands, ctx, next); + }); + }; + auto const sortBy = [&config, columns, sortable, resort](std::size_t index, SortGesture gesture) { + config.touch(); + if (index >= columns->size() || !sortable->at(index)) { + return; + } + resort([&](SortChain const& current) { + return applySortGesture(current, columns->at(index).id, gesture, config.maxSortKeys()); + }); + }; + // A layout gesture: refused in the status line when its column is locked or the table does not allow it. The + // table's own layout takes the change when no key binds one, and is saved; then `onLayoutChange` runs with + // `event` the new layout. The arrangement follows the layout, so the mount fetches the columns it shows. + auto const relayout = [this, ctx, &config, &element, keep, + commands = node.event("onLayoutChange")](table::ColumnLayoutValue value) { + static_cast(keep); + Value const event = layoutValueOf(value); + runtime().batch([&] { + if (config.bound == nullptr) { + session.asUser([&] { + session.noteWrite(); + config.held = value; + config.version.set(config.version.peek() + 1); + }); + if (config.save) { + table::StateDocument changed; + changed.layout = std::move(value); + config.save(changed, StateParts::Layout); + } + tablePoints(element); + } + runEvent(commands, ctx, event); + }); + }; + auto const arrange = [this, &config, columns, layoutHeld, relayout](LayoutGesture const& gesture) { + config.touch(); + table::ColumnLayout layout = runtime().untracked(layoutHeld); + LayoutResult const result = applyLayoutGesture(layout, *columns, config.allowed, gesture); + if (result.refusal) { + config.message(*result.refusal); + return; + } + if (result.changed) { + relayout(layout.value()); + } + }; + options.onSort = [sortBy](std::size_t index, HeaderClick click) { + sortBy(index, click == HeaderClick::Shift ? SortGesture::Extend : SortGesture::Click); + }; + options.onColumnMove = [&config, arrange, columns](std::size_t column, std::size_t position) { + if (column >= columns->size()) { + config.touch(); + return; + } + arrange(MoveColumnTo{.id = columns->at(column).id, .position = position}); + }; + // A table whose widths its user cannot set offers no edge to drag. + if (allows(config.allowed, Configure::Resize)) { + options.onColumnResize = [&config, arrange, columns](std::size_t column, std::optional units) { + if (column >= columns->size()) { + config.touch(); + return; + } + arrange(ResizeColumn{.id = columns->at(column).id, .units = units}); + }; + } + // Filters from the header, on every table: a column filters unless it says `filterable: false`, whatever + // `configurable` lets the user change about the columns. A user's filters go to the rows, and are held and + // saved, unless the document binds them; then `onFiltersChange` runs with `event` the new filters. + FilterMenu& menu = *config.filterMenu; + auto const refilter = [this, ctx, &config, keep, + commands = node.event("onFiltersChange")](table::FilterSpec const& spec) { + static_cast(keep); + bool applied = true; + Value const event = filtersValueOf(spec); + runtime().batch([&] { + if (!config.filtersBound) { + session.asUser([&] { + session.noteWrite(); + applied = config.setFilters && config.setFilters(spec); + }); + if (applied && config.save) { + table::StateDocument changed; + changed.filters = spec; + config.save(changed, StateParts::Filters); + } + } + if (applied) { + runEvent(commands, ctx, event); + } + }); + return applied; + }; + auto const filtersNow = [&config] { return config.filters ? config.filters() : table::FilterSpec{}; }; + // Every group the table has: those it declares, then those its user formed, each with whether it was formed. + auto const groupsNow = [&config, layoutHeld] { + std::vector> out; + if (config.declaredGroups) { + for (table::ColumnGroupInfo& group : config.declaredGroups()) { + out.emplace_back(std::move(group), false); + } + } + for (table::ColumnGroupInfo const& group : layoutHeld().groups()) { + out.emplace_back(group, true); + } + return out; + }; + // A menu names a formed group by its id after U+001F, so it never meets a declared group's id. + auto const groupArgument = [](table::ColumnGroupInfo const& group, bool formed) { + return formed ? "\x1F" + group.id : group.id; + }; + auto const columnTarget = [&config](std::string const& columnId) -> std::optional { + return config.filterTarget ? config.filterTarget(columnId) : std::nullopt; + }; + auto const groupTarget = [columnTarget](table::ColumnGroupInfo const& group, + bool formed) -> std::optional { + if (group.columns.empty()) { + return std::nullopt; + } + std::optional target = columnTarget(group.columns.front()); + if (!target) { + return std::nullopt; + } + target->column.clear(); + target->group = formed ? std::string{} : group.id; + target->columns = group.columns; + target->formed = formed; + target->label = group.label; + return target; + }; + // The columns a list reads are put in use before the menu reads the column's kind: a table over `rows` infers + // it from the cells. + auto const openColumn = [this, &config, &menu, columnTarget](std::string const& columnId) { + runtime().untracked([&] { + if (config.listing) { + config.listing({columnId}); + } + if (std::optional target = columnTarget(columnId)) { + menu.open(std::move(*target)); + } else if (config.listing) { + config.listing({}); + } + }); + }; + auto const openGroup = [this, &config, &menu, groupsNow, groupArgument, groupTarget](std::string const& argument) { + runtime().untracked([&] { + for (auto const& [group, formed] : groupsNow()) { + if (groupArgument(group, formed) != argument) { + continue; + } + if (config.listing) { + config.listing(group.columns); + } + if (std::optional target = groupTarget(group, formed)) { + menu.open(std::move(*target)); + } else if (config.listing) { + config.listing({}); + } + return; + } + }); + }; + // The menu outlives a mount, and `refilter` holds the mount's scope: the menu reaches it weakly, through what the + // mount keeps, so the element does not keep its own scope alive. + auto const applying = std::make_shared>(refilter); + menu.setHost(FilterMenuHost{ + .rows = config.rows, + .filters = [this, filtersNow] { return runtime().untracked(filtersNow); }, + .apply = + [weak = std::weak_ptr{applying}](table::FilterSpec const& spec) { + auto const live = weak.lock(); + return live != nullptr && (*live)(spec); + }, + .touch = config.touch, + .listing = config.listing, + .scheduler = session.options().scheduler, + .debounce = session.options().tableFilterDebounce, + .format = ctx.scope->formatting(), + }); + // Which columns this mount offers a filter on, read once with its columns. + auto const filterable = std::make_shared>(); + runtime().untracked([&] { + for (LayoutColumn const& column : *columns) { + filterable->push_back(columnTarget(column.id).has_value()); + } + }); + options.onFilter = [&config, columns, filterable, openColumn, applying](std::size_t index) { + static_cast(applying); + config.touch(); + if (index < columns->size() && filterable->at(index)) { + openColumn(columns->at(index).id); + } + }; + // The columns with a filter, whose headers say so, hidden ones included: the filter keeps applying while its + // column is hidden, and the header says so again once it is shown. + options.filtered = slotProp>([columns, filtersNow] { + table::FilterSpec const filters = filtersNow(); + std::vector out; + for (std::size_t at = 0; at < columns->size(); ++at) { + if (filters.columns.contains(columns->at(at).id)) { + out.push_back(at); + } + } + return out; + }); + // A group's header row stands over its columns while they stand side by side in the layout, in the group's order. + auto const sideBySide = [layoutHeld, groupsNow, filtersNow, groupArgument] { + std::vector> out; + table::ColumnLayout const layout = layoutHeld(); + std::vector const visible = layout.visible(); + table::FilterSpec const filters = filtersNow(); + for (auto const& [group, formed] : groupsNow()) { + auto const first = + std::ranges::find(visible, group.columns.empty() ? std::string{} : group.columns.front()); + auto const index = static_cast(first - visible.begin()); + bool together = first != visible.end() && index + group.columns.size() <= visible.size(); + for (std::size_t offset = 0; together && offset < group.columns.size(); ++offset) { + together = visible.at(index + offset) == group.columns.at(offset); + } + if (!together) { + continue; + } + FilterTarget probe; + probe.group = formed ? std::string{} : group.id; + probe.columns = group.columns; + probe.formed = formed; + out.emplace_back(TableColumnGroup{.label = group.label, + .first = index, + .count = group.columns.size(), + .filtered = groupFilterIndex(filters, probe).has_value()}, + groupArgument(group, formed)); + } + return out; + }; + options.columnGroups = slotProp>([sideBySide] { + std::vector out; + for (auto& [group, argument] : sideBySide()) { + static_cast(argument); + out.push_back(std::move(group)); + } + return out; + }); + options.onGroupFilter = [this, &config, sideBySide, openGroup](std::size_t index) { + config.touch(); + auto const shown = runtime().untracked(sideBySide); + if (index < shown.size()) { + openGroup(shown.at(index).second); + } + }; + // While `headerEnabled` is false a sort, filter or arrangement gesture changes nothing: it is refused in the + // status line. The condition is read at each gesture, so it follows the document's state. + ExprPtr const headerEnabledExpr = node.prop("headerEnabled"); + options.headerEnabled = bindProp(ctx, headerEnabledExpr, true, boolOf); + auto const headerOn = [this, enabled = options.headerEnabled] { + return runtime().untracked([&] { return enabled.evaluate(); }); + }; + if (headerEnabledExpr) { + auto const refused = [&config, headerOn] { + if (headerOn()) { + return false; + } + config.touch(); + config.message(std::string{tableText::kHeaderBusy}); + return true; + }; + // NOLINTNEXTLINE(bugprone-exception-escape): copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + options.onSort = [refused, sort = std::move(options.onSort)](std::size_t index, HeaderClick click) { + if (!refused()) { + sort(index, click); + } + }; + // NOLINTNEXTLINE(bugprone-exception-escape): copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + options.onColumnMove = [refused, move = std::move(options.onColumnMove)](std::size_t column, + std::size_t position) { + if (!refused()) { + move(column, position); + } + }; + if (options.onColumnResize) { + // NOLINTNEXTLINE(bugprone-exception-escape): copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + options.onColumnResize = [refused, resize = std::move(options.onColumnResize)](std::size_t column, + std::optional units) { + if (!refused()) { + resize(column, units); + } + }; + } + // NOLINTNEXTLINE(bugprone-exception-escape): copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + options.onFilter = [refused, filter = std::move(options.onFilter)](std::size_t column) { + if (!refused()) { + filter(column); + } + }; + // NOLINTNEXTLINE(bugprone-exception-escape): copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + options.onGroupFilter = [refused, filter = std::move(options.onGroupFilter)](std::size_t group) { + if (!refused()) { + filter(group); + } + }; + } + // A cell's menu: "Copy", "Copy with headers", "Filter by this value", "Exclude this value" and, on a column of a + // declared group, "Filter by this value in any "; then the document's `cellMenu` entries, lowered in the + // row's scope with `row`, `column` (the column's id) and `value` (the cell) bound. The filter entries take the + // cell's operand, or `isEmpty` on an empty cell, and are disabled on a cell not loaded or not readable, and while + // the header is disabled, when one chosen anyway is refused as the header's gestures are. + if (config.heldCell) { + // NOLINTNEXTLINE(bugprone-exception-escape, readability-function-cognitive-complexity): builds the cell menu: copy, filter and group entries each gated by the column's kind and the header's state, in menu order; copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + options.cellMenu = [this, ctx, &config, &node, columns, filterable, copy, refilter, filtersNow, keep, + headerOn](Key const& key, std::size_t column) { + static_cast(keep); + std::vector items; + std::string const columnId = column < columns->size() ? columns->at(column).id : std::string{}; + std::optional const held = + config.heldCell && !columnId.empty() ? config.heldCell(key, columnId) : std::optional{}; + CellLook const look = held ? cellLook(held->cell, held->shown, held->units) : CellLook::Unloaded; + std::optional const operand = + held ? operandOf(held->cell, held->shown, held->units) : std::nullopt; + bool const usable = (look == CellLook::Empty || (look == CellLook::Text && operand.has_value())) && + column < filterable->size() && filterable->at(column) && headerOn(); + table::FilterEntry const entry = look == CellLook::Empty + ? table::FilterEntry{.isEmpty = true} + : table::FilterEntry{.oneOf = std::vector{operand.value_or("")}}; + auto const command = [&config](std::string label, std::function run, bool enabled = true) { + MenuItem item; + item.label = std::move(label); + item.enabled = enabled; + item.onSelect = [&config, run = std::move(run)] { + config.touch(); + run(); + }; + return item; + }; + auto const filtering = [&config, headerOn](std::function run) { + // NOLINTNEXTLINE(bugprone-exception-escape): copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + return [&config, headerOn, run = std::move(run)] { + if (!headerOn()) { + config.message(std::string{tableText::kHeaderBusy}); + return; + } + run(); + }; + }; + items.push_back(command("Copy", [copy] { copy(false); })); + items.push_back(command("Copy with headers", [copy] { copy(true); })); + items.push_back(command("Filter by this value", filtering([this, columnId, entry, refilter, filtersNow] { + table::FilterSpec spec = runtime().untracked(filtersNow); + spec.columns.insert_or_assign(columnId, + table::ColumnFilter{.include = {entry}}); + static_cast(refilter(spec)); + }), + usable)); + items.push_back(command("Exclude this value", filtering([this, columnId, entry, refilter, filtersNow] { + table::FilterSpec spec = runtime().untracked(filtersNow); + std::vector& exclude = spec.columns[columnId].exclude; + auto const listed = + std::ranges::find_if(exclude, [](table::FilterEntry const& excluded) { + return excluded.oneOf.has_value(); + }); + if (entry.oneOf && listed != exclude.end()) { + if (!std::ranges::contains(*listed->oneOf, entry.oneOf->front())) { + listed->oneOf->push_back(entry.oneOf->front()); + } + } else if (!std::ranges::contains(exclude, entry)) { + exclude.push_back(entry); + } + static_cast(refilter(spec)); + }), + usable)); + if (config.declaredGroups) { + for (table::ColumnGroupInfo const& group : + runtime().untracked([&] { return config.declaredGroups(); })) { + if (!std::ranges::contains(group.columns, columnId)) { + continue; + } + items.push_back( + command("Filter by this value in any " + group.label, + filtering([this, groupId = group.id, entry, refilter, filtersNow] { + table::FilterSpec spec = runtime().untracked(filtersNow); + std::erase_if(spec.groups, [&groupId](table::GroupFilter const& filter) { + return filter.group == groupId; + }); + spec.groups.push_back(table::GroupFilter{.group = groupId, .include = {entry}}); + static_cast(refilter(spec)); + }), + usable)); + } + } + std::span const parts = node.partList("cellMenu"); + if (parts.empty()) { + return items; + } + MenuItem separator; + separator.separator = true; + items.push_back(std::move(separator)); + // The entries read the row as it was when the menu opened; the scope owns the signal that holds it. The + // scope is the menu's own: state the table's row scope declares starts at its initial value in it. + Value const record = held ? held->record : Value{}; + auto const scope = std::make_shared(*this, ctx.scope, nullptr, ctx.scope->nodes.depth() + 2); + scope->row = &scope->nodes.make>(runtime(), record); + scope->rowKey = canonicalJson(valueOfKey(key)); + declare(*scope, node.scope ? &*node.scope : nullptr, {}, {}); + auto bindings = std::make_shared(*ctx.bindings); + Value const value = [&] { + Value const* const field = record.field(columnId); + return field == nullptr ? Value{} : *field; + }(); + // NOLINTNEXTLINE(performance-no-automatic-move): the binding's read runs on every evaluation and each returns a copy of the captured record, so the capture stays const + bindings->push_back(Binding{.name = "row", .read = [record] { return record; }}); + bindings->push_back(Binding{.name = "column", .read = [columnId] { return Value{columnId}; }}); + // NOLINTNEXTLINE(performance-no-automatic-move): the binding's read runs on every evaluation and each returns a copy of the captured value, so the capture stays const + bindings->push_back(Binding{.name = "value", .read = [value] { return value; }}); + std::vector own = + menuItems(parts, LowerCtx{.scope = scope, .bindings = std::move(bindings), .boundary = ctx.boundary}); + clearsMessageFirst(config, own); + std::ranges::move(own, std::back_inserter(items)); + return items; + }; + } + // The chords the document's cell entries declare: a key that is none of them never asks for a cell's entries. + if (options.cellMenu) { + options.cellMenuKeys = chordsOf(node.partList("cellMenu")); + } + // A table with `configurable: false` has no menus, so neither the column chooser nor the sort dialog; with no + // column that filters, no dialog can open either, and the table is mounted alone. + if (!config.menus) { + return std::ranges::contains(*filterable, true) ? filterMenuDialog(menu) : nullptr; + } + // A header's menu ends with the document's `headerMenu` entries, read in a scope with `column`, the column's id. + if (std::span const parts = node.partList("headerMenu"); !parts.empty()) { + options.headerEntries = [this, ctx, &config, parts, columns](std::size_t column) { + auto bindings = std::make_shared(*ctx.bindings); + std::string const columnId = column < columns->size() ? columns->at(column).id : std::string{}; + bindings->push_back(Binding{.name = "column", .read = [columnId] { return Value{columnId}; }}); + std::vector own = menuItems( + parts, LowerCtx{.scope = ctx.scope, .bindings = std::move(bindings), .boundary = ctx.boundary}); + clearsMessageFirst(config, own); + return own; + }; + } + // The saved views. A view is fitted to the table as a stored state is, and the arrangement is the view's while its + // layout, laid over the table's columns, its sort and its filters are those fitted ones. + auto const fittedView = [&config](table::SavedView const& view) { + table::StateDocument document; + document.layout = view.layout; + document.sort = view.sort; + document.filters = view.filters; + if (std::optional const description = + config.description ? config.description() : std::nullopt) { + table::FitReport ignored; + document = table::fitState(std::move(document), *description, ignored); + } + return document; + }; + auto const arrangementNow = [this, &element, layoutHeld, filtersNow] { + return runtime().untracked([&] { + return table::SavedView{.name = {}, + .layout = layoutHeld().value(), + .sort = sortChainOf(tableSort(element)), + .filters = filtersNow()}; + }); + }; + auto const viewsInput = [&config, columns, hidden, fittedView, arrangementNow]() -> std::optional { + TableViews const* const views = config.views; + if (views == nullptr) { + return std::nullopt; + } + ViewsMenuInput input; + for (table::SavedView const& view : views->own().views) { + input.own.push_back(view.name); + } + for (table::SavedView const& view : views->shared().views) { + input.shared.push_back(view.name); + } + input.current = config.savedView; + input.currentShared = config.viewShared; + input.defaultOnMount = views->own().defaultOnMount; + input.shares = views->shares(); + table::SavedView const* const current = + !config.savedView ? nullptr + // NOLINTNEXTLINE(readability-avoid-nested-conditional-operator): a three-way pick: none, the shared view or the user's own view + : config.viewShared ? views->sharedView(*config.savedView) + : views->ownView(*config.savedView); + if (current != nullptr) { + table::StateDocument const view = fittedView(*current); + table::SavedView const now = arrangementNow(); + input.modified = layoutOver(*columns, *hidden, view.layout).value() != now.layout || + view.sort.value_or(SortChain{}) != now.sort || + view.filters.value_or(table::FilterSpec{}) != now.filters; + } + return input; + }; + // Records the view the arrangement was taken from in the table's state, and shows it at the table's points. + auto const recordView = [this, &config, &element](std::optional name, bool shared) { + config.savedView = std::move(name); + config.viewShared = shared && config.savedView.has_value(); + if (config.save) { + table::StateDocument changed; + changed.view = config.savedView; + config.save(changed, StateParts::View); + } + tablePoints(element); + }; + // Applying a view sets its layout, sort and filters as the gestures do, through their handlers where they are + // bound, and records its name. + auto const applyView = [this, &config, columns, hidden, fittedView, arrangementNow, relayout, resort, refilter, + recordView](table::SavedView const& saved, bool shared) { + auto const apply = [this, columns, hidden, fittedView, arrangementNow, relayout, resort, refilter, recordView, + saved, shared] { + table::StateDocument const view = fittedView(saved); + table::SavedView const now = arrangementNow(); + runtime().batch([&] { + if (view.layout && layoutOver(*columns, *hidden, view.layout).value() != now.layout) { + relayout(*view.layout); + } + SortChain const chain = view.sort.value_or(SortChain{}); + resort([&chain](SortChain const&) { return SortChange{.chain = chain, .refusal = {}}; }); + if (table::FilterSpec const filters = view.filters.value_or(table::FilterSpec{}); + filters != now.filters) { + static_cast(refilter(filters)); + } + recordView(saved.name, shared); + }); + }; + if (!config.prepare) { + apply(); + return; + } + // The rows take a filter on a column only once they have taken in its kind, which putting it in use gives + // them when they next flush their changes: the view is applied in a task after that. + config.prepare(table::StateDocument{.version = table::kStateVersion, + .layout = {}, + .sort = saved.sort, + .filters = saved.filters, + .view = {}, + .carried = {}}); + runtime().owner().post(config.viewsScope.token().guard(apply)); + }; + // A views change answers on the owner: its refusal goes to the status line, and what it did once done. + auto const changeViews = [&config](async::Completion completion, std::function done) { + completion.then(config.viewsScope, [&config, done = std::move(done)](TableViews::Result const& result) { + if (!result) { + config.message(result.error()); + return; + } + done(); + }); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks): the analyzer loses the owner of the callable `std::function` heap-allocates for this capture; the function object owns it and frees it + }; + auto const nameView = [&config, arrangementNow, recordView, changeViews] { + ViewDialog const dialog = config.viewDialog.peek(); + std::string name = dialog.name; + name.erase(0, name.find_first_not_of(" \t")); + name.erase(name.find_last_not_of(" \t") + 1); + TableViews* const views = config.views; + if (name.empty() || views == nullptr) { + return; + } + config.viewDialog.set(ViewDialog{}); + config.touch(); + table::SavedView view = arrangementNow(); + view.name = name; + switch (dialog.purpose) { + case ViewNaming::Save: { + // A name the user has, in the views stored when the save is applied, replaces that view. + changeViews(views->saveView(std::move(view)), [&config, recordView, name] { + recordView(name, false); + config.message("Saved view " + name); + }); + break; + } + case ViewNaming::Rename: { + if (!config.savedView || config.viewShared) { + return; + } + changeViews(views->change(table::RenameView{.from = *config.savedView, .to = name}), + [recordView, name] { recordView(name, false); }); + break; + } + case ViewNaming::Publish: { + // A name the shared views have, as stored when the publish is applied, replaces that view. + changeViews(views->publishView(std::move(view)), + [&config, name] { config.message("Published view " + name); }); + break; + } + default: + break; + } + }; + auto const viewCommand = [&config, applyView, recordView, changeViews](TableMenuEntry const& entry) { + TableViews* const views = config.views; + if (views == nullptr) { + return; + } + std::optional const current = config.viewShared ? std::nullopt : config.savedView; + auto const naming = [&config](ViewNaming purpose, std::string name) { + config.viewDialog.set(ViewDialog{.open = true, .purpose = purpose, .name = std::move(name)}); + }; + switch (entry.command) { + case MenuCommand::ApplyView: + if (table::SavedView const* const view = views->ownView(entry.argument)) { + applyView(table::SavedView{*view}, false); + } + break; + case MenuCommand::ApplySharedView: + if (table::SavedView const* const view = views->sharedView(entry.argument)) { + applyView(table::SavedView{*view}, true); + } + break; + case MenuCommand::SaveView: + naming(ViewNaming::Save, current.value_or(std::string{})); + break; + case MenuCommand::RenameView: + if (current) { + naming(ViewNaming::Rename, *current); + } + break; + case MenuCommand::PublishView: + naming(ViewNaming::Publish, config.savedView.value_or(std::string{})); + break; + case MenuCommand::RemoveView: + if (current) { + changeViews(views->change(table::RemoveView{*current}), + [recordView] { recordView(std::nullopt, false); }); + } + break; + case MenuCommand::SetDefaultView: + if (current) { + changeViews(views->change(table::SetDefaultView{current}), [] {}); + } + break; + case MenuCommand::DefaultOnMount: + changeViews(views->change(table::SetDefaultOnMount{!views->own().defaultOnMount}), [] {}); + break; + case MenuCommand::SaveAsMyView: + if (table::SavedView const* const view = views->sharedView(entry.argument)) { + std::string const name = view->name; + changeViews(views->change(table::AddView{*view}), [&config, recordView, name] { + recordView(name, false); + config.message("Saved view " + name); + }); + } + break; + case MenuCommand::SortAscending: + case MenuCommand::SortDescending: + case MenuCommand::AddToSort: + case MenuCommand::RemoveFromSort: + case MenuCommand::Filter: + case MenuCommand::FilterGroup: + case MenuCommand::MoveLeft: + case MenuCommand::MoveRight: + case MenuCommand::PinColumn: + case MenuCommand::UnpinColumn: + case MenuCommand::HideColumn: + case MenuCommand::DisplayUnit: + case MenuCommand::Columns: + case MenuCommand::SortDialog: + case MenuCommand::ClearAllFilters: + case MenuCommand::ResetColumns: + case MenuCommand::Copy: + case MenuCommand::CopyWithHeaders: + case MenuCommand::None: + default: + break; + } + }; + // A menu is built when it opens, and again when an entry is chosen, from the chain and the layout of the moment, + // so the path the backend reports names the entry it showed. + auto const entriesOf = [this, &config, &element, columns, sortable, filterable, layoutHeld, groupsNow, + groupArgument, filtersNow, + viewsInput](std::optional column) -> std::vector { + return runtime().untracked([&]() -> std::vector { + table::ColumnLayout const layout = layoutHeld(); + // The groups, each named in its members' menus and in the table's. + auto const groupsOf = [&](std::string_view columnId) { + std::vector out; + for (auto const& [group, formed] : groupsNow()) { + if (columnId.empty() || std::ranges::contains(group.columns, columnId)) { + out.push_back(MenuGroup{.id = groupArgument(group, formed), + .label = group.label, + .columns = group.columns.size()}); + } + } + return out; + }; + if (!column) { + return offeredEntries(tableMenu(TableMenuInput{.anyFilter = !filtersNow().empty(), + .groups = groupsOf({}), + .allowed = config.allowed, + .views = viewsInput()})); + } + if (*column >= columns->size()) { + return {}; + } + std::vector const visible = layout.visible(); + LayoutColumn const& index = columns->at(*column); + SortChain const chain = sortChainOf(tableSort(element)); + auto const held = std::ranges::find(chain, index.id, &table::SortKey::column); + std::vector dimensions = + config.dimensions ? config.dimensions(index.id) : std::vector{}; + table::ColumnLayoutValue const value = layout.value(); + if (auto const units = value.units.find(index.id); units != value.units.end()) { + for (MenuDimension& dimension : dimensions) { + if (auto const chosen = units->second.find(dimension.dimension); chosen != units->second.end()) { + dimension.chosen = chosen->second; + } + } + } + return offeredEntries(headerMenu(HeaderMenuInput{ + .column = index, + .sortable = sortable->at(*column), + .filterable = filterable->at(*column), + .sortPlace = + held == chain.end() ? std::nullopt : std::optional{static_cast(held - chain.begin())}, + .chainSize = chain.size(), + .maxSortKeys = config.maxSortKeys(), + .visibleIndex = static_cast(std::ranges::find(visible, index.id) - visible.begin()), + .visibleCount = visible.size(), + .pinned = layout.pinned(), + .dimensions = std::move(dimensions), + .groups = groupsOf(index.id), + .allowed = config.allowed, + })); + }); + }; + // While the header is disabled the table's menu offers copy alone; the mount greys a column's menu itself. + // NOLINTNEXTLINE(bugprone-exception-escape): copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + options.menu = [entriesOf, headerOn](std::optional column) { + std::vector entries = entriesOf(column); + if (!column && !headerOn()) { + for (TableMenuEntry& entry : entries) { + if (entry.command != MenuCommand::Copy && entry.command != MenuCommand::CopyWithHeaders) { + entry.entry.enabled = false; + } + } + } + return menuEntries(entries); + }; + // NOLINTNEXTLINE(bugprone-exception-escape): copying a `Prop` throws `bad_variant_access` only from a valueless source, which `copyOf` documents and nothing here builds + options.onMenu = [&config, &menu, entriesOf, sortBy, arrange, columns, openColumn, openGroup, refilter, copy, + headerOn, viewCommand](std::optional column, std::vector const& path) { + config.touch(); + std::vector const entries = entriesOf(column); + TableMenuEntry const* const entry = chosen(entries, path); + if (entry == nullptr) { + return; + } + // A menu opened while the header was enabled cannot sort, filter or arrange once it is not. + if (entry->command != MenuCommand::Copy && entry->command != MenuCommand::CopyWithHeaders && !headerOn()) { + config.message(std::string{tableText::kHeaderBusy}); + return; + } + std::size_t const index = column.value_or(columns->size()); + std::string const columnId = index < columns->size() ? columns->at(index).id : std::string{}; + switch (entry->command) { + case MenuCommand::SortAscending: + sortBy(index, SortGesture::Ascending); + break; + case MenuCommand::SortDescending: + sortBy(index, SortGesture::Descending); + break; + case MenuCommand::AddToSort: + sortBy(index, SortGesture::Add); + break; + case MenuCommand::RemoveFromSort: + sortBy(index, SortGesture::Remove); + break; + case MenuCommand::MoveLeft: + arrange(MoveColumn{.id = columnId, .by = -1}); + break; + case MenuCommand::MoveRight: + arrange(MoveColumn{.id = columnId, .by = 1}); + break; + case MenuCommand::PinColumn: + arrange(PinColumn{.id = columnId}); + break; + case MenuCommand::UnpinColumn: + arrange(UnpinColumn{.id = columnId}); + break; + case MenuCommand::HideColumn: + arrange(HideColumn{.id = columnId}); + break; + case MenuCommand::ResetColumns: + arrange(ResetColumns{}); + break; + case MenuCommand::Columns: + config.chooserOpen.set(true); + break; + case MenuCommand::SortDialog: + config.sortOpen.set(true); + break; + case MenuCommand::Filter: + if (!columnId.empty()) { + openColumn(columnId); + } + break; + case MenuCommand::FilterGroup: + openGroup(entry->argument); + break; + case MenuCommand::ClearAllFilters: + menu.close(); + static_cast(refilter(table::FilterSpec{})); + break; + case MenuCommand::DisplayUnit: { + // Choosing the checked unit clears it: the cells show their own units again. + std::size_t const cut = entry->argument.find('\x1F'); + if (cut != std::string::npos && !columnId.empty()) { + std::string const unit = entry->argument.substr(cut + 1); + arrange(SetDisplayUnit{.id = columnId, + .dimension = entry->argument.substr(0, cut), + .unit = entry->entry.checked == true ? std::nullopt : std::optional{unit}}); + } + break; + } + case MenuCommand::Copy: + copy(false); + break; + case MenuCommand::CopyWithHeaders: + copy(true); + break; + case MenuCommand::ApplyView: + case MenuCommand::SaveView: + case MenuCommand::RenameView: + case MenuCommand::RemoveView: + case MenuCommand::SetDefaultView: + case MenuCommand::DefaultOnMount: + case MenuCommand::ApplySharedView: + case MenuCommand::PublishView: + case MenuCommand::SaveAsMyView: + viewCommand(*entry); + break; + case MenuCommand::None: + default: + // `offeredEntries` offers no other entry. + break; + } + }; + // The column chooser and the sort dialog apply each change as it is made, through the gestures the header and + // the menus use; each change clears the status line's message first, as every gesture on the table does. + Node chooser = columnChooser(ColumnChooserView{ + .open = [&config] { return config.chooserOpen.get(); }, + .state = + [&config, columns, layoutHeld] { + static_cast(config.version.get()); + return chooserState(layoutHeld(), *columns, config.allowed); + }, + .draft = [&config] { return config.groupDraft.get(); }, + .setDraft = [&config](GroupDraft draft) { config.groupDraft.set(std::move(draft)); }, + .onShow = + [arrange](std::string const& columnId, bool shown) { + if (shown) { + arrange(ShowColumn{.id = columnId}); + } else { + arrange(HideColumn{.id = columnId}); + } + }, + .onMove = [arrange](std::string const& columnId, + int delta) { arrange(MoveColumn{.id = columnId, .by = delta}); }, + .onReset = [arrange] { arrange(ResetColumns{}); }, + .onFormGroup = + [this, arrange, layoutHeld](std::string label, std::vector members) { + std::size_t const before = runtime().untracked([&] { return layoutHeld().groups().size(); }); + arrange(FormGroup{.label = std::move(label), .columns = std::move(members)}); + return runtime().untracked([&] { return layoutHeld().groups().size(); }) > before; + }, + // A removed group takes its filter with it: the group filter that names the group's columns. + .onRemoveGroup = + [this, &config, &menu, arrange, layoutHeld, filtersNow, refilter](std::string const& columnId) { + std::vector members; + std::size_t const before = runtime().untracked([&] { + table::ColumnLayout const layout = layoutHeld(); + auto const group = std::ranges::find(layout.groups(), columnId, &table::ColumnGroupInfo::id); + if (group != layout.groups().end()) { + members = group->columns; + } + return layout.groups().size(); + }); + arrange(RemoveGroup{.id = columnId}); + if (runtime().untracked([&] { return layoutHeld().groups().size(); }) >= before) { + return; + } + FilterMenuState const& open = + runtime().untracked([&]() -> FilterMenuState const& { return menu.state(); }); + if (open.open && open.target.formed && open.target.columns == members) { + menu.close(); + } + table::FilterSpec spec = runtime().untracked(filtersNow); + auto const dropped = std::erase_if(spec.groups, [&](table::GroupFilter const& group) { + return group.group.empty() && group.columns == members; + }); + if (dropped > 0 && config.setFilters) { + static_cast(refilter(spec)); + } + }, + .onClose = + [&config] { + config.chooserOpen.set(false); + config.groupDraft.set(GroupDraft{}); + }, + }); + Node sorter = sortDialog(SortDialogView{ + .open = [&config] { return config.sortOpen.get(); }, + .chain = [&element] { return sortChainOf(tableSort(element)); }, + .sortable = + [columns, sortable] { + std::vector out; + for (std::size_t at = 0; at < columns->size(); ++at) { + if (sortable->at(at)) { + out.push_back(SortColumnOption{.id = columns->at(at).id, .label = columns->at(at).label}); + } + } + return out; + }, + .onEdit = + [&config, columns, sortable, resort](SortEdit const& edit) { + config.touch(); + std::vector ids; + for (std::size_t at = 0; at < columns->size(); ++at) { + if (sortable->at(at)) { + ids.push_back(columns->at(at).id); + } + } + resort( + [&](SortChain const& current) { return applySortEdit(current, ids, edit, config.maxSortKeys()); }); + }, + .onClose = [&config] { config.sortOpen.set(false); }, + }); + std::vector dialogs{std::move(chooser), std::move(sorter), filterMenuDialog(menu)}; + if (config.views != nullptr) { + dialogs.push_back(viewNameDialog(ViewNameDialogView{ + .open = [&config] { return config.viewDialog.get().open; }, + .title = + [&config] { + switch (config.viewDialog.get().purpose) { + case ViewNaming::Rename: + return std::string{"Rename view"}; + case ViewNaming::Publish: + return std::string{"Publish view"}; + case ViewNaming::Save: + default: + return std::string{"Save view"}; + } + }, + .name = [&config] { return config.viewDialog.get().name; }, + .onName = + [&config](std::string name) { + ViewDialog dialog = config.viewDialog.peek(); + dialog.name = std::move(name); + config.viewDialog.set(std::move(dialog)); + }, + .onSave = nameView, + .onClose = [&config] { config.viewDialog.set(ViewDialog{}); }, + })); + } + return ui::column(Column{.children = std::move(dialogs)}); +} + +Node ScreenCore::lowerModelTable(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + if (element == nullptr || element->modelTable == nullptr || element->modelTable->window == nullptr) { + return ui::text(Text{.text = std::string{"table"}, .role = TextRole::Muted}); + } + ModelTable& model = *element->modelTable; + // One row, keyed by the description's revision: a new revision mounts the table again, with the columns, levels + // and cells of that description, while the rows, their sort and filters, the selection and the message, which + // the element holds, stay. + Common placed; + commonOf(node, ctx, element, placed); + Common listCommon; + listCommon.layout = placed.layout; + Node list = ui::forEach([&model] { return std::vector{Value{model.revision.get()}}; }, + [](Value const& revision) -> Key { return Key{*revision.asString()}; }, + [this, ctx, &node, element](reactive::Signal const& revision) { + static_cast(revision); + return modelTableOf(node, ctx, *element); + }, + Axis::Vertical, 0, listCommon); + std::span const empty = node.nodes("empty"); + if (empty.empty()) { + return list; + } + // `empty` shows once a reply said the view has no row, exactly, and no row is undecided. + Column wrapper; + wrapper.common.layout = placed.layout; + wrapper.children.push_back(std::move(list)); + Column content{.children = {lowerAll(empty, ctx)}}; + content.common.visible = slotProp([&model] { + static_cast(model.version.get()); + TableCountsView const counts = model.rows->counts(); + return counts.view.known && counts.view.rows == 0 && counts.view.kind == table::TotalKind::Exact && + counts.undecided == 0; + }); + wrapper.children.push_back(ui::column(std::move(content))); + return ui::column(std::move(wrapper)); +} + +} // namespace morph::ui::detail diff --git a/src/ui/interpreter_table_model.cpp b/src/ui/interpreter_table_model.cpp new file mode 100644 index 000000000..b4b3e2bd2 --- /dev/null +++ b/src/ui/interpreter_table_model.cpp @@ -0,0 +1,1212 @@ +// SPDX-License-Identifier: Apache-2.0 + +// A model-backed table's lowering. + +#include "interpreter_grid_detail.hpp" + +namespace morph::ui::detail { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity, readability-function-size): the columns, the cells, the row's parts and the handlers; each stage hands the next the same element, options and config +Node ScreenCore::modelTableOf(DocNode const& node, LowerCtx const& ctx, ElementState& element) { + ModelTable& model = *element.modelTable; + TableOptions options; + commonOf(node, ctx, &element, options.common); + options.status = slotProp([&element, &model, scope = ctx.scope] { + static_cast(model.version.get()); + TableCountsView const counts = model.rows->counts(); + TableStatus status; + status.shown = model.statusShown; + SelectedCount const selected = model.rows->selectedCount(selectionNow(element)); + status.counts = countsText(counts, selected.rows, scope->formatting()); + if (selected.kind == CountKind::Approximate && selected.rows > 0 && counts.view.known && + counts.undecided == 0) { + auto const grouped = [&scope](std::int64_t number) { + return render::formatCanonicalNumber(std::to_string(number), scope->formatting().numeric); + }; + status.counts = "about " + grouped(selected.rows) + " of " + grouped(counts.view.rows) + + (counts.view.kind == table::TotalKind::AtLeast ? " or more" : "") + " selected"; + } + if (!counts.failed.empty()) { + status.state = levelWords(counts.failed.front()) + " data could not be loaded."; + status.retry = true; + } else if (auto const& error = model.window->error()) { + status.state = "The rows could not be loaded: " + error->message; + status.retry = true; + } else if (Value const failed = model.describe != nullptr ? model.describe->error() : Value{}; + failed.asString() != nullptr) { + status.state = "The table's description could not be loaded: " + *failed.asString(); + } + if (model.statusShown) { + status.message = model.message.get(); + status.entries = model.entries.get(); + } + // The standing states, in the order saving, failed, unmatched, joined by ". ". + static_cast(model.marksRevision.get()); + auto const grouped = [&scope](std::int64_t number) { + return render::formatCanonicalNumber(std::to_string(number), scope->formatting().numeric); + }; + auto const stand = [&status](std::string text) { + status.standing += (status.standing.empty() ? "" : ". ") + std::move(text); + }; + if (std::int64_t const busy = model.rows->states().busyCount(); busy > 0) { + stand("Saving " + grouped(busy) + (busy == 1 ? " row" : " rows")); + } + if (auto const failed = static_cast(model.rows->states().failedKeys().size()); failed > 0) { + stand(grouped(failed) + (failed == 1 ? " row could not be saved" : " rows could not be saved")); + status.standingEntries.push_back(StatusEntry{.id = std::string{kSelectFailed}, .label = "Select them"}); + status.standingEntries.push_back(StatusEntry{.id = std::string{kClearMarks}, .label = "Clear marks"}); + } + if (counts.retained > 0) { + stand(grouped(counts.retained) + + (counts.retained == 1 ? " row shown that no longer matches" : " rows shown that no longer match")); + status.standingEntries.push_back( + StatusEntry{.id = std::string{kShowMatching}, .label = "Show only matching rows"}); + } + return status; + }); + options.onStatusEntry = [this, &element, &model](std::string const& entryId) { + // "Select them" makes the failed rows the selection; "Clear marks" drops their marks. + if (entryId == kSelectFailed || entryId == kClearMarks) { + tableGesture(element); + runtime().batch([&] { + if (entryId == kSelectFailed) { + std::vector const failed = model.rows->states().failedKeys(); + model.viewSelection.set(std::nullopt); + if (model.config.selectKeys) { + model.config.selectKeys(failed); + } + } else { + model.rows->states().clearFailed(); + } + model.marksRevision.set(model.marksRevision.peek() + 1); + }); + return; + } + // "Show only matching rows": the retained rows go, and with them a selection of the view, which named them. + if (entryId == kShowMatching) { + tableGesture(element); + runtime().batch([&] { + model.rows->clearRetained(); + model.marksRevision.set(model.marksRevision.peek() + 1); + if (model.viewSelection.peek()) { + model.viewSelection.set(std::nullopt); + if (element.bound == nullptr) { + session.asUser([&] { + session.noteWrite(); + element.selection.set(Value{ValueList{}}); + }); + } + } + }); + return; + } + auto const found = model.entryHandlers.find(entryId); + if (found == model.entryHandlers.end()) { + return; + } + // Taken before the message is cleared, which drops the handlers. + std::function const chosen = found->second; + tableMessage(element, {}); + chosen(); + }; + options.onRetry = [this, &element, &model] { + tableGesture(element); + model.window->retry(); + }; + table::TableDescription const* const description = model.window->description(); + if (description == nullptr) { + // Before the description, and after one that does not read: the status line alone. + Table spec; + spec.status = std::move(options.status); + spec.onRetry = std::move(options.onRetry); + spec.common = std::move(options.common); + return makeNode(std::move(spec)); + } + FormatContext const& format = ctx.scope->formatting(); + Align const tableValign = cellPlaceNamed(node.name("valign")).value_or(Align::Center); + auto const describedColumn = [description](std::string_view columnId) -> table::TableColumn const* { + auto const found = + std::ranges::find(description->columns, columnId, + [](table::TableColumn const& column) -> auto const& { return column.info.id; }); + return found == description->columns.end() ? nullptr : &*found; + }; + std::vector columns; + std::vector parts; + std::vector roles; + TableSource source; + // Each shown column as it shows its cells: the description's display under the part's display parts. + auto const shown = std::make_shared>(); + auto const displayUnits = std::make_shared>(); + auto const cellExprs = std::make_shared>(); + std::shared_ptr registry; + if (auto made = table::registryOf(*description)) { + registry = std::move(*made); + } else { + report(node.path, "the units of `" + model.id + "` do not read: " + made.error().message); + } + std::vector const companions = table::companionColumns(*description); + table::CompanionOverrides overrides{.tone = {}, .tooltip = {}, .rowTone = node.prop("rowTone") != nullptr}; + // NOLINTNEXTLINE(readability-function-cognitive-complexity): adds one described column: its kind, layout, display, filter and edit parts each read the same part and description + auto const add = [&](table::TableColumn const& described, DocNode const* part) { + TableColumn column{.id = described.info.id, + .label = described.label.empty() ? described.info.id : described.label, + .valign = tableValign, + .sortable = described.sortable}; + table::TableColumn display = described; + CellExprs exprs{.tone = nullptr, .tooltip = nullptr, .path = part != nullptr ? part->path : node.path}; + if (part != nullptr) { + display.display = + displayOf(*part, described.display, [&](ExprPtr const& expr) { return once(ctx, expr); }); + if (described.info.kind == table::ColumnKind::Measure && + (display.display.decimals || !display.display.unit.empty())) { + report(part->path, "`" + described.info.id + + "` is a measure column, which shows each cell in its own unit; `decimals` " + "and `unit` do not apply"); + display.display.decimals.reset(); + display.display.unit.clear(); + } + exprs.tone = part->prop("tone"); + exprs.tooltip = part->prop("tooltip"); + if (exprs.tone) { + overrides.tone.insert(described.info.id); + } + if (exprs.tooltip) { + overrides.tooltip.insert(described.info.id); + } + } + column.unit = display.display.unit; + DisplayUnits units{.units = registry.get(), .byDimension = {}}; + if (model.config.held) { + if (auto const chosen = model.config.held->units.find(described.info.id); + chosen != model.config.held->units.end()) { + units.byDimension.insert(chosen->second.begin(), chosen->second.end()); + } + } + shown->push_back(std::move(display)); + displayUnits->push_back(std::move(units)); + cellExprs->push_back(std::move(exprs)); + TextRole role = TextRole::Normal; + if (part != nullptr) { + if (ExprPtr const label = part->prop("label")) { + column.label = textOf(once(ctx, label), format); + } + if (ExprPtr const width = part->prop("width")) { + column.width = sizingOf(once(ctx, width)); + } + if (ExprPtr const named = part->prop("role")) { + Value const value = once(ctx, named); + std::optional const found = roleNamed(textOf(value, format)); + if (!found) { + report(named->path, "role is " + canonicalJson(value) + "; " + std::string{kRoleNames}); + } + role = found.value_or(TextRole::Normal); + } + column.role = role; + column.align = cellPlaceNamed(part->name("align")).value_or(Align::Start); + column.valign = cellPlaceNamed(part->name("valign")).value_or(tableValign); + column.wrap = part->flag("wrap", true); + column.shrink = part->flag("shrink") && column.width.kind == Sizing::Kind::Stretch; + } + // A measure's amounts line up on their digits, as an `end` column's do. + if (described.info.kind == table::ColumnKind::Measure && (part == nullptr || part->name("align").empty())) { + column.align = Align::End; + } + columns.push_back(std::move(column)); + parts.push_back(part); + roles.push_back(role); + source.levels.push_back(described.info.level); + }; + // A companion column (a tone, a tooltip, a row's tone or lock) is never shown: it travels with its column. + if (auto const laidOut = node.partList("columns"); !laidOut.empty()) { + for (DocNodePtr const& part : laidOut) { + if (std::ranges::binary_search(companions, part->id)) { + report(part->path, "`" + part->id + "` is a companion column of `" + model.id + "`; it is not shown"); + } else if (table::TableColumn const* const described = describedColumn(part->id)) { + add(*described, part.get()); + } else { + report(part->path, "the table `" + model.id + "` has no column `" + part->id + "`"); + } + } + } else { + // A column the description does not show is a column too, hidden by the layout until its user shows it. + for (table::TableColumn const& described : description->columns) { + if (!std::ranges::binary_search(companions, described.info.id)) { + add(described, nullptr); + } + } + } + // What the row's own parts and the cells read of the row is fetched with every page: the key, each field named, + // and every column when one of them passes the row on whole. + RowReads reads; + reads.ids.insert(description->key); + for (std::string_view const key : {"rowTone", "rowLabel"}) { + if (ExprPtr const expr = node.prop(key)) { + rowReadsOf(*expr, reads); + } + } + if (Commands const* const activate = node.event("onActivate")) { + rowReadsOf(*activate, reads); + } + // A cell menu's entries act on any row, so what they read is fetched with every row, as the row's tone is. + for (DocNodePtr const& entry : node.partList("cellMenu")) { + rowReadsOf(*entry, reads); + } + // A column's own reads are fetched while the column is in the window; one that passes the row on whole makes + // every column always fetched. + std::vector partReads(parts.size()); + for (std::size_t at = 0; at < parts.size(); ++at) { + if (parts.at(at) != nullptr) { + rowReadsOf(*parts.at(at), partReads.at(at)); + reads.whole = reads.whole || partReads.at(at).whole; + } + } + if (reads.whole) { + report(node.path, "the table reads its row whole; every column of `" + model.id + "` is fetched"); + for (table::TableColumn const& column : description->columns) { + reads.ids.insert(column.info.id); + } + } + for (std::string const& columnId : reads.ids) { + if (model.described.contains(columnId)) { + source.alwaysFetched.push_back(columnId); + } + } + std::vector ids; + ids.reserve(columns.size()); + for (TableColumn const& column : columns) { + ids.push_back(column.id); + } + source.cellReads.resize(parts.size()); + source.ownCell.resize(parts.size(), false); + for (std::size_t at = 0; at < parts.size(); ++at) { + for (std::string const& columnId : partReads.at(at).ids) { + if (columnId != ids.at(at) && model.described.contains(columnId) && + !std::ranges::contains(source.alwaysFetched, columnId)) { + source.cellReads.at(at).push_back(columnId); + } + } + source.ownCell.at(at) = parts.at(at) != nullptr && !parts.at(at)->nodes("cell").empty(); + } + // The companions travel with their column: the query names them beside the columns the mount names. + model.rows->companions([described = std::make_shared(*description), + overrides](std::span named) { + return table::columnsWithCompanions(*described, named, overrides); + }); + // A cell's text, by its column's display. Each column's `DisplayUnits` points into `registry`, so the formatters + // hold it: it lives as long as the cells do. + auto const textOfCell = [shown, displayUnits, registry](std::size_t column, Value const& record, + FormatContext const& formatting) { + table::TableColumn const& display = shown->at(column); + DisplayUnits const& units = displayUnits->at(column); + return formatCell(cellOfRecord(record.field(display.info.id), display, units.units), display, formatting, + units); + }; + // A cell's accent: the document's tone and tooltip, else its companions'; an unreadable value is invalid. An + // unknown tone is reported once per column. + auto const cellToneReported = std::make_shared>(); + auto const accentOf = [this, shown, displayUnits, registry, cellExprs, cellToneReported, bindings = ctx.bindings]( + std::size_t column, Value const& record, RtScope const* scope) { + table::TableColumn const& display = shown->at(column); + CellExprs const& exprs = cellExprs->at(column); + auto const toneOf = [&](Value const& named) -> std::optional { + if (named.isNull() || (named.asString() != nullptr && named.asString()->empty())) { + return std::nullopt; + } + if (std::optional const tone = toneNamed(named)) { + return tone; + } + if (cellToneReported->insert(column).second) { + report(exprs.path, "column `" + display.info.id + "`'s tone is " + canonicalJson(named) + + "; a tone is neutral, info, ok, warn or err"); + } + return std::nullopt; + }; + CellAccent accent; + if (exprs.tone && scope != nullptr) { + accent.tone = toneOf(evalIn(*scope, bindings.get(), exprs.tone)); + } else if (Value const* const named = display.tone.empty() ? nullptr : record.field(display.tone)) { + accent.tone = toneOf(*named); + } + if (exprs.tooltip && scope != nullptr) { + Value const tip = evalIn(*scope, bindings.get(), exprs.tooltip); + accent.tooltip = tip.isNull() ? std::string{} : textOf(tip, scope->formatting()); + } else if (Value const* const tip = display.tooltip.empty() ? nullptr : record.field(display.tooltip)) { + accent.tooltip = tip->asString() != nullptr ? *tip->asString() : std::string{}; + } + DisplayUnits const& units = displayUnits->at(column); + if (cellLook(cellOfRecord(record.field(display.info.id), display, units.units), display, units) == + CellLook::Invalid) { + accent.invalid = true; + accent.tooltip = std::string{kUnreadable}; + } + return accent; + }; + bool const cellExprsGiven = std::ranges::any_of( + *cellExprs, [](CellExprs const& exprs) { return exprs.tone != nullptr || exprs.tooltip != nullptr; }); + // The row scope a cell's own tone and tooltip expressions read; none when no column gives one. + auto const exprScope = [this, ctx, &node, &model](reactive::Signal const& row) { + std::string key = runtime().untracked([&] { + Value const* const rowKey = row.peek().field(model.keyColumn); + return rowKey == nullptr ? std::string{} : canonicalJson(*rowKey); + }); + auto const scope = rowScope(node, ctx, row, {}, std::move(key)); + scope->onMissingRowField = &model.onMissing; + scope->rowKeyNow = [&row, &model] { + Value const* const rowKey = row.get().field(model.keyColumn); + return rowKey == nullptr ? std::string{} : canonicalJson(*rowKey); + }; + return scope; + }; + // The default cell follows the column the mount gives it, so one cell serves every column of its role. + source.defaultCellView = [this, scope = ctx.scope, roles, textOfCell, accentOf, cellExprsGiven, exprScope]( + reactive::Signal const& column, + reactive::Signal const& row) -> Node { + std::shared_ptr const cellScope = cellExprsGiven ? exprScope(row) : nullptr; + Node text = ui::text(Text{ + .text = slotProp([scope, &row, &column, textOfCell] { + return textOfCell(column.get(), row.get(), scope->formatting()); + }), + // Read once: the mount pools default cells by role, so a cell only ever moves to a column of its own role. + .role = roles.at(column.peek()), + }); + return accentedCell(std::move(text), slotProp([&row, &column, accentOf, cellScope] { + return accentOf(column.get(), row.get(), cellScope.get()); + })); + }; + source.rows = model.rows; + // The cells' drafts, once an editable table's grid is made below: a plain cell shows its draft while one is held. + auto const drafts = std::make_shared>(); + source.cellView = [this, ctx, &node, &model, parts, roles, textOfCell, accentOf, cellExprs, exprScope, drafts, + shown](std::size_t column, reactive::Signal const& row) -> Node { + DocNode const* const part = column < parts.size() ? parts.at(column) : nullptr; + std::span const cell = part != nullptr ? part->nodes("cell") : std::span{}; + if (!cell.empty()) { + std::vector content; + for (DocNodePtr const& child : cell) { + content.push_back(child.get()); + } + std::string key = runtime().untracked([&] { + Value const* const rowKey = row.peek().field(model.keyColumn); + return rowKey == nullptr ? std::string{} : canonicalJson(*rowKey); + }); + auto const scope = rowScope(node, ctx, row, content, std::move(key)); + scope->onMissingRowField = &model.onMissing; + // The mount rebinds a pooled cell to other rows by its signal: the row its elements are keyed by is the + // one the signal holds now. + scope->rowKeyNow = [&row, &model] { + Value const* const rowKey = row.get().field(model.keyColumn); + return rowKey == nullptr ? std::string{} : canonicalJson(*rowKey); + }; + LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; + // The cell owns its scope for as long as its node lives. + auto const owner = + std::make_shared> const>(lowerAll(cell, rowCtx), scope); + return accentedCell(Node{owner, owner->first.get()}, slotProp([&row, column, accentOf, scope] { + return accentOf(column, row.get(), scope.get()); + })); + } + CellExprs const& exprs = cellExprs->at(column); + std::shared_ptr const cellScope = + exprs.tone != nullptr || exprs.tooltip != nullptr ? exprScope(row) : nullptr; + Node text = ui::text(Text{ + .text = slotProp([scope = ctx.scope, &row, &model, column, textOfCell, drafts, shown] { + if (std::shared_ptr const grid = drafts->lock()) { + if (Value const* const rowKey = row.get().field(model.keyColumn); rowKey != nullptr) { + if (std::optional held = + grid->heldText(keyOf(*rowKey), shown->at(column).info.id)) { + return std::move(*held); + } + } + } + return textOfCell(column, row.get(), scope->formatting()); + }), + .role = roles.at(column), + }); + return accentedCell(std::move(text), slotProp([&row, column, accentOf, cellScope] { + return accentOf(column, row.get(), cellScope.get()); + })); + }; + ExprPtr const toneExpr = node.prop("rowTone"); + ExprPtr const labelExpr = node.prop("rowLabel"); + Commands const* const activateCommands = node.event("onActivate"); + // Every row of a model's table has a look: its marks and its tone say whether an action works on it, failed on it + // or kept it in view, and whether it is locked. + { + auto const toneReported = std::make_shared(false); + source.rowView = [this, ctx, &node, &model, toneExpr, labelExpr, + toneReported](reactive::Signal const& row) { + std::string key = runtime().untracked([&] { + Value const* const rowKey = row.peek().field(model.keyColumn); + return rowKey == nullptr ? std::string{} : canonicalJson(*rowKey); + }); + auto const scope = rowScope(node, ctx, row, {}, key); + scope->onMissingRowField = &model.onMissing; + // A row that left the realized window released its scope; its entry goes when the next row comes, so the + // index holds the realized rows and those that left since. + std::erase_if(model.rowScopes, [](auto const& entry) { return entry.second.expired(); }); + model.rowScopes[std::move(key)] = scope; + LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; + TableRowLook look; + look.keep = scope; + if (labelExpr) { + look.label = bindProp(rowCtx, labelExpr, std::string{}, stringOf); + } + std::optional const rowKey = runtime().untracked([&]() -> std::optional { + Value const* const keyValue = row.peek().field(model.keyColumn); + return keyValue == nullptr ? std::nullopt : std::optional{keyOf(*keyValue)}; + }); + // A locked row's tooltip is why it is locked; else a failed row's is its message, else an unmatched row + // says so. + look.marks = slotProp([&model, &row, rowKey] { + static_cast(model.marksRevision.get()); + RowMarks marks; + if (!rowKey) { + return marks; + } + Value const& record = row.get(); + table::TableDescription const* const rowDescription = model.window->description(); + std::optional const locked = + rowDescription == nullptr ? std::nullopt + : lockText(TableRowRef{.key = *rowKey, .row = record}, *rowDescription); + RowStates const& states = model.rows->states(); + marks.busy = states.isBusy(*rowKey); + marks.locked = locked.has_value(); + marks.unmatched = model.rows->unmatched(*rowKey); + if (locked) { + marks.tooltip = *locked; + } else if (std::optional failure = states.failure(*rowKey)) { + marks.tooltip = std::move(*failure); + } else if (marks.unmatched) { + marks.tooltip = "This row no longer matches the filter"; + } + return marks; + }); + // A failed row draws `err`; else the row's own tone. + look.tone = slotProp>( + [this, &model, rowKey, scope, bindings = ctx.bindings, toneExpr, toneReported] -> std::optional { + static_cast(model.marksRevision.get()); + if (rowKey && model.rows->states().failure(*rowKey)) { + return Tone::Err; + } + if (!toneExpr) { + return std::nullopt; + } + return rowToneOf(evalIn(*scope, bindings.get(), toneExpr), toneExpr->path, *toneReported); + }); + return look; + }; + } + options.showHeader = node.flag("showHeader", true); + // The document's bands, else the description's; bands that cannot be drawn over the description's columns are + // reported and none is drawn. + options.bands = node.partList("bands").empty() ? description->bands : bandsOf(node.partList("bands")); + if (!options.bands.empty()) { + std::vector described; + described.reserve(description->columns.size()); + for (table::TableColumn const& column : description->columns) { + described.push_back(column.info.id); + } + if (std::optional const refused = table::bandRefusal(options.bands, described)) { + report(pointerAppend(node.path, "bands"), *refused); + options.bands.clear(); + } + } + options.selectColumn = node.flag("selectColumn"); + if (ExprPtr const selectAll = node.prop("selectAllLabel")) { + options.selectAllLabel = bindProp(ctx, selectAll, std::string{}, stringOf); + } + if (ExprPtr const overscan = node.prop("virtualizeOverscan")) { + options.virtualize.overscan = + static_cast(std::max(0, intOf(once(ctx, overscan), 10))); + } + std::string const mode = + node.prop("selectionMode") ? textOf(once(ctx, node.prop("selectionMode")), format) : std::string{}; + options.selectionMode = + mode == "single" ? SelectionMode::Single + // NOLINTNEXTLINE(readability-avoid-nested-conditional-operator): a three-way map of the mode text to the enum + : mode == "multiple" ? SelectionMode::Multiple + : SelectionMode::None; + options.selection = slotProp>([&element] { + std::vector keys; + if (Value const itemsValue = tableSelection(element); ValueList const* const items = itemsValue.asList()) { + for (Value const& item : *items) { + keys.push_back(keyOf(item)); + } + } + return keys; + }); + // The selection the user made: held by the element unless the document binds it, then the command list. + auto const selectRows = [this, ctx, &element, + commands = node.event("onSelectionChange")](std::vector const& keys) { + ValueList items; + for (Key const& key : keys) { + items.push_back(valueOfKey(key)); + } + Value const selected{std::move(items)}; + runtime().batch([&] { + if (element.bound == nullptr) { + session.asUser([&] { + session.noteWrite(); + element.selection.set(selected); + }); + } + runEvent(commands, ctx, selected); + }); + }; + // Held by the table's handlers; a range's reply, which may come after the table is gone, holds it weakly, so it + // keeps no scope of the screen alive. + auto const select = std::make_shared const&)>>(selectRows); + // While the selection is of the view, the backend marks every row but `except`. A `Ctrl`+click reports the keys + // now selected among the rows it holds: each held key absent from the report is left out, each present one is + // selected again. A plain click ends the selection of the view. + options.keyMoves = slotProp([&model] { return model.keyMoves.get(); }); + options.selectionView = slotProp>>([&model]() -> std::optional> { + auto const& view = model.viewSelection.get(); + if (!view) { + return std::nullopt; + } + return std::vector(view->except.begin(), view->except.end()); + }); + options.onSelectionChange = [this, &element, &model, select](std::vector const& keys, + SelectionChange change) { + tableGesture(element); + std::optional const viewing = model.viewSelection.peek(); + if (viewing && change == SelectionChange::Extend) { + std::unordered_set const inReport(keys.begin(), keys.end()); + TableSelection next = *viewing; + // The rows the backend holds are those the mount named in or near view; a held row outside them is not + // in the report, and is not read as left out. + auto const [first, count] = model.rows->shownRange(); + for (std::int64_t at = first; at < first + count; ++at) { + std::optional const row = model.rows->row(at); + if (!row) { + continue; + } + if (inReport.contains(row->key)) { + std::erase(next.except, row->key); + } else if (!std::ranges::contains(next.except, row->key)) { + next.except.push_back(row->key); + } + } + model.viewSelection.set(std::move(next)); + return; + } + runtime().batch([&] { + if (viewing) { + model.viewSelection.set(std::nullopt); + } + (*select)(keys); + }); + }; + // Select-all on a table that may select many rows selects the view: no row is fetched, and the server resolves + // it when an action runs. Refused while the view's membership is open. + if (options.selectionMode == SelectionMode::Multiple) { + options.onSelectAll = [this, ctx, &element, &model] { + tableGesture(element); + auto view = model.rows->selectView(); + if (!view) { + tableMessage(element, selectAllRefusalText(view.error(), ctx.scope->formatting())); + return; + } + runtime().batch([&] { + model.viewSelection.set(TableSelection{.keys = {}, .view = std::move(*view), .except = {}}); + if (element.bound == nullptr) { + session.asUser([&] { + session.noteWrite(); + element.selection.set(Value{ValueList{}}); + }); + } + }); + }; + } + // A range the backend reports as view rows: its keys come from the rows, fetched as pages of keys alone where the + // window does not hold them, and select as the gesture says. Past `maxRangeRows` it is refused and selects + // nothing. + // NOLINTNEXTLINE(readability-function-cognitive-complexity): resolves a reported range to keys, fetching pages of keys where the window lacks them, and applies the gesture; the paths share the range state + options.onSelectRange = [this, ctx, &element, &model, select](std::size_t anchor, std::size_t focus, + SelectionChange change) { + tableGesture(element); + std::size_t const first = std::min(anchor, focus); + std::size_t const count = std::max(anchor, focus) - first + 1; + std::size_t const bound = session.options().maxRangeRows; + if (count > bound) { + tableMessage(element, + "A range selects at most " + + render::formatCanonicalNumber(std::to_string(bound), ctx.scope->formatting().numeric) + + " rows"); + return; + } + // In a selection of the view a range changes `except`: from an anchor left out it leaves the range out, + // from a selected anchor it selects the range again. + if (std::optional const viewing = model.viewSelection.peek()) { + std::optional const anchorRow = model.rows->row(static_cast(anchor)); + bool const leaving = anchorRow && std::ranges::contains(viewing->except, anchorRow->key); + model.rows->keysOf(static_cast(first), static_cast(count)) + .then(model.scope, [this, &element, &model, leaving]( + std::expected, table::TableError> const& found) { + if (!found) { + tableMessage(element, "The range could not be selected: " + found.error().message); + return; + } + std::optional next = model.viewSelection.peek(); + if (!next) { + return; + } + for (table::RowId const& key : *found) { + if (!leaving) { + std::erase(next->except, key); + } else if (!std::ranges::contains(next->except, key)) { + next->except.push_back(key); + } + } + model.viewSelection.set(std::move(next)); + }); + return; + } + model.rows->keysOf(static_cast(first), static_cast(count)) + .then(model.scope, [this, &element, select = std::weak_ptr{select}, + change](std::expected, table::TableError> const& found) { + if (!found) { + tableMessage(element, "The range could not be selected: " + found.error().message); + return; + } + std::vector keys; + if (change == SelectionChange::Extend) { + if (Value const heldValue = tableSelection(element); + ValueList const* const held = heldValue.asList()) { + for (Value const& item : *held) { + keys.push_back(keyOf(item)); + } + } + } + for (table::RowId const& rowId : *found) { + Key const key = std::visit([](auto const& value) { return Key{value}; }, rowId); + if (!std::ranges::contains(keys, key)) { + keys.push_back(key); + } + } + if (auto const live = select.lock()) { + (*live)(keys); + } + }); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks): the analyzer loses the owner of the callable `std::function` heap-allocates for this capture; the function object owns it and frees it + }; + options.highlight = slotProp>([&model] { return model.highlight.get(); }); + // The header's sort chain and menus, and the columns' arrangement; the column chooser and the sort dialog. + // A column's filter menu shows its values as the column shows its cells, and reads a measure's operand with the + // description's units. + { + auto const described = std::make_shared(*description); + auto const labels = std::make_shared>(); + auto const refused = std::make_shared>(); + for (std::size_t at = 0; at < columns.size(); ++at) { + labels->push_back(columns.at(at).label); + refused->push_back(parts.at(at) != nullptr && !parts.at(at)->flag("filterable", true)); + } + auto const unitsOf = [described](table::TableColumn const& column) { + std::vector dimensions = column.info.dimensions; + if (dimensions.empty()) { + for (table::UnitInfo const& unit : described->units) { + if (!std::ranges::contains(dimensions, unit.dimension)) { + dimensions.push_back(unit.dimension); + } + } + } + std::vector out; + for (std::string const& dimension : dimensions) { + MenuDimension entry{.dimension = dimension, .units = {}, .chosen = {}}; + for (table::UnitInfo const& unit : described->units) { + if (unit.dimension == dimension) { + entry.units.push_back(unit.id); + } + } + if (!entry.units.empty()) { + out.push_back(std::move(entry)); + } + } + return out; + }; + bool const listed = described->capabilities.distinct && node.name("action").empty(); + model.config.beginMount(); + model.config.filterTarget = [shown, displayUnits, registry, described, labels, refused, unitsOf, + listed](std::string const& columnId) -> std::optional { + auto const found = std::ranges::find_if( + *shown, [&columnId](table::TableColumn const& column) { return column.info.id == columnId; }); + if (found == shown->end() || !found->filterable) { + return std::nullopt; + } + auto const index = static_cast(found - shown->begin()); + if (refused->at(index)) { + return std::nullopt; + } + FilterTarget target; + target.column = columnId; + target.label = labels->at(index); + target.shown = *found; + target.units = displayUnits->at(index); + target.unitList = described->units; + if (found->info.kind == table::ColumnKind::Measure) { + for (MenuDimension const& dimension : unitsOf(*found)) { + target.unitChoices.insert(target.unitChoices.end(), dimension.units.begin(), + dimension.units.end()); + } + } + target.listed = listed; + target.keep = registry; + return target; + }; + // A cell a menu opens on: unloaded while its row holds no field for it or its level has not loaded. + model.config.heldCell = [&model, shown, displayUnits, registry]( + Key const& key, std::string const& columnId) -> std::optional { + auto const found = std::ranges::find_if( + *shown, [&columnId](table::TableColumn const& column) { return column.info.id == columnId; }); + if (found == shown->end()) { + return std::nullopt; + } + auto const place = static_cast(found - shown->begin()); + for (auto const& [first, count] : model.window->heldRanges()) { + for (std::int64_t at = first; at < first + count; ++at) { + std::optional const ref = model.rows->row(at); + if (!ref || ref->key != key) { + continue; + } + Value const* const field = ref->row.field(columnId); + table::UnloadedLevels const levels = model.rows->unloadedLevels(at); + bool const unloaded = + field == nullptr || + (!found->info.level.empty() && std::ranges::contains(levels.levels, found->info.level)); + return HeldCell{.record = ref->row, + .cell = unloaded ? table::Cell{table::Unloaded{}} + : cellOfRecord(field, *found, registry.get()), + .shown = *found, + .units = displayUnits->at(place), + .keep = registry}; + } + } + return std::nullopt; + }; + model.config.dimensions = [shown, unitsOf](std::string const& unitId) { + auto const found = std::ranges::find_if( + *shown, [&unitId](table::TableColumn const& column) { return column.info.id == unitId; }); + return found == shown->end() || found->info.kind != table::ColumnKind::Measure + ? std::vector{} + : unitsOf(*found); + }; + } + // A copy reads the rows the window holds and fetches the others by key, naming the columns copied; each cell + // is written as the column shows it, in its display unit, and each header with its unit. A column's own `cell` + // is not copied: its value's text is. + auto const headers = std::make_shared>(); + for (TableColumn const& column : columns) { + headers->push_back(headerText(column.label, column.unit)); + } + model.config.selectKeys = [select](std::vector const& keys) { (*select)(keys); }; + model.config.viewSelected = [&model]() -> std::optional { + auto const& view = model.viewSelection.peek(); + if (!view) { + return std::nullopt; + } + return model.rows->selectedCount(*view).rows; + }; + // A selection of the view is copied from page queries of the view's rows naming the columns copied, in view + // order, its `except` left out. + model.config.gatherView = [&model, shown, displayUnits, registry, headers, scope = ctx.scope]( + std::vector const& columnIds, CopyDone const& done) { + std::vector places; + std::vector named; + CopyGathered gathered; + for (std::string const& columnId : columnIds) { + auto const found = std::ranges::find_if( + *shown, [&columnId](table::TableColumn const& column) { return column.info.id == columnId; }); + if (found != shown->end()) { + places.push_back(static_cast(found - shown->begin())); + named.push_back(columnId); + gathered.headers.push_back(headers->at(places.back())); + } + } + std::optional const view = model.viewSelection.peek(); + if (!view) { + done(std::move(gathered)); + return; + } + std::unordered_set const except(view->except.begin(), view->except.end()); + FormatContext const formatting = scope->formatting(); + model.rows->rowsOf(0, model.rows->total().rows, named) + .then(model.scope, + [shown, displayUnits, registry, places, formatting, except, done, gathered = std::move(gathered)]( + std::expected, table::TableError> const& found) mutable { + if (!found) { + done(std::unexpected("The rows could not be copied: " + found.error().message)); + return; + } + for (FetchedRow const& fetchedRow : *found) { + if (except.contains(fetchedRow.key)) { + continue; + } + CopyRow row{.viewRow = fetchedRow.viewRow, .cells = {}}; + for (std::size_t column = 0; column < places.size() && column < fetchedRow.cells.size(); + ++column) { + table::Cell const& cell = fetchedRow.cells.at(column); + std::size_t const place = places.at(column); + row.cells.push_back(std::holds_alternative(cell) + ? std::nullopt + : std::optional{formatCell(cell, shown->at(place), formatting, + displayUnits->at(place))}); + } + gathered.rows.push_back(std::move(row)); + } + done(std::move(gathered)); + }); + }; + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the gather of a model table: it formats each row's cells by the visible columns with the units, registry and places; the steps share those + model.config.gather = [&model, shown, displayUnits, registry, headers, textOfCell, scope = ctx.scope]( + std::vector keys, std::vector const& columnIds, CopyDone const& done) { + std::vector places; + std::vector named; + CopyGathered gathered; + for (std::string const& columnId : columnIds) { + auto const found = std::ranges::find_if( + *shown, [&columnId](table::TableColumn const& column) { return column.info.id == columnId; }); + if (found != shown->end()) { + places.push_back(static_cast(found - shown->begin())); + named.push_back(columnId); + gathered.headers.push_back(headers->at(places.back())); + } + } + FormatContext const formatting = scope->formatting(); + std::unordered_set wanted{keys.begin(), keys.end()}; + // The rows held with every column copied; a row held without one of them is fetched with the rest. + TableRows const& rows = *model.rows; + std::vector held; + for (auto const& [first, count] : model.window->heldRanges()) { + for (std::int64_t at = first; at < first + count; ++at) { + held.push_back(at); + } + } + for (std::int64_t const index : held) { + if (wanted.empty()) { + break; + } + std::optional const ref = rows.row(index); + if (!ref || !wanted.contains(ref->key) || !std::ranges::all_of(named, [&](std::string const& columnId) { + return ref->row.field(columnId) != nullptr; + })) { + continue; + } + std::span const unloaded = rows.unloadedLevels(index).levels; + CopyRow row{.viewRow = index, .cells = {}}; + for (std::size_t const place : places) { + std::string const& level = shown->at(place).info.level; + bool const missing = !level.empty() && std::ranges::contains(unloaded, level); + row.cells.push_back(missing ? std::nullopt : std::optional{textOfCell(place, ref->row, formatting)}); + } + gathered.rows.push_back(std::move(row)); + wanted.erase(ref->key); + } + if (wanted.empty()) { + done(std::move(gathered)); + return; + } + std::vector fetched; + for (Key const& key : keys) { + if (wanted.erase(key) != 0) { + fetched.push_back(key); + } + } + model.rows->fetchRows(std::move(fetched), std::move(named)) + .then(model.scope, + [shown, displayUnits, registry, places, formatting, done, gathered = std::move(gathered)]( + std::expected, table::TableError> const& found) mutable { + if (!found) { + done(std::unexpected("The rows could not be copied: " + found.error().message)); + return; + } + for (FetchedRow const& fetchedRow : *found) { + CopyRow row{.viewRow = fetchedRow.viewRow, .cells = {}}; + for (std::size_t column = 0; column < places.size() && column < fetchedRow.cells.size(); + ++column) { + table::Cell const& cell = fetchedRow.cells.at(column); + std::size_t const place = places.at(column); + row.cells.push_back(std::holds_alternative(cell) + ? std::nullopt + : std::optional{formatCell(cell, shown->at(place), formatting, + displayUnits->at(place))}); + } + gathered.rows.push_back(std::move(row)); + } + done(std::move(gathered)); + }); + }; + Node dialogs = configureTable(model.config, ctx, options, nullptr); + markFilterable(model.config, columns, options); + options.onActivate = [this, ctx, &element, &model, commands = activateCommands](Key const& key) { + Value const activated = valueOfKey(key); + session.asUser([&] { + session.noteWrite(); + element.activeKey.set(activated); + }); + auto const found = model.rowScopes.find(canonicalJson(activated)); + std::shared_ptr const scope = found == model.rowScopes.end() ? nullptr : found->second.lock(); + LowerCtx const rowCtx{.scope = scope ? scope : ctx.scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; + runEvent(commands, rowCtx, activated); + }; + model.rows->mounting(); + if (std::shared_ptr const grid = + editableModelTable(node, ctx, element, *description, *shown, source, options, drafts)) { + return besideDialogs(options.common, std::move(dialogs), + [&] { return grid->node(std::move(columns), std::move(options), std::move(source)); }); + } + return besideDialogs(options.common, std::move(dialogs), + [&] { return ui::table(std::move(columns), std::move(source), std::move(options)); }); +} + +// A model's table with a column its description edits is mounted as a grid over its cells: each editable column's +// cells the field of its edit action, read from the catalog's schema, read-only where the principal may not run it. +// The grid's controller owns its source and what follows the table for it: the status line's notices, the rows' +// busy and failed states, and the layout the walk follows. Null for a table with no editable column. +// NOLINTNEXTLINE(readability-function-cognitive-complexity): builds an editable model table: each editable column's field, its read-only state and the controller's ownership of source and status line +std::shared_ptr ScreenCore::editableModelTable( + DocNode const& node, LowerCtx const& ctx, ElementState& element, table::TableDescription const& description, + std::vector const& shown, TableSource& source, TableOptions const& options, + std::shared_ptr> const& drafts) { + ModelTable& model = *element.modelTable; + if (model.edits == nullptr) { + return nullptr; + } + Catalog const& catalog = session.options().catalog; + std::vector columns; + bool editable = false; + for (table::TableColumn const& described : shown) { + ModelColumn column{.id = described.info.id, .edit = described.edit, .model = nullptr, .path = {}}; + if (described.edit) { + std::optional const schema = + catalog.schema ? catalog.schema(described.edit->action) : std::nullopt; + if (schema) { + if (auto made = forms::FormModel::fromSchema(described.edit->action, *schema)) { + column.model = std::make_shared(std::move(*made)); + column.path = + described.edit->member.empty() ? std::string{"value"} : "values." + described.edit->member; + editable = true; + } else { + report(node.path, "`" + described.info.id + "` is edited by `" + described.edit->action + + "`, whose input schema does not read: " + made.error().message); + } + } + } + columns.push_back(std::move(column)); + } + if (!editable) { + return nullptr; + } + EditMode const mode = node.name("editMode") == "row" ? EditMode::Row : EditMode::Cell; + // The edit sessions' number locale holds views into the formatting it was given, which the grid keeps. + std::shared_ptr const formatting = session.formattingHandle(); + auto const grid = std::make_shared( + model.rows, *model.edits, std::move(columns), mode, + ModelGridContext{.runtime = &runtime(), + .choices = model.calls, + .session = engineOptions(), + .format = ctx.scope->formatting(), + .may = [this](std::string_view action) { return session.can(action); }}); + grid->setDescription(description); + *drafts = grid; + model.editGrid = grid; + GridOptions walk{}; + gridOptions(node, ctx, walk); + walk.appendRows = false; + walk.rowsFixed = true; + walk.onActivate = options.onActivate; + auto controller = std::make_shared(runtime(), *grid, std::move(walk)); + // What the mounted grid holds while it lives: its source, the formatting its sessions read, and its effects. + struct Held { + std::shared_ptr grid; + std::shared_ptr formatting; + std::vector> effects; + }; + auto const held = std::make_shared(Held{.grid = grid, .formatting = formatting, .effects = {}}); + std::weak_ptr const weak = controller; + ModelGridSource* const cells = grid.get(); + // The grid's refusals and notices go to the status line as the table's messages, each once. + auto const posted = std::make_shared(0); + held->effects.push_back(std::make_unique(runtime(), [this, &element, weak, posted] { + std::shared_ptr const live = weak.lock(); + if (live == nullptr) { + return; + } + std::string text = live->message(); + std::uint64_t const notices = live->notices(); + runtime().untracked([&] { + if (notices != *posted) { + *posted = notices; + tableMessage(element, std::move(text)); + } + }); + })); + // The rows' busy and failed states are not reactive: their revision tells the cells. + held->effects.push_back(std::make_unique(runtime(), [this, &model, cells] { + static_cast(model.marksRevision.get()); + runtime().untracked([cells] { cells->touch(); }); + })); + // The walk follows the visible columns in layout order, and the cells the scope's formatting. + held->effects.push_back(std::make_unique(runtime(), [this, &model, cells, scope = ctx.scope] { + TableConfig const& arranged = model.config; + std::vector visible = + layoutOver(arranged.columns, arranged.declaredHidden, layoutNow(arranged)).visible(); + FormatContext format = scope->formatting(); + runtime().untracked([&] { + if (!visible.empty()) { + cells->setLayout(std::move(visible)); + } + cells->setFormat(std::move(format)); + }); + })); + controller->keepAlive(held); + source.rows = std::shared_ptr(grid, &grid->view()); + // Every cell is the column's own, so each draws its marks: no default cell is shared across columns. + source.defaultCellView = {}; + return controller; +} + +TableRowLook ScreenCore::headingRow(DocNode const& node, LowerCtx const& ctx, reactive::Signal const& row, + std::string key) { + auto const heading = node.partList("group").front()->nodes("heading"); + std::vector content; + content.reserve(heading.size()); + for (DocNodePtr const& child : heading) { + content.push_back(child.get()); + } + auto const scope = rowScope(node, ctx, row, content, std::move(key)); + LowerCtx const rowCtx{.scope = scope, .bindings = ctx.bindings, .boundary = ctx.boundary}; + // The row keeps the heading's scope for as long as it is realized. + TableRowLook look; + look.heading = lowerAll(heading, rowCtx); + look.keep = scope; + return look; +} + +Node ScreenCore::lowerChart(DocNode const& node, LowerCtx const& ctx, ElementState* element) { + Chart spec; + spec.data = slotProp( + [this, &node, scope = ctx.scope, bindings = ctx.bindings] { return chartData(node, *scope, bindings.get()); }); + commonOf(node, ctx, element, spec.common); + return ui::chart(std::move(spec)); +} + +std::optional ScreenCore::chartMagnitude(Value const& value, std::string const& path, + std::optional& unit) { + std::optional const number = numeric(value); + if (!number) { + report(path, "a chart value is a number or a quantity; this one is left out"); + return std::nullopt; + } + std::string const own = number->unit != nullptr ? *number->unit : std::string{}; + if (!unit) { + unit = own; + return number->value; + } + if (*unit == own) { + return number->value; + } + std::optional converted; + if (!own.empty() && !unit->empty()) { + converted = convertUnit(number->value, own, *unit, session.formatting().units); + } + if (!converted) { + report(path, "a chart value does not convert to the unit of the chart's first value; it is left out"); + } + return converted; +} + +std::optional ScreenCore::chartToneOf(Value const& value, std::string const& path) { + static constexpr std::array, 5> kTones = { + { + {"neutral", Tone::Neutral}, + {"info", Tone::Info}, + {"ok", Tone::Ok}, + {"warn", Tone::Warn}, + {"err", Tone::Err}, + }, + }; + if (value.isNull()) { + return std::nullopt; + } + if (std::string const* const text = value.asString()) { + for (auto const& [name, tone] : kTones) { + if (name == *text) { + return tone; + } + } + } + report(path, "a chart tone is neutral, info, ok, warn or err; this one marks nothing"); + return std::nullopt; +} + +std::optional ScreenCore::chartPosition(Value const& value, std::string const& path, + detail::ChartAxisKinds& kinds) { + if (value.isNull()) { + return std::nullopt; + } + if (std::optional const number = numeric(value)) { + kinds.numbers = true; + return number->value; + } + if (std::optional const instant = + dateInstantOf(value, session.formatting().utcOffsetMinutes).instant) { + kinds.instants = true; + return math::Rational{instant->value.time_since_epoch().count(), math::DecimalPlaces{0}}; + } + report(path, "a chart's `x` is a number, a date or an instant; this point is left out"); + return std::nullopt; +} + +std::vector ScreenCore::chartPoints(DocNode const& series, RtScope const& scope, + Bindings const* bindings, std::optional& unit, + detail::ChartAxisKinds& kinds) { + // A chart is a picture of a few hundred values; a larger set is a table's. + static constexpr std::size_t kMaxPoints = 1000; + FormatContext const& format = scope.formatting(); + ExprPtr const pointsExpr = series.prop("points"); + Value const listed = evalIn(scope, bindings, pointsExpr); + ValueList const* const list = listed.asList(); + if (list == nullptr) { + // `null` is a query still loading, and draws as empty without a word. + if (!listed.isNull()) { + report(pointsExpr->path, "`points` is a list; the series draws as empty"); + } + return {}; + } + std::size_t const first = list->size() > kMaxPoints ? list->size() - kMaxPoints : 0; + if (first > 0) { + report(pointsExpr->path, "a series draws its last 1000 points"); + } + ExprPtr const yExpr = series.prop("y"); + ExprPtr const xExpr = series.prop("x"); + ExprPtr const labelExpr = series.prop("xLabel"); + ExprPtr const toneExpr = series.prop("tone"); + ExprPtr const noteExpr = series.prop("note"); + std::vector points; + for (std::size_t index = first; index < list->size(); ++index) { + ScopeEnv const env{scope, bindings, &list->at(index)}; + detail::ChartRawPoint point{.index = index}; + if (xExpr) { + point.x = chartPosition(evaluate(*xExpr, env), xExpr->path, kinds); + if (!point.x) { + continue; + } + } + Value const value = evaluate(*yExpr, env); + if (!value.isNull()) { + point.y = chartMagnitude(value, yExpr->path, unit); + if (!point.y) { + continue; + } + } + point.xLabel = labelExpr ? textOf(evaluate(*labelExpr, env), format) : std::string{}; + point.note = noteExpr ? textOf(evaluate(*noteExpr, env), format) : std::string{}; + point.tone = toneExpr ? chartToneOf(evaluate(*toneExpr, env), toneExpr->path) : std::nullopt; + points.push_back(std::move(point)); + } + return points; +} + +} // namespace morph::ui::detail diff --git a/src/ui/mount_1.cpp b/src/ui/mount_1.cpp new file mode 100644 index 000000000..cf312eca5 --- /dev/null +++ b/src/ui/mount_1.cpp @@ -0,0 +1,1456 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +Windowing windowingOf(Virtualization const& virtualization, std::size_t rows, std::size_t visibleColumns, + bool serverMode) { + // rows × columns > cellThreshold, compared as a quotient so no product overflows. + bool const overCells = visibleColumns != 0 && rows > virtualization.cellThreshold / visibleColumns; + return Windowing{.rows = serverMode || rows >= virtualization.threshold || overCells, + .columns = visibleColumns > virtualization.columnThreshold || overCells}; +} + +void ColumnExtents::assign(std::span widths) { + _widths.assign(widths.begin(), widths.end()); + for (int& width : _widths) { + width = std::max(width, 0); + } + _user.assign(_widths.size(), false); + _tree.assign(_widths.size() + 1, 0); + for (std::size_t at = 0; at < _widths.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `at` runs below `_widths.size()`, the loop condition above + add(at, _widths[at]); + } +} + +bool ColumnExtents::grow(std::size_t column, int width) { + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column >= _widths.size()` returns first, and `assign` sizes `_user` with `_widths` + if (column >= _widths.size() || _user[column] || width <= _widths[column]) { + return false; + } + add(column, width - _widths[column]); + _widths[column] = width; + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + return true; +} + +bool ColumnExtents::fit(std::size_t column, int width) { + width = std::max(width, 0); + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column >= _widths.size()` returns first, and `assign` sizes `_user` with `_widths` + if (column >= _widths.size() || _user[column] || width == _widths[column]) { + return false; + } + add(column, width - _widths[column]); + _widths[column] = width; + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + return true; +} + +void ColumnExtents::set(std::size_t column, int width) { + if (column >= _widths.size()) { + return; + } + width = std::max(width, 0); + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column >= _widths.size()` returned above, and `assign` sizes `_user` with `_widths` + add(column, width - _widths[column]); + _widths[column] = width; + _user[column] = true; + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) +} + +std::pair ColumnExtents::columnsAt(int offset, int viewport) const { + std::size_t const count = _widths.size(); + std::size_t const first = std::min(below(std::max(offset, 0)), count); + std::size_t last = first; + if (viewport > 0) { + int const end = std::max(offset, 0) + viewport - 1; + last = std::min(below(end) + 1, count); + } + return {first, std::max(first, last)}; +} + +int ColumnExtents::offsetOf(std::size_t column) const { + std::size_t index = std::min(column, _widths.size()); + int sum = 0; + for (; index > 0; index -= index & (~index + 1)) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `index` starts at most at `_widths.size()`, one below `_tree.size()`, and only descends + sum += _tree[index]; + } + return sum; +} + +int ColumnExtents::widthOf(std::size_t column) const { + ++_reads; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): guarded by `column < _widths.size()` in the same expression + return column < _widths.size() ? _widths[column] : 0; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`column`, `delta`): called from `assign`, `grow`, `fit` and `set`, each passing the column first and the signed width change second +void ColumnExtents::add(std::size_t column, int delta) { + for (std::size_t at = column + 1; at < _tree.size(); at += at & (~at + 1)) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `at` stays below `_tree.size()` by the loop condition + _tree[at] += delta; + } +} + +std::size_t ColumnExtents::below(int offset) const { + std::size_t index = 0; + std::size_t step = std::bit_floor(std::max(_tree.size(), 1)); + int left = offset; + for (; step > 0; step >>= 1U) { + std::size_t const next = index + step; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `next < _tree.size()` is the first operand of this condition + if (next < _tree.size() && _tree[next] <= left) { + index = next; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): reached only under `next < _tree.size()`, tested on the line above + left -= _tree[next]; + } + } + return index; +} + +ColumnWindow columnWindow( + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`pinned`, `scrollX`): a column count then a scroll offset, passed by name from the table state at the one call site + ColumnExtents const& extents, std::size_t pinned, int scrollX, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`viewport`, `overscan`): a width then a column count, passed by name from the table state at the one call site + int viewport, std::size_t overscan) { + ColumnWindow window; + std::size_t const count = extents.size(); + pinned = std::min(pinned, count); + auto [first, last] = extents.columnsAt(scrollX, viewport); + first = first > overscan ? first - overscan : 0; + last = std::min(count, last + overscan); + first = std::max(first, pinned); + for (std::size_t at = 0; at < pinned; ++at) { + window.columns.push_back(at); + } + for (std::size_t at = first; at < last; ++at) { + window.columns.push_back(at); + } + window.leading = first < last ? extents.offsetOf(first) - extents.offsetOf(pinned) : 0; + window.trailing = extents.totalWidth() - extents.offsetOf(std::max(first, last)); + return window; +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +// NOLINTNEXTLINE(misc-no-recursion): a band's children are bands one level down. +void appendBandRuns(std::span bands, std::span visible, std::size_t pinned, + std::size_t level, std::vector& out) { + for (table::BandInfo const& band : bands) { + std::optional first; + std::size_t count = 0; + auto const close = [&] { + if (first) { + out.push_back(BandRun{.level = level, + .label = band.label, + .unit = band.unit, + .first = *first, + .count = count, + .pinned = *first < pinned}); + } + first.reset(); + count = 0; + }; + for (std::size_t at = 0; at < visible.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `at` is below `visible.size()`, the loop condition + bool const own = std::ranges::contains(band.columns, visible[at]); + // A run ends at a foreign column, and at the pinned edge. + if (!own || (at == pinned && first)) { + close(); + } + if (own) { + first = first.value_or(at); + ++count; + } + } + close(); + appendBandRuns(band.bands, visible, pinned, level + 1, out); + } +} + +// NOLINTNEXTLINE(misc-no-recursion): a band's children are bands one level down. +void enclosingBands(std::span bands, std::string_view columnId, + std::vector& out) { + for (table::BandInfo const& band : bands) { + if (std::ranges::contains(band.columns, columnId)) { + out.push_back(&band); + enclosingBands(band.bands, columnId, out); + return; + } + } +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +std::vector bandRuns(std::span bands, std::span visible, + std::size_t pinned) { + std::vector out; + detail::appendBandRuns(bands, visible, pinned, 0, out); + std::ranges::stable_sort(out, [](BandRun const& left, BandRun const& right) { + return left.level != right.level ? left.level < right.level : left.first < right.first; + }); + return out; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`columnId`, `unit`): a column id then its unit id, both read from the same TableColumn at every call +bool columnUnitShown(std::span bands, std::string_view columnId, std::string_view unit) { + if (unit.empty()) { + return true; + } + std::vector enclosing; + detail::enclosingBands(bands, columnId, enclosing); + return std::ranges::none_of(enclosing, [unit](table::BandInfo const* band) { return band->unit == unit; }); +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`columnId`, `unit`): a column id then its unit id, both read from the same TableColumn at every call +std::string bandedHeaderName(std::span bands, std::string_view columnId, + std::string_view label) { + std::vector enclosing; + detail::enclosingBands(bands, columnId, enclosing); + std::string out; + for (table::BandInfo const* band : enclosing) { + out += band->label + ", "; + } + return out + std::string{label}; +} + +std::size_t cutColumns(CellSpan const& span, std::span declared, + std::span visible) { + auto const shown = std::ranges::find(visible, span.column); + if (shown == visible.end()) { + return 0; + } + auto const own = std::ranges::find(declared, span.column); + if (own == declared.end()) { + return 1; + } + auto const place = static_cast(shown - visible.begin()); + auto const order = static_cast(own - declared.begin()); + std::size_t count = 1; + while ( + count < span.columns && place + count < visible.size() && order + count < declared.size() && + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `place + count < visible.size()` and `order + count < declared.size()` are earlier operands of the same condition + visible[place + count] == declared[order + count]) { + ++count; + } + return count; +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one refusal per rule of a span. +ResolvedSpans resolveRowSpans(std::vector const& rows, std::size_t columns, + std::span const> placeOf) { + ResolvedSpans out; + out.effective.resize(rows.size()); + auto const placeOfColumn = [&placeOf](std::size_t column) -> std::optional { + if (placeOf.empty()) { + return column; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): guarded by `column < placeOf.size()` in the same expression + return column < placeOf.size() ? placeOf[column] : std::nullopt; + }; + // Until which row each visible place is covered. + std::vector coveredUntil(columns, 0); + for (std::size_t index = 0; index < rows.size(); ++index) { + SpanRow const& row = rows.at(index); + std::vector named(columns, false); + for (RowSpan const& span : row.requested) { + auto const refuse = [&](char const* const site, std::string_view why) { + out.refused.emplace_back( + site, row.name + ": column " + std::to_string(span.column) + " " + std::string{why}); + }; + if (span.column >= columns || span.rows == 0 || span.columns == 0 || row.heading || + named.at(span.column)) { + refuse(site::kRowSpanInvalid, "is not a span of this table"); + continue; + } + named.at(span.column) = true; + std::optional const place = placeOfColumn(span.column); + if (!place || *place >= columns) { + continue; + } + std::size_t const wide = std::min(span.columns, columns - *place); + if (coveredUntil.at(*place) > index) { + refuse(site::kRowSpanOverlap, "starts under another span"); + continue; + } + if (span.rows == 1 && wide == 1) { + continue; + } + if (std::any_of(coveredUntil.begin() + static_cast(*place), + coveredUntil.begin() + static_cast(*place + wide), + [index](std::size_t until) { return until > index; })) { + refuse(site::kRowSpanOverlap, "covers a cell another span covers"); + continue; + } + std::size_t const end = index + span.rows; + bool const crossesHeading = + end <= rows.size() && std::any_of(rows.begin() + static_cast(index) + 1, + rows.begin() + static_cast(end), + [](SpanRow const& covered) { return covered.heading; }); + if (end > rows.size() || crossesHeading) { + refuse(site::kRowSpanOverrun, "runs past the last row or over a heading"); + continue; + } + out.effective.at(index).push_back(span); + std::fill(coveredUntil.begin() + static_cast(*place), + coveredUntil.begin() + static_cast(*place + wide), end); + } + std::ranges::sort(out.effective.at(index), {}, &RowSpan::column); + } + return out; +} + +KeyedRows::~KeyedRows() { + while (!list.empty()) { + list.pop_back(); + } +} + +std::vector stableTargets(std::vector const& sequence) { + constexpr auto kNone = static_cast(-1); + std::vector tails; // tails.at(n - 1): where the smallest tail of a run of length n sits + std::vector previous(sequence.size(), kNone); + for (std::size_t i = 0; i < sequence.size(); ++i) { + auto const place = std::ranges::lower_bound(tails, sequence.at(i), {}, + [&sequence](std::size_t entry) { return sequence.at(entry); }); + auto const length = static_cast(place - tails.begin()); + if (length > 0) { + previous.at(i) = tails.at(length - 1); + } + if (length == tails.size()) { + tails.push_back(i); + } else { + tails.at(length) = i; + } + } + std::vector stable(sequence.size(), false); + for (std::size_t cursor = tails.empty() ? kNone : tails.back(); cursor != kNone; cursor = previous.at(cursor)) { + stable.at(sequence.at(cursor)) = true; + } + return stable; +} + +void reorderChildren(ContainerWidget& container, std::vector& current, std::vector const& target) { + std::unordered_map targetOf; + for (std::size_t i = 0; i < target.size(); ++i) { + targetOf.emplace(target.at(i), i); + } + std::vector sequence; + sequence.reserve(current.size()); + for (Widget const* const child : current) { + sequence.push_back(targetOf.at(child)); + } + std::vector const stable = stableTargets(sequence); + auto const indexOf = [¤t](Widget const* child) { + return static_cast(std::ranges::find(current, child) - current.begin()); + }; + // From the back: each moved child goes directly before its successor in the target order, which is already + // in place, so one move per unstable child suffices. + for (std::size_t position = target.size(); position-- > 0;) { + if (stable.at(position)) { + continue; + } + Widget* const moving = target.at(position); + std::size_t const from = indexOf(moving); + std::size_t destination = current.size() - 1; + if (position + 1 < target.size()) { + std::size_t const before = indexOf(target.at(position + 1)); + destination = from < before ? before - 1 : before; + } + if (destination == from) { + continue; + } + container.moveChild(*moving, destination); + current.erase(current.begin() + static_cast(from)); + current.insert(current.begin() + static_cast(destination), moving); + } +} + +Widget* Mounter::mount(reactive::Scope& scope, Node const& node, ContainerWidget* parent) { + if (!node) { + return nullptr; + } + return std::visit( + [&](auto const& spec) -> Widget* { + if constexpr (requires { spec.common.layout.alignSelf; }) { + checkPlacement(spec.common, parent); + checkShare(spec.common, parent); + } + Widget& widget = this->mountKind(scope, spec, parent); + link(scope, widget, parent, takesFocus(spec)); + return &widget; + }, + node->kind); +} + +bool Mounter::focusAlong(std::string_view focusId, bool forward) { + auto const found = _focusable.lower_bound(focusId); + if (found == _focusable.end() || found->first != focusId) { + return false; + } + return focusAlong(*found->second, forward); +} + +bool Mounter::focusAlong(Widget const& from, bool forward) { + // The chain of the mount the widget is in: Tab in a dialog stays in the dialog. + Widget const* top = &from; + for (auto found = _chain.find(top); found != _chain.end() && found->second.parent != nullptr; + found = _chain.find(top)) { + top = found->second.parent; + } + bool const rooted = std::ranges::contains(_chainRoots, top); + std::vector> order; + for (Widget* const root : _chainRoots) { + if (root == top || !rooted) { + chainOrder(*root, true, order); + } + } + auto const hit = std::ranges::find(order, &from, [](auto const& entry) { return entry.first; }); + if (hit == order.end()) { + return false; + } + auto const index = static_cast(hit - order.begin()); + for (std::size_t step = 1; step < order.size(); ++step) { + if (!forward && step > index) { + break; + } + std::size_t const next = forward ? index + step : index - step; + if (next >= order.size()) { + break; + } + if (order.at(next).second) { + try { + order.at(next).first->focus(); + } catch (...) { // NOLINT(bugprone-empty-catch) + // Focus is a request: a backend that cannot move it leaves it where it was. + } + return true; + } + } + return false; +} + +bool Mounter::focus(std::string_view focusId) { + // lower_bound, not find: of equal names, find may answer any; lower_bound answers the first inserted. + auto const found = _focusable.lower_bound(focusId); + if (found == _focusable.end() || found->first != focusId) { + return false; + } + try { + found->second->focus(); + } catch (...) { // NOLINT(bugprone-empty-catch) + // Focus is a request: a backend that cannot move it leaves it where it was. + } + return true; +} + +bool Mounter::placeCursor(std::string_view focusId, std::size_t offset) { + auto const found = _focusable.lower_bound(focusId); + if (found == _focusable.end() || found->first != focusId) { + return false; + } + auto* const field = dynamic_cast(found->second); + if (field == nullptr) { + return false; + } + field->setCursor(offset); + try { + field->focus(); + } catch (...) { // NOLINT(bugprone-empty-catch) + // Focus is a request: a backend that cannot move it leaves it where it was. + } + // After the focus: a scroll that follows focus has moved to the field as a whole by now, and the cursor's + // line is what is then brought into view. + field->revealCursor(); + return true; +} + +ContainerWidget* Mounter::overlayFooter() const { + if (auto* const dialog = dynamic_cast(_overlay)) { + return &dialog->footer(); + } + if (auto* const drawer = dynamic_cast(_overlay)) { + return &drawer->footer(); + } + return nullptr; +} + +void Mounter::checkLayout(Common const& common) { + LayoutHints const& hints = common.layout; + auto const refuse = [&common](std::string const& what) { + throw std::logic_error{"morph::ui::mount: " + what + " on the node" + + (common.testId.empty() ? std::string{} : " `" + common.testId + "`")}; + }; + auto const check = [&refuse](Sizing sizing, std::optional minimum, std::optional maximum, + std::string const& axis) { + if (minimum.value_or(0) < 0 || maximum.value_or(0) < 0) { + refuse("a negative " + axis + " bound"); + } + if (minimum && maximum && *minimum > *maximum) { + refuse("a minimum " + axis + " above its maximum"); + } + if (sizing.kind == Sizing::Kind::Fixed && + (sizing.amount < minimum.value_or(sizing.amount) || sizing.amount > maximum.value_or(sizing.amount))) { + refuse("a fixed " + axis + " outside its bounds"); + } + }; + check(hints.width, hints.minWidth, hints.maxWidth, "width"); + check(hints.height, hints.minHeight, hints.maxHeight, "height"); + if (hints.width.kind == Sizing::Kind::Percent && (hints.width.amount < 1 || hints.width.amount > 100)) { + refuse("a percent width outside 1 to 100"); + } + if (hints.height.kind == Sizing::Kind::Percent) { + refuse("a percent height; a percent sizes a width"); + } +} + +void Mounter::checkShare(Common const& common, ContainerWidget const* parent) const { + if (common.layout.width.kind == Sizing::Kind::Percent && !_shareParents.contains(parent)) { + std::string const named = common.testId.empty() ? std::string{} : " (node `" + common.testId + "`)"; + throw std::logic_error{ + "morph::ui::mount: `percent` sizes a width along a row or a horizontal splitter; " + "nothing here takes a share" + + named}; + } +} + +void Mounter::checkNoShare(std::span tracks) { + if (std::ranges::any_of(tracks, + [](GridTrack const& track) { return track.width.kind == Sizing::Kind::Percent; })) { + throw std::logic_error{ + "morph::ui::mount: a grid track is sized by the grid; `percent` sizes a width " + "along a row or a horizontal splitter"}; + } +} + +void Mounter::checkNoShare(std::span columns) { + if (std::ranges::any_of(columns, + [](TableColumn const& column) { return column.width.kind == Sizing::Kind::Percent; })) { + throw std::logic_error{ + "morph::ui::mount: a table column is sized by the table; `percent` sizes a width " + "along a row or a horizontal splitter"}; + } +} + +void Mounter::checkOverlayLayout(Common const& common, std::string_view kind) { + LayoutHints const& hints = common.layout; + auto const refuse = [&common, kind](std::string const& axis) { + throw std::logic_error{"morph::ui::mount: a " + std::string{kind} + + " is sized by the frontend, not by its container; its " + axis + " cannot stretch" + + (common.testId.empty() ? std::string{} : " (node `" + common.testId + "`)")}; + }; + if (hints.width.kind == Sizing::Kind::Stretch) { + refuse("width"); + } + if (hints.width.kind == Sizing::Kind::Percent) { + throw std::logic_error{"morph::ui::mount: a " + std::string{kind} + + " is sized by the frontend, not by its container; its width takes no share"}; + } + if (hints.height.kind == Sizing::Kind::Stretch) { + refuse("height"); + } +} + +void Mounter::checkPlacement(Common const& common, ContainerWidget const* parent) { + if (common.layout.alignSelf && dynamic_cast(parent) == nullptr && + dynamic_cast(parent) == nullptr) { + std::string const named = common.testId.empty() ? std::string{} : " `" + common.testId + "`"; + throw std::logic_error{"morph::ui::mount: `alignSelf` places a node in its row, column or grid, and the node" + + named + " is not in one"}; + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): applies each common property (visible, enabled, tooltip, keys and so on) to the widget; each binds against the same scope +void Mounter::applyCommon(reactive::Scope& scope, Widget& widget, Common const& common) { + // The focus chain passes over a hidden or disabled widget and what is inside it. + ChainFlags const* const flags = common.visible.isBound() || !common.visible.constant() || + common.enabled.isBound() || !common.enabled.constant() + ? &scope.make(_chainFlags, &widget) + : nullptr; + if (common.visible.isBound() || !common.visible.constant()) { + bind(scope, common.visible, [&widget, flags](bool shown) { + flags->set(true, shown); + widget.setVisible(shown); + }); + } + if (common.enabled.isBound() || !common.enabled.constant()) { + bind(scope, common.enabled, [&widget, flags](bool enabled) { + flags->set(false, enabled); + widget.setEnabled(enabled); + }); + } + if (common.layout != LayoutHints{}) { + checkLayout(common); + widget.setLayout(common.layout); + } + if (common.dragKey.isBound() || common.dragKey.constant().has_value()) { + bind(scope, common.dragKey, [&widget](std::optional const& key) { widget.setDragKey(key); }); + } + if (common.onDrop) { + applyDrop(widget, common); + } + if (common.a11y.name.isBound() || !common.a11y.name.constant().empty()) { + bind(scope, common.a11y.name, [&widget](std::string const& name) { widget.setAccessibleName(name); }); + } + if (!common.a11y.role.empty()) { + widget.setAccessibleRole(common.a11y.role); + } + if (!common.testId.empty()) { + widget.setTestId(common.testId); + } + if (common.tooltip.isBound() || !common.tooltip.constant().empty()) { + bind(scope, common.tooltip, [&widget](std::string const& text) { widget.setTooltip(text); }); + } + if (common.surface.isBound() || !common.surface.constant().empty()) { + bind(scope, common.surface, [&widget](std::string const& surface) { widget.setSurface(surface); }); + } + if (!common.keys.empty()) { + applyKeys(widget, common.keys); + } + if (common.autofocus && _autofocus == nullptr) { + _autofocus = &widget; + } + if (common.focusId.isBound()) { + // Registered under the name it has now, and again under each new one. + auto& focusable = scope.make(_focusable, std::nullopt); + bind(scope, common.focusId, [this, &focusable, &widget](std::string const& name) { + focusable.reset(name.empty() ? std::nullopt : std::optional{_focusable.emplace(name, &widget)}); + }); + } else if (!common.focusId.constant().empty()) { + scope.make(_focusable, _focusable.emplace(common.focusId.constant(), &widget)); + } +} + +void Mounter::ChainFlags::set(bool visible, bool value) const { + auto& entry = flags->at(of); + (visible ? entry.first : entry.second) = value; +} + +void Mounter::link(reactive::Scope& scope, Widget& widget, ContainerWidget const* parent, bool focusable) { + // A source table's cells, and an editor in one, are inside the table, which is one stop of the chain. + if (parent != nullptr && _offChain.contains(parent)) { + return; + } + ChainEntry& entry = _chain[&widget]; + if (entry.linked) { + entry.takesFocus = entry.takesFocus || focusable; + return; + } + entry.linked = true; + entry.parent = parent; + entry.takesFocus = focusable; + if (parent != nullptr) { + _chain[parent].children.push_back(&widget); + } else { + _chainRoots.push_back(&widget); + } + scope.make(*this, &widget); +} + +void Mounter::unlink(Widget* widget) noexcept { + auto const found = _chain.find(widget); + if (found == _chain.end()) { + return; + } + Widget const* const parent = found->second.parent; + found->second.linked = false; + found->second.parent = nullptr; + if (found->second.children.empty()) { + _chain.erase(found); + } + std::erase(_chainRoots, widget); + if (parent == nullptr) { + return; + } + if (auto const above = _chain.find(parent); above != _chain.end()) { + std::erase(above->second.children, widget); + if (!above->second.linked && above->second.children.empty()) { + _chain.erase(above); + } + } +} + +void Mounter::reorderChain(Widget const& container, std::vector const& order) { + auto const found = _chain.find(&container); + if (found == _chain.end()) { + return; + } + std::vector& children = found->second.children; + std::vector next; + next.reserve(children.size()); + std::ranges::copy_if(order, std::back_inserter(next), + [&children](Widget const* child) { return std::ranges::contains(children, child); }); + std::ranges::copy_if(children, std::back_inserter(next), + [&next](Widget const* child) { return !std::ranges::contains(next, child); }); + children = std::move(next); +} + +// NOLINTNEXTLINE(misc-no-recursion): a container's children are walked in turn. +void Mounter::chainOrder(Widget& widget, bool shown, std::vector>& out) const { + bool here = shown; + if (auto const flags = _chainFlags.find(&widget); flags != _chainFlags.end()) { + here = here && flags->second.first && flags->second.second; + } + auto const found = _chain.find(&widget); + if (found == _chain.end()) { + return; + } + if (found->second.takesFocus) { + out.emplace_back(&widget, here); + } + for (Widget* const child : found->second.children) { + chainOrder(*child, here, out); + } +} + +void Mounter::Focusable::reset(std::optional next) noexcept { + if (entry) { + map->erase(*entry); + } + entry = next; +} + +void Mounter::applyDrop(Widget& widget, Common const& common) { + std::function accepts = [](Key const&) { return true; }; + if (common.accepts) { + accepts = [runtime = _rt, predicate = common.accepts](Key const& key) { + bool accepted = false; + static_cast(runCallback(*runtime, [&] { accepted = predicate(key); })); + return accepted; + }; + } + widget.setDropHandler(std::move(accepts), event(common.onDrop)); +} + +void Mounter::applyKeys(Widget& widget, std::vector const& keys) { + std::vector chords; + chords.reserve(keys.size()); + for (KeyBinding const& binding : keys) { + chords.push_back(binding.chord); + } + widget.setKeys(chords, [runtime = _rt, keys](std::string const& chord) { + auto const bound = std::ranges::find(keys, chord, &KeyBinding::chord); + if (bound != keys.end() && bound->onPress) { + static_cast(runCallback(*runtime, bound->onPress)); + } + }); +} + +void Mounter::mountChildren(reactive::Scope& scope, std::vector const& children, ContainerWidget& container) { + for (Node const& child : children) { + static_cast(mount(scope, child, &container)); + } +} + +Widget& Mounter::mountStack(reactive::Scope& scope, Axis axis, std::vector const& children, int gap, + Common const& common, ContainerWidget* parent, Align align, Justify justify, bool wrap, + bool divided, Padding padding, std::optional> const& selected, bool holder) { + StackWidget& widget = scope.adopt(_backend->createStack(parent, axis)); + if (holder) { + widget.setPassesBleed(true); + } + if (axis == Axis::Horizontal && !wrap && dynamic_cast(parent) == nullptr) { + scope.make(_shareParents, &widget); + } + if (wrap) { + widget.setWrap(true); + } + if (divided) { + widget.setDivided(true); + } + if (Padding const inset = clampedPadding(padding); inset != Padding{}) { + widget.setPadding(inset); + } + applyCommon(scope, widget, common); + if (selected) { + bind(scope, *selected, [&widget](bool chosen) { widget.setSelected(chosen); }); + } + widget.setGap(spacingStep(gap)); + if (align != Align::Stretch) { + widget.setAlign(align); + } + if (justify != Justify::Start) { + widget.setJustify(justify); + } + if (startsHidden(common) && dynamic_cast(parent) == nullptr) { + mountWhenShown(scope, children, widget, common.visible); + } else { + mountChildren(scope, children, widget); + } + return widget; +} + +void Mounter::mountWhenShown(reactive::Scope& scope, std::vector const& children, ContainerWidget& container, + Prop const& visible) { + if (!visible.isBound()) { + return; + } + reactive::Scope& content = scope.child(); + bool& mounted = scope.make(false); + bind(scope, visible, [this, &content, &container, &mounted, children](bool shown) { + if (!shown || mounted) { + return; + } + mounted = true; + _rt->untracked([&] { + mountPass([&] { + mountChildren(content, children, container); + return 0; + }); + }); + }); +} + +// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. +std::vector Mounter::shownLevel(std::vector const& items, MenuLevelAt const& where, + std::map& sources) { + std::vector entries; + auto const record = [&](std::size_t source) { + MenuPath shownPath = where.shown; + shownPath.push_back(entries.size() - 1); + MenuPath sourcePath = where.source; + sourcePath.push_back(source); + sources.insert_or_assign(std::move(shownPath), std::move(sourcePath)); + }; + for (std::size_t source = 0; source < items.size(); ++source) { + MenuItem const& item = items.at(source); + if (item.separator) { + if (!entries.empty() && !entries.back().separator) { + entries.push_back(MenuEntry{.separator = true}); + record(source); + } + continue; + } + if (!item.visible.evaluate()) { + continue; + } + MenuLevelAt child = where; + child.shown.push_back(entries.size()); + child.source.push_back(source); + entries.push_back(MenuEntry{.label = item.label.evaluate(), + .icon = item.icon, + .keys = item.keys, + .checked = item.checked.evaluate(), + .enabled = item.enabled.evaluate(), + .items = shownLevel(item.items, child, sources), + .description = item.description.evaluate()}); + record(source); + } + if (!entries.empty() && entries.back().separator) { + MenuPath last = where.shown; + last.push_back(entries.size() - 1); + sources.erase(last); + entries.pop_back(); + } + return entries; +} + +Mounter::ShownMenu Mounter::shownOf(std::vector const& items) { + ShownMenu shown; + shown.entries = shownLevel(items, MenuLevelAt{}, shown.sources); + return shown; +} + +// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. +bool Mounter::entryBound(MenuItem const& item) { + return item.label.isBound() || item.description.isBound() || item.checked.isBound() || item.enabled.isBound() || + item.visible.isBound() || anyBound(item.items); +} + +MenuItem const* Mounter::itemAt(std::vector const& items, std::map const& sources, + MenuPath const& path) { + auto const found = sources.find(path); + if (found == sources.end()) { + return nullptr; + } + std::vector const* level = &items; + MenuItem const* item = nullptr; + for (std::size_t const index : found->second) { + if (index >= level->size()) { + return nullptr; + } + item = &level->at(index); + level = &item->items; + } + return item == nullptr || item->separator ? nullptr : item; +} + +void Mounter::applyField(reactive::Scope& scope, FieldWidget& widget, FieldState const& field) { + if (field.readonly.isBound() || field.readonly.constant()) { + bind(scope, field.readonly, [&widget](bool readonly) { widget.setReadOnly(readonly); }); + } + if (field.required.isBound() || field.required.constant()) { + bind(scope, field.required, [&widget](bool required) { widget.setRequired(required); }); + } + if (field.errors.isBound() || !field.errors.constant().empty()) { + bind(scope, field.errors, [&widget](std::vector const& errors) { widget.setErrors(errors); }); + } + if (field.stale.isBound() || field.stale.constant()) { + bind(scope, field.stale, [&widget](bool stale) { widget.setStale(stale); }); + } + if (field.description.isBound() || !field.description.constant().empty()) { + bind(scope, field.description, + [&widget](std::string const& description) { widget.setDescription(description); }); + } + if (field.labelHint.isBound() || !field.labelHint.constant().empty()) { + bind(scope, field.labelHint, [&widget](std::string const& hint) { widget.setCaptionHint(hint); }); + } + if (field.tone.isBound() || field.tone.constant() != Tone::Neutral) { + bind(scope, field.tone, [&widget](Tone tone) { widget.setTone(tone); }); + } +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Text const& spec, ContainerWidget* parent) { + if (spec.field.description.isBound() || !spec.field.description.constant().empty()) { + throw std::logic_error{"morph::ui: a text is not described; put the line in the text"}; + } + if (spec.field.labelHint.isBound() || !spec.field.labelHint.constant().empty()) { + throw std::logic_error{"morph::ui: a text has no caption to hint after; put the hint in the text"}; + } + TextWidget& widget = scope.adopt(_backend->createText(parent)); + applyCommon(scope, widget, spec.common); + applyField(scope, widget, spec.field); + // Spans replace the text, so a text that has them is never told its plain text. + if (hasSpans(spec.spans)) { + bind(scope, spec.spans, [&widget](std::vector const& spans) { widget.setSpans(spans); }); + } else { + bind(scope, spec.text, [&widget](std::string const& text) { widget.setText(text); }); + } + bind(scope, spec.role, [&widget](TextRole role) { widget.setRole(role); }); + if (spec.align) { + widget.setAlign(*spec.align); + } + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Button const& spec, ContainerWidget* parent) { + if (spec.style == ButtonStyle::Push && spec.child != nullptr) { + throw std::logic_error{"morph::ui: only a list entry holds content; a push button has a label"}; + } + ButtonWidget& widget = scope.adopt(_backend->createButton(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.label, [&widget](std::string const& label) { widget.setLabel(label); }); + if (spec.emphasis != ButtonEmphasis::Normal) { + widget.setEmphasis(spec.emphasis); + } + if (!spec.icon.empty()) { + widget.setIcon(spec.icon); + } + if (spec.style == ButtonStyle::Item) { + widget.setStyle(spec.style); + } + if (spec.shape != ControlShape::Default) { + widget.setShape(spec.shape); + } + if (spec.size != ButtonSize::Normal) { + widget.setSize(spec.size); + } + if (spec.mono) { + widget.setMono(true); + } + if (spec.weight != 0) { + widget.setWeight(spec.weight); + } + if (spec.selected.isBound() || spec.selected.constant()) { + bind(scope, spec.selected, [&widget](bool selected) { widget.setSelected(selected); }); + } + widget.setOnClick(event(spec.onClick)); + if (spec.child != nullptr) { + static_cast(mount(scope, spec.child, &widget.content())); + } + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, TextInput const& spec, ContainerWidget* parent) { + bool const hasUnit = spec.unit.isBound() || !spec.unit.constant().empty(); + bool const hasPrefix = spec.prefix.isBound() || !spec.prefix.constant().empty(); + bool const hasDecimals = spec.decimals.isBound() || spec.decimals.constant() >= 0; + if ((hasUnit || hasPrefix || hasDecimals || !spec.icon.empty()) && spec.mode == TextInputMode::Multiline) { + throw std::logic_error{ + "morph::ui: a multiline text input holds no number, so it takes no unit, prefix, places or icon"}; + } + if (spec.align != Align::Start && spec.mode == TextInputMode::Multiline) { + throw std::logic_error{"morph::ui: a multiline text input's text starts at the leading edge"}; + } + if (spec.emphasis != InputEmphasis::Normal && spec.mode == TextInputMode::Multiline) { + throw std::logic_error{"morph::ui: a multiline text input's size is its own; it takes no emphasis"}; + } + TextInputWidget& widget = scope.adopt(_backend->createTextInput(parent, spec.mode)); + applyCommon(scope, widget, spec.common); + applyField(scope, widget, spec.field); + auto reassert = controlled(scope, spec.value, [&widget](std::string const& value) { widget.setText(value); }); + bind(scope, spec.placeholder, [&widget](std::string const& text) { widget.setPlaceholder(text); }); + // An input without a unit or places is not told any, so a backend sees only what a field declares. + if (hasUnit) { + bind(scope, spec.unit, [&widget](std::string const& unit) { widget.setUnit(unit); }); + } + if (hasPrefix) { + bind(scope, spec.prefix, [&widget](std::string const& prefix) { widget.setPrefix(prefix); }); + } + if (hasDecimals) { + bind(scope, spec.decimals, [&widget](int decimals) { widget.setDecimals(decimals); }); + } + if (!spec.icon.empty()) { + widget.setIcon(spec.icon); + } + if (spec.emphasis != InputEmphasis::Normal) { + widget.setEmphasis(spec.emphasis); + } + if (spec.mono) { + widget.setMono(true); + } + if (!spec.wrap) { + widget.setWrap(false); + } + if (spec.align != Align::Start) { + widget.setAlign(spec.align); + } + applyCaption(scope, widget, spec.label, spec.showLabel); + widget.setOnChange(inputEvent(spec.onChange, reassert)); + // An empty submit handler tells the backend the field does not submit, so Enter goes on to its ancestors' + // chords (a dialog's default) once the field has committed. + widget.setOnSubmit(spec.onSubmit ? inputEvent(spec.onSubmit, std::move(reassert)) + : std::function{}); + widget.setOnCommit(event(spec.onCommit)); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Checkbox const& spec, ContainerWidget* parent) { + CheckboxWidget& widget = scope.adopt(_backend->createCheckbox(parent)); + applyCommon(scope, widget, spec.common); + applyField(scope, widget, spec.field); + bind(scope, spec.label, [&widget](std::string const& label) { widget.setLabel(label); }); + widget.setOnToggle(inputEvent( + spec.onToggle, controlled(scope, spec.checked, [&widget](bool checked) { widget.setChecked(checked); }))); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Select const& spec, ContainerWidget* parent) { + SelectWidget& widget = scope.adopt(_backend->createSelect(parent, spec.style)); + applyCommon(scope, widget, spec.common); + applyField(scope, widget, spec.field); + bind(scope, spec.options, [&widget](std::vector const& options) { widget.setOptions(options); }); + widget.setOnSelect(inputEvent( + spec.onSelect, + controlled(scope, spec.selected, [&widget](std::optional const& key) { widget.setSelected(key); }))); + widget.setOnOpen(event(spec.onOpen)); + applyCaption(scope, widget, spec.label, spec.showLabel); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Menu const& spec, ContainerWidget* parent) { + MenuWidget& widget = scope.adopt(_backend->createMenu(parent, spec.style)); + applyCommon(scope, widget, spec.common); + if (spec.style == MenuStyle::Button) { + bind(scope, spec.label, [&widget, icon = spec.icon, emphasis = spec.emphasis](std::string const& label) { + widget.setTrigger(MenuTrigger{.label = label, .icon = icon, .emphasis = emphasis}); + }); + } + std::vector const& items = spec.items; + // One prop for the whole tree: a bound label, description, mark, enablement or visibility anywhere re-sends + // every entry, which keeps setItems the one setter. A reported path is read against what was last sent. + auto sent = std::make_shared>(); + Prop const shown = anyBound(items) ? Prop([items = items] { return shownOf(items); }) + : Prop(shownOf(items)); + bind(scope, shown, [&widget, sent](ShownMenu const& menu) { + *sent = menu.sources; + widget.setItems(menu.entries); + }); + widget.setOnActivate(event( + std::function)>{[items = items, sent](std::vector const& path) { + MenuItem const* const item = itemAt(items, *sent, path); + if (item != nullptr && item->onSelect) { + item->onSelect(); + } + }})); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Column const& spec, ContainerWidget* parent) { + return mountStack(scope, Axis::Vertical, spec.children, spec.gap, spec.common, parent, spec.align, spec.justify, + false, spec.divided, spec.padding, spec.selected, spec.holder); +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Row const& spec, ContainerWidget* parent) { + if ((spec.tone || spec.label || spec.heading || spec.spans) && dynamic_cast(parent) == nullptr) { + throw std::logic_error{ + "morph::ui: a row's tone, label, heading and spans are a table row's; this row is not in a table"}; + } + if (spec.selected && dynamic_cast(parent) != nullptr) { + throw std::logic_error{"morph::ui: a table row's selection is the table's; this row gives its own"}; + } + return mountStack(scope, Axis::Horizontal, spec.children, spec.gap, spec.common, parent, spec.align, spec.justify, + spec.wrap, spec.divided && !spec.wrap, spec.padding, spec.selected); +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Grid const& spec, ContainerWidget* parent) { + GridWidget& widget = scope.adopt(_backend->createGrid(parent)); + applyCommon(scope, widget, spec.common); + checkNoShare(spec.tracks); + if (spec.tracks.empty()) { + widget.setColumns(spec.columns); + } else { + widget.setTracks(spec.tracks); + } + if (spec.minColumnWidth > 0 && spec.tracks.empty()) { + widget.setMinColumnWidth(spec.minColumnWidth); + } + widget.setGap(spacingStep(spec.gap)); + if (spec.align != Align::Stretch) { + widget.setAlign(spec.align); + } + for (GridCell const& cell : spec.cells) { + Widget* const child = mount(scope, cell.node, &widget); + if (child != nullptr && cell.span != 1) { + widget.setSpan(*child, cell.span); + } + } + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Spacer const& spec, ContainerWidget* parent) { + SpacerWidget& widget = scope.adopt(_backend->createSpacer(parent)); + applyCommon(scope, widget, spec.common); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Panel const& spec, ContainerWidget* parent) { + PanelWidget& widget = scope.adopt(_backend->createPanel(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.title, [&widget](std::string const& title) { widget.setTitle(title); }); + if (Widget* const header = mount(scope, spec.header, &widget); header != nullptr) { + widget.setHeader(*header); + } + widget.setPadding(spacingStep(spec.padding)); + widget.setCollapsible(spec.collapsible); + if (spec.collapsible) { + widget.setOnToggle(inputEvent(spec.onToggle, controlled(scope, spec.collapsed, [&widget](bool collapsed) { + widget.setCollapsed(collapsed); + }))); + } + static_cast(mount(scope, spec.child, &widget)); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Scroll const& spec, ContainerWidget* parent) { + ScrollWidget& widget = scope.adopt(_backend->createScroll(parent, spec.axis)); + applyCommon(scope, widget, spec.common); + static_cast(mount(scope, spec.child, &widget)); + return widget; +} + +std::unique_ptr Mounter::mountContent(std::size_t depth, Node const& node, ContainerWidget& host) { + return mountPass([&] { + auto content = std::make_unique(*_rt, depth); + _rt->untracked([&] { static_cast(mount(*content, node, &host)); }); + return content; + }); +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Switch const& spec, ContainerWidget* parent) { + SlotWidget& widget = scope.adopt(_backend->createSlot(parent)); + applyCommon(scope, widget, spec.common); + auto& content = scope.make>(); + bind(scope, spec.selector, + [this, &widget, &content, depth = scope.depth() + 1, cases = spec.cases, fallback = spec.fallback, + overlay = _overlay](Key const& key) { + content.reset(); + auto const chosen = std::ranges::find(cases, key, &SwitchCase::key); + Node const& node = chosen == cases.end() ? fallback : chosen->node; + if (node) { + content = underOverlay(overlay, [&] { return mountContent(depth, node, widget); }); + } + }); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Tabs const& spec, ContainerWidget* parent) { + TabsWidget& widget = scope.adopt(_backend->createTabs(parent)); + applyCommon(scope, widget, spec.common); + if (spacingStep(spec.inset) != 0) { + widget.setInset(spacingStep(spec.inset)); + } + if (spec.pageInset) { + widget.setPageInset(spacingStep(*spec.pageInset)); + } + if (!spec.stripSurface.empty()) { + widget.setStripSurface(spec.stripSurface); + } + // One prop over every caption, as a menu's entries: a bound caption re-sends them all. The count never + // changes, so the widget keeps its highlight, the shown page and the focus across a relabel. + std::vector> captions; + captions.reserve(spec.tabs.size()); + for (Tab const& tab : spec.tabs) { + captions.push_back(tab.label); + } + auto labelsOf = [captions] { + std::vector labels; + labels.reserve(captions.size()); + for (Prop const& caption : captions) { + labels.push_back(caption.evaluate()); + } + return labels; + }; + Prop> const labels = std::ranges::any_of(captions, &Prop::isBound) + ? Prop>(std::move(labelsOf)) + : Prop>(labelsOf()); + bind(scope, labels, [&widget](std::vector const& shown) { widget.setTabs(shown); }); + if (spec.moreLabel.isBound() || spec.moreLabel.constant() != "More") { + bind(scope, spec.moreLabel, [&widget](std::string const& label) { widget.setMoreLabel(label); }); + } + auto& pageScope = scope.child(); + auto& pages = scope.make(); + pages.pageSlots.resize(spec.tabs.size(), nullptr); + // A bound index is controlled: after a pick, the bar highlights the page that is shown, so a pick the + // document refuses moves the highlight back. A constant index is not a slot, and the bar keeps the pick. + std::function reassert; + if (spec.selected.isBound()) { + reassert = reasserter( + scope, pages.highlighted, + [&pages] { return pages.shown.value_or(std::numeric_limits::max()); }, + [&widget, &pages](std::size_t index) { highlight(widget, pages, index); }); + } + widget.setOnSelect(inputEvent(spec.onSelect, reassert)); + pages.onSelect = inputEvent(spec.onSelect, std::move(reassert)); + auto show = [this, &widget, &pageScope, &pages, pageSpecs = spec.tabs, overlay = _overlay](std::size_t index) { + _rt->untracked([&] { showPage(widget, pageScope, pages, pageSpecs, index, overlay); }); + }; + if (!spec.selected.isBound()) { + show(spec.selected.constant()); + } else { + scope.effect([binding = spec.selected.binding(), show = std::move(show)] { show(binding()); }); + } + return widget; +} + +void Mounter::showPage(TabsWidget& widget, reactive::Scope& pageScope, Pages& pages, std::vector const& pageSpecs, + std::size_t index, ContainerWidget* overlay) { + bool const exists = index < pageSpecs.size(); + bool const isNew = exists && pages.pageSlots.at(index) == nullptr; + if (isNew) { + try { + underOverlay(overlay, [&] { mountPage(widget, pageScope, pages, pageSpecs.at(index).node, index); }); + } catch (...) { + if (pages.shown.has_value()) { + restoreSelection(widget, pages, *pages.shown); + } + throw; + } + } + if (pages.shown != index) { + if (pages.shown.has_value() && *pages.shown < pages.pageSlots.size()) { + if (SlotWidget* const previous = pages.pageSlots.at(*pages.shown); previous != nullptr) { + previous->setVisible(false); + } + } + if (exists && !isNew) { + pages.pageSlots.at(index)->setVisible(true); + } + } + pages.shown = index; + highlight(widget, pages, index); +} + +void Mounter::highlight(TabsWidget& widget, Pages& pages, std::size_t index) { + widget.setSelected(index); + pages.highlighted = index; +} + +void Mounter::restoreSelection(TabsWidget& widget, Pages& pages, std::size_t shown) noexcept { + try { + highlight(widget, pages, shown); + } catch (...) { // NOLINT(bugprone-empty-catch) + // The page's failure is the one reported; the bar keeps whatever highlight it had. + } + try { + std::function const onSelect = pages.onSelect; + if (onSelect) { + onSelect(shown); + } + } catch (...) { // NOLINT(bugprone-empty-catch) + // Only copying the wrapper can throw here; the application then keeps the failed index. + } +} + +void Mounter::mountPage(TabsWidget& widget, reactive::Scope& pageScope, Pages& pages, Node const& node, + std::size_t index) { + auto page = mountPass([&] { + auto built = std::make_unique(*_rt, pageScope.depth()); + SlotWidget& slot = built->adopt(_backend->createSlot(&widget)); + // A page fills the area under the strip, pads itself by the node's `pageInset` and scrolls itself while + // its content overflows, as a workspace's page does. + slot.setLayout({.width = Sizing::stretch(), .height = Sizing::stretch()}); + slot.setScrollable(true); + static_cast(mount(*built, node, &slot)); + return std::pair{std::move(built), &slot}; + }); + pageScope.adopt(std::move(page.first)); + pages.pageSlots.at(index) = page.second; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Dialog const& spec, ContainerWidget* parent) { + checkOverlayLayout(spec.common, "dialog"); + DialogWidget& widget = scope.adopt(_backend->createDialog(parent)); + applyCommon(scope, widget, spec.common); + if (spec.sheet.isBound() || spec.sheet.constant()) { + bind(scope, spec.sheet, [&widget](bool sheet) { widget.setSheet(sheet); }); + } + return mountOverlay(scope, spec, widget); +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Drawer const& spec, ContainerWidget* parent) { + checkOverlayLayout(spec.common, "drawer"); + DrawerWidget& widget = scope.adopt(_backend->createDrawer(parent, spec.side)); + applyCommon(scope, widget, spec.common); + return mountOverlay(scope, spec, widget); +} + +void Mounter::dismissFailed(std::function const& onDismiss) noexcept { + try { + std::function const dismiss = onDismiss; + if (dismiss) { + dismiss(); + } + } catch (...) { // NOLINT(bugprone-empty-catch) + // Only copying the wrapper can throw here; the application then keeps `open` true. + } +} + +Widget& Mounter::mountKind(reactive::Scope& scope, ForEach const& spec, ContainerWidget* parent) { + StackWidget& widget = scope.adopt(_backend->createStack(parent, spec.axis)); + // A horizontal ForEach directly in an action bar is part of the row of actions, so its rows are the action + // gap apart, whatever gap the ForEach says. + bool const actionRow = spec.axis == Axis::Horizontal && _actionBar != nullptr && parent == _actionBar; + if (actionRow) { + widget.setActionRow(); + } + if (spec.axis == Axis::Horizontal && !spec.wrap) { + scope.make(_shareParents, &widget); + } + if (spec.wrap && spec.axis == Axis::Horizontal) { + widget.setWrap(true); + } + if (spec.divided && spec.axis == Axis::Vertical) { + widget.setDivided(true); + } + applyCommon(scope, widget, spec.common); + widget.setGap(spacingStep(actionRow ? 2 : spec.gap)); + mountRows(scope, spec.model, widget, {}, nullptr); + return widget; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): resolves spans against the table's rows in one pass: what the widget is told depends on the difference from the previous resolve, and refusals report when their set changes +void Mounter::resolveSpans(TableWidget& widget, SpanTable& table) { + if (table.reconciling != 0 || !table.anyAsked) { + return; + } + std::vector rows; + rows.reserve(table.order.size()); + for (SpanTable::Placed const& placed : table.order) { + auto const found = table.rows.find(placed.key); + SpanRow row{.name = "row " + std::visit([](auto const& key) { return std::format("{}", key); }, placed.key)}; + if (found != table.rows.end()) { + row.heading = found->second.heading; + row.requested = found->second.requested; + } + rows.push_back(std::move(row)); + } + bool const virtualized = table.windowed || table.order.size() >= table.threshold; + ResolvedSpans resolved; + if (table.sorted) { + resolved.effective.resize(rows.size()); + } else if (virtualized) { + resolved.effective.resize(rows.size()); + if (std::ranges::any_of(rows, [](SpanRow const& row) { + return std::ranges::any_of(row.requested, + [](RowSpan const& span) { return span.rows >= 2 || span.columns >= 2; }); + })) { + resolved.refused.emplace_back(site::kRowSpanVirtualized, "the table is virtualized"); + } + } else { + resolved = resolveRowSpans(rows, table.columns, table.placeOf); + } + std::set refused; + for (auto const& [reason, text] : resolved.refused) { + refused.insert(std::string{reason} + " | " + text); + } + if (refused != table.lastRefused) { + std::set sites; + for (auto const& [reason, text] : resolved.refused) { + sites.insert(reason); + } + for (char const* const reason : sites) { + _rt->core()->report(reason); + } + table.lastRefused = std::move(refused); + } + for (std::size_t index = 0; index < table.order.size(); ++index) { + SpanTable::Placed const& placed = table.order.at(index); + auto const found = table.rows.find(placed.key); + if (placed.widget == nullptr || found == table.rows.end()) { + continue; + } + RowSpanEntry& entry = found->second; + if (entry.told != placed.widget) { + entry.told = placed.widget; + entry.sent.clear(); + } + if (resolved.effective.at(index) != entry.sent) { + entry.sent = resolved.effective.at(index); + widget.setRowSpans(*placed.widget, entry.sent); + } + } +} + +} // namespace morph::ui::detail diff --git a/src/ui/mount_2.cpp b/src/ui/mount_2.cpp new file mode 100644 index 000000000..9cd68c7f5 --- /dev/null +++ b/src/ui/mount_2.cpp @@ -0,0 +1,1400 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui::detail { + +// NOLINTNEXTLINE(misc-no-recursion): a submenu is a menu one level down. +void Mounter::readMenuItems(std::vector const& items, std::vector& shown, + std::vector& kept) { + for (MenuItem const& item : items) { + if (item.separator) { + if (!shown.empty() && !shown.back().separator) { + shown.push_back(MenuEntry{.separator = true}); + kept.emplace_back(); + } + continue; + } + if (!item.visible.evaluate()) { + continue; + } + MenuEntry entry{.label = item.label.evaluate(), + .icon = item.icon, + .keys = item.keys, + .checked = item.checked.evaluate(), + .enabled = item.enabled.evaluate(), + .description = item.description.evaluate()}; + OpenItem open{.onSelect = item.onSelect, .items = {}}; + readMenuItems(item.items, entry.items, open.items); + shown.push_back(std::move(entry)); + kept.push_back(std::move(open)); + } + if (!shown.empty() && shown.back().separator) { + shown.pop_back(); + kept.pop_back(); + } +} + +Mounter::OpenItem const* Mounter::openItemAt(std::vector const& kept, std::span path) { + OpenItem const* found = nullptr; + std::vector const* level = &kept; + for (std::size_t const index : path) { + if (index >= level->size()) { + return nullptr; + } + found = &level->at(index); + level = &found->items; + } + return found; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one seam per configuring callback. +void Mounter::bindTableConfig(reactive::Scope& scope, Table const& spec, TableWidget& widget, + std::function focusCell) { + auto const open = std::make_shared(); + if (spec.menu || spec.headerEntries) { + // The entries are read when a menu opens, as a callback is: untracked, an exception reported. While the + // header is disabled every built-in entry of a column's menu is, since each sorts, filters or arranges. + widget.setMenu( + [runtime = _rt, entries = spec.menu, extra = spec.headerEntries, enabled = spec.headerEnabled, + open](std::optional column) { + std::vector shown; + static_cast(runCallback(*runtime, [&] { + if (entries) { + shown = entries(column); + } + if (!column) { + return; + } + if (!enabled.evaluate()) { + for (MenuEntry& entry : shown) { + entry.enabled = false; + } + } + open->headerColumn = column; + open->builtIn = shown.size(); + open->header.clear(); + if (!extra) { + return; + } + std::vector added; + readMenuItems(extra(*column), added, open->header); + if (added.empty()) { + return; + } + if (!shown.empty()) { + shown.push_back(MenuEntry{.separator = true}); + } + open->headerOffset = shown.size(); + std::ranges::move(added, std::back_inserter(shown)); + })); + return shown; + }, + [runtime = _rt, chosen = event(spec.onMenu), open](std::optional column, + std::vector path) { + bool const builtIn = !column || open->headerColumn != column || path.empty() || + path.front() < open->builtIn || open->header.empty(); + if (builtIn) { + if (chosen) { + chosen(column, std::move(path)); + } + return; + } + if (path.front() < open->headerOffset) { + return; + } + path.front() -= open->headerOffset; + OpenItem const* const item = openItemAt(open->header, path); + if (item != nullptr && item->onSelect && item->items.empty()) { + Action const run = item->onSelect; + static_cast(runCallback(*runtime, run)); + } + }); + } + if (spec.cellMenu) { + widget.setCellMenu( + [runtime = _rt, entries = spec.cellMenu, open, focusCell](Key const& row, std::size_t column) { + std::vector shown; + static_cast(runCallback(*runtime, [&] { + if (focusCell) { + focusCell(row, column); + } + open->cell = std::pair{row, column}; + open->cellItems.clear(); + readMenuItems(entries(row, column), shown, open->cellItems); + })); + return shown; + }, + [runtime = _rt, open](Key const& row, std::size_t column, std::vector const& path) { + if (open->cell != std::pair{row, column}) { + return; + } + OpenItem const* const item = openItemAt(open->cellItems, path); + if (item != nullptr && item->onSelect && item->items.empty()) { + Action const run = item->onSelect; + static_cast(runCallback(*runtime, run)); + } + }); + widget.setCellMenuKeys(spec.cellMenuKeys); + } + if (spec.onColumnMove) { + widget.setOnColumnMove(event(spec.onColumnMove)); + } + if (spec.onColumnResize) { + widget.setOnColumnResize(event(spec.onColumnResize)); + } + if (spec.onFilter) { + widget.setOnFilter(event(spec.onFilter)); + } + if (spec.filtered.isBound() || !spec.filtered.constant().empty()) { + bind(scope, spec.filtered, + [&widget](std::vector const& columns) { widget.setFiltered(columns); }); + } + if (spec.columnGroups.isBound() || !spec.columnGroups.constant().empty()) { + bind(scope, spec.columnGroups, + [&widget](std::vector const& groups) { widget.setColumnGroups(groups); }); + } + if (spec.onGroupFilter) { + widget.setOnGroupFilter(event(spec.onGroupFilter)); + } + if (spec.onCopy) { + widget.setOnCopy(event(spec.onCopy)); + } +} + +void Mounter::bindSelectionView(reactive::Scope& scope, Table const& spec, TableWidget& widget, bool& viewing) { + if (spec.onStatusEntry) { + widget.setOnStatusEntry(event(spec.onStatusEntry)); + } + if (!spec.selectionView.isBound() && !spec.selectionView.constant()) { + return; + } + bind(scope, spec.selectionView, + [this, &widget, &viewing, selection = spec.selection](std::optional> const& except) { + if (except) { + viewing = true; + widget.setSelectionView(*except); + return; + } + if (!viewing) { + return; + } + viewing = false; + widget.setSelection(selection.isBound() ? _rt->untracked([&] { return selection.binding()(); }) + : selection.constant()); + }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): mounts each table spec kind (rows, source, model) against one widget, in the order the rows then the selection must bind +Widget& Mounter::mountKind(reactive::Scope& scope, Table const& spec, ContainerWidget* parent) { + if (spec.source) { + return mountSourceTable(scope, spec, parent); + } + TableWidget& widget = scope.adopt(_backend->createTable(parent)); + applyCommon(scope, widget, spec.common); + checkNoShare(spec.columns); + widget.setColumns(spec.columns); + widget.setShowHeader(spec.showHeader); + widget.setSelectionMode(spec.selectionMode); + if (spec.selectColumn) { + widget.setSelectColumn(true); + bind(scope, spec.selectAllLabel, [&widget](std::string const& label) { widget.setSelectAllLabel(label); }); + } + widget.setOnActivate(event(spec.onActivate)); + if (spec.onSelectAll) { + widget.setOnSelectAll(event(spec.onSelectAll)); + } + bool const sortable = std::ranges::any_of(spec.columns, &TableColumn::sortable); + reactive::Computed> const* sortValue = nullptr; + if (sortable) { + sortValue = bind(scope, spec.sort, [&widget](std::vector const& chain) { widget.setSort(chain); }); + widget.setOnSort(event(spec.onSort)); + } + bindTableConfig(scope, spec, widget); + auto& spans = scope.make(); + spans.columns = spec.columns.size(); + spans.threshold = spec.virtualize.threshold; + // The sort counts where it is wired: a table with no sortable column shows no sort. It is read inside the + // rows Effect, not in an Effect of its own, so that two Effects cannot resolve the spans in either order, + // one of them against the wrong rows. A sort bound to a server query can still clear before the rows reorder. + spans.sorted = sortable && sortValue == nullptr && !spec.sort.constant().empty(); + mountRows( + scope, spec.rows, widget, + [this, &widget, &spans](reactive::Scope& rowScope, Node const& node, Widget& rowWidget, Key const& key) { + widget.setRowKey(rowWidget, key); + // A row's tone binds in the row's scope, after its key and whether it is a heading. + Row const* const view = node ? std::get_if(&node->kind) : nullptr; + if (view != nullptr && view->heading) { + widget.setRowHeading(rowWidget); + } + if (view != nullptr && (view->heading || view->spans)) { + spans.rows[key].heading = view->heading; + if (view->spans) { + bind(rowScope, *view->spans, [this, &widget, &spans, key](std::vector const& asked) { + spans.rows[key].requested = asked; + spans.anyAsked = spans.anyAsked || !asked.empty(); + resolveSpans(widget, spans); + }); + } + } + if (view != nullptr && view->tone) { + bind(rowScope, *view->tone, + [&widget, &rowWidget](std::optional const& tone) { widget.setRowTone(rowWidget, tone); }); + } + if (view != nullptr && view->label) { + bind(rowScope, *view->label, + [&widget, &rowWidget](std::string const& label) { widget.setRowLabel(rowWidget, label); }); + } + }, + &spec.virtualize, + RowsObserver{.track = + [&spans, sortValue] { + if (sortValue != nullptr) { + spans.sorted = !sortValue->get().empty(); + } + }, + .begin = [&spans] { ++spans.reconciling; }, + .end = + [this, &widget, &spans](std::vector const& rows) { + --spans.reconciling; + spans.order.clear(); + for (KeyedRow const& row : rows) { + spans.order.push_back( + {.key = row.key, + .widget = row.widgetState == RowWidgetState::Realized ? row.widget : nullptr}); + } + std::unordered_set present; + for (KeyedRow const& row : rows) { + present.insert(row.key); + } + std::erase_if(spans.rows, + [&present](auto const& entry) { return !present.contains(entry.first); }); + resolveSpans(widget, spans); + }}); + // While the selection is of the view the backend marks it, and the key list it holds is not sent over it. + auto& viewing = scope.make(false); + widget.setOnSelectionChange(inputEvent( + spec.onSelectionChange, controlled(scope, spec.selection, [&widget, &viewing](std::vector const& keys) { + if (!viewing) { + widget.setSelection(keys); + } + }))); + bindSelectionView(scope, spec, widget, viewing); + return widget; +} + +void Mounter::reconcileWindowed(std::size_t depth, ForEachSession& session, KeyedRows& rows, + ContainerWidget& container, TableWidget& table, std::vector const& keys, + RowHook const& onRow, VisibleRange const& window, Virtualization const& setting, + bool windowed) { + if (keys.size() < setting.threshold) { + reconcile(depth, session, rows.list, container, keys, onRow); + if (windowed) { + // Rows released while the table was windowed come back: below the threshold every row is realized. + applyWindow(depth, rows.list, container, {.first = 0, .count = rows.list.size()}, 0, onRow); + } + return; + } + std::pair const windowAndOverscan{window, setting.overscan}; + reconcile(depth, session, rows.list, container, keys, onRow, &windowAndOverscan); + // The kept rows have new view positions, and reconcile realizes only new keys: apply the window again so the + // realized rows are the ones now at the window's view positions. + applyWindow(depth, rows.list, container, window, setting.overscan, onRow); + // Only above threshold: a backend's own selection-filtering logic may need to know a key still exists even + // without a realized row for it right now (backend.hpp's setExistingKeys). Below threshold every key already + // has a realized row, so this would add nothing. + table.setExistingKeys(keys); +} + +void Mounter::publishRealizedWindow(TableWidget& table, KeyedRows const& rows, std::size_t keyCount, + Virtualization const& setting, bool& windowed) { + if (keyCount >= setting.threshold) { + auto const [first, count] = realizedExtent(rows.list); + table.setRealizedWindow(first, count, rows.list.size()); + windowed = true; + } else if (windowed) { + table.setRealizedWindow(0, rows.list.size(), rows.list.size()); + windowed = false; + } +} + +Mounter::SourceTable::~SourceTable() { + // The rows' widgets go one by one, and the backend measures the table as they do: `closing` ends every + // window pass that asks, since the span table and whatever else the mount made after this one is gone. + closing = true; + focusLocate.request_stop(); + while (!realized.empty()) { + realized.pop_back(); + } +} + +CellLoad Mounter::cellLoadOf(SourceTable const& table, table::UnloadedLevels const& levels, std::size_t column) { + if (column >= table.source.levels.size() || table.source.levels.at(column).empty()) { + return CellLoad::Loaded; + } + std::string const& level = table.source.levels.at(column); + if (std::ranges::contains(levels.failed, level)) { + return CellLoad::Failed; + } + return std::ranges::contains(levels.levels, level) ? CellLoad::Unloaded : CellLoad::Loaded; +} + +Mounter::SourceTable::PoolKey Mounter::poolOf(SourceTable const& table, std::size_t column) { + bool const own = !table.source.defaultCellView || + (column < table.source.ownCell.size() ? table.source.ownCell.at(column) : true); + if (own) { + return {false, column}; + } + return {true, static_cast(table.columns.at(column).role)}; +} + +int Mounter::contentWidthOf(ColumnMeasure const& known, TableMeasure const& measure) { + int const measured = std::max(known.natural, known.header); + return measured > 0 ? measured : measure.contentEstimate; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): takes a new arrangement: the visible columns, their places and their widths, declared and user's, each step reading the previous one's result +void Mounter::arrange(SourceTable& table, TableArrangement arrangement) { + table.arrangement = std::move(arrangement); + std::vector const before = std::exchange(table.visible, {}); + table.placeOf.assign(table.columns.size(), std::nullopt); + auto const add = [&table](std::size_t column) { + if (column < table.columns.size() && !table.placeOf.at(column)) { + table.placeOf.at(column) = table.visible.size(); + table.visible.push_back(column); + } + }; + if (table.arrangement.visible.empty()) { + for (std::size_t column = 0; column < table.columns.size(); ++column) { + add(column); + } + } else { + for (std::size_t const column : table.arrangement.visible) { + add(column); + } + } + if (table.visible != before || !table.visibleTold) { + table.visibleTold = true; + table.widget->setVisibleColumns(table.visible); + } + // Widths in the backend's measure: a fixed column's units and a user's width scaled by it, with the padding a + // column takes beyond its content, a content column from the backend's estimate. Monospace characters are + // rounded up, so a column of n of them never cuts the last. + TableMeasure const measure = table.widget->tableMeasure(); + table.measure = measure; + table.measures.resize(table.columns.size()); + auto const scaled = [&measure, &table](std::size_t column, int units) { + bool const mono = table.columns.at(column).role == TextRole::Mono; + double const content = units * (mono ? measure.monoUnit : measure.unit); + return (mono ? static_cast(std::ceil(content)) : static_cast(std::lround(content))) + + measure.padding; + }; + std::vector widths; + widths.reserve(table.visible.size()); + for (std::size_t const column : table.visible) { + Sizing const& width = table.columns.at(column).width; + ColumnMeasure const& known = table.measures.at(column); + widths.push_back(width.kind == Sizing::Kind::Fixed ? scaled(column, width.amount) + : contentWidthOf(known, measure)); + } + table.extents->assign(widths); + table.stretchPlaces.clear(); + for (std::size_t place = 0; place < table.visible.size(); ++place) { + std::size_t const column = table.visible.at(place); + if (table.columns.at(column).width.kind == Sizing::Kind::Stretch && + !table.arrangement.widths.contains(column)) { + table.stretchPlaces.push_back(place); + } + } + table.stretchDirty = true; + if (table.spans != nullptr) { + table.spans->placeOf = table.placeOf; + } + for (auto const& [column, width] : table.arrangement.widths) { + if (column < table.placeOf.size()) { + if (auto const place = table.placeOf.at(column)) { + table.extents->set(*place, scaled(column, width)); + } + } + } + table.windowDirty = true; +} + +std::vector Mounter::fetchedOf(SourceTable const& table) { + std::vector ids = table.source.alwaysFetched; + auto const add = [&ids](std::string const& columnId) { + if (!columnId.empty() && !std::ranges::contains(ids, columnId)) { + ids.push_back(columnId); + } + }; + for (std::size_t const column : table.window) { + add(table.columns.at(column).id); + if (column < table.source.cellReads.size()) { + for (std::string const& columnId : table.source.cellReads.at(column)) { + add(columnId); + } + } + } + return ids; +} + +VisibleRange Mounter::shownOf(SourceTable const& table) { + return table.range.count > 0 || !table.source.alwaysWindowed + ? table.range + : VisibleRange{.first = 0, .count = table.virtualize.overscan}; +} + +void Mounter::tellVisible(SourceTable& table) { + VisibleRange const shown = shownOf(table); + table.source.rows->visible(static_cast(shown.first), static_cast(shown.count), + table.fetched); +} + +void Mounter::refreshColumns(SourceTable& table, std::size_t rows) { + if (table.stretchDirty) { + fitStretch(table); + } + bool const windowed = + table.horizontal && windowingOf(table.virtualize, rows, table.visible.size(), /*serverMode*/ true).columns; + if (!table.windowDirty && windowed == table.windowedColumns) { + return; + } + table.windowDirty = false; + table.windowedColumns = windowed; + ColumnExtents const& extents = *table.extents; + std::size_t pinned = std::min(table.arrangement.pinned, table.visible.size()); + // Pinned columns wider than half the viewport leave the last of them to scroll with the rest; the + // arrangement keeps its count. + if (table.horizontal) { + while (pinned > 0 && extents.offsetOf(pinned) > table.viewport / 2) { + --pinned; + } + } + std::vector places; + if (windowed) { + places = columnWindow(extents, pinned, table.scrollX, table.viewport, table.virtualize.columnOverscan).columns; + } else { + places.resize(table.visible.size()); + // NOLINTNEXTLINE(modernize-use-ranges): std::ranges::iota is missing from Emscripten's libc++. + std::iota(places.begin(), places.end(), std::size_t{0}); + } + std::vector window; + window.reserve(places.size() + 1); + for (std::size_t const place : places) { + window.push_back(table.visible.at(place)); + } + tellBands(table, places, pinned); + // The focused column stays realized whatever the scroll. + std::optional const focusPlace = + table.focused && table.focusColumn < table.placeOf.size() ? table.placeOf.at(table.focusColumn) : std::nullopt; + if (focusPlace && !std::ranges::contains(window, table.focusColumn)) { + window.push_back(table.focusColumn); + places.push_back(*focusPlace); + } + bool const changed = window != table.window || pinned != table.pinnedShown; + table.window = std::move(window); + table.pinnedShown = pinned; + if (arranged(table)) { + std::vector offsets; + std::vector widths; + offsets.reserve(places.size()); + widths.reserve(places.size()); + for (std::size_t const place : places) { + offsets.push_back(extents.offsetOf(place)); + widths.push_back(extents.widthOf(place)); + } + table.widget->setColumnWindow(table.window, offsets, widths, extents.totalWidth(), table.pinnedShown); + } + if (changed) { + std::vector fetched = fetchedOf(table); + if (fetched != table.fetched) { + table.fetched = std::move(fetched); + if (table.mounted) { + tellVisible(table); + } + } + } +} + +std::size_t Mounter::firstFullPlace(SourceTable const& table) { + ColumnExtents const& extents = *table.extents; + std::size_t firstFull = extents.columnsAt(table.scrollX, 1).first; + if (extents.offsetOf(firstFull) < table.scrollX) { + ++firstFull; + } + return std::max(firstFull, table.pinnedShown); +} + +void Mounter::fitStretch(SourceTable& table) { + table.stretchDirty = false; + if (!table.horizontal || table.stretchPlaces.empty()) { + return; + } + ColumnExtents& extents = *table.extents; + int const shrinkFloor = table.measure.shrinkFloor; + std::vector columns; + columns.reserve(table.stretchPlaces.size()); + std::int64_t held = 0; + for (std::size_t const place : table.stretchPlaces) { + TableColumn const& column = table.columns.at(table.visible.at(place)); + ColumnMeasure const& known = table.measures.at(table.visible.at(place)); + int const natural = std::max(known.header, known.natural); + columns.push_back(StretchColumn{.natural = natural, + .least = column.wrap ? std::max(known.header, known.least) : natural, + .floor = column.shrink ? std::min(known.header, shrinkFloor) : known.header, + .weight = column.width.amount, + .shrink = column.shrink}); + held += extents.offsetOf(place + 1) - extents.offsetOf(place); + } + std::int64_t const room = std::int64_t{table.viewport} - (extents.totalWidth() - held); + std::vector const widths = + stretchWidths(columns, static_cast(std::clamp(room, 0, std::numeric_limits::max()))); + std::size_t const firstFull = firstFullPlace(table); + int moved = 0; + bool changed = false; + for (auto const [place, width] : std::views::zip(table.stretchPlaces, widths)) { + int const before = extents.offsetOf(place + 1) - extents.offsetOf(place); + if (extents.fit(place, width)) { + changed = true; + if (place >= table.pinnedShown && place < firstFull) { + moved += width - before; + } + } + } + if (!changed) { + return; + } + table.windowDirty = true; + if (moved != 0) { + table.scrollX = std::max(table.scrollX + moved, 0); + table.widget->setHorizontalOffset(table.scrollX); + } +} + +void Mounter::tellBands(SourceTable& table, std::vector const& places, std::size_t pinned) { + if (table.bands.empty()) { + return; + } + std::vector ids; + ids.reserve(table.visible.size()); + for (std::size_t const column : table.visible) { + ids.push_back(table.columns.at(column).id); + } + std::vector inWindow(table.visible.size(), false); + for (std::size_t const place : places) { + inWindow.at(place) = true; + } + std::vector runs; + for (BandRun const& run : bandRuns(table.bands, ids, pinned)) { + std::optional first; + for (std::size_t at = run.first; at <= run.first + run.count; ++at) { + bool const shown = at < run.first + run.count && inWindow.at(at); + if (shown && !first) { + first = at; + } else if (!shown && first) { + BandRun part = run; + part.first = *first; + part.count = at - *first; + runs.push_back(std::move(part)); + first.reset(); + } + } + } + if (!table.bandsTold || *table.bandsTold != runs) { + table.widget->setBands(runs); + table.bandsTold = std::move(runs); + } +} + +Mounter::SourceTable::Cell Mounter::makeCell(SourceTable& table, SourceTable::Realized& row, std::size_t column, + Value const& record) { + SourceTable::Cell cell; + cell.pool = poolOf(table, column); + cell.scope = std::make_unique(*_rt, table.depth + 1); + reactive::Scope& scope = *cell.scope; + cell.row = &scope.make>(*_rt, record); + Node made; + if (cell.pool.first) { + cell.column = &scope.make>(*_rt, column); + made = table.source.defaultCellView(*cell.column, *cell.row); + } else { + made = table.source.cellView(column, *cell.row); + } + Node const& node = scope.make(std::move(made)); + auto* const stack = dynamic_cast(row.widget); + // A marked cell's content is the cell, which may be accented; an accented cell mounts its content as the + // cell. The marks and the accent are bound in the cell's scope and told once the cell is attached to a row + // (`realizeCell`), so a cell built for a pool tells nothing yet. + MarkedCell const* const marked = node ? std::get_if(&node->kind) : nullptr; + Node const& inner = marked != nullptr ? marked->content : node; + AccentedCell const* const accented = inner ? std::get_if(&inner->kind) : nullptr; + Widget* const widget = inner ? mount(scope, accented != nullptr ? accented->content : inner, stack) + : &scope.adopt(_backend->createSpacer(stack)); + if (marked != nullptr) { + auto& marks = scope.make(); + cell.marks = &marks; + bind(scope, marked->marks, [&table, &marks](CellMarks const& value) { + marks.last = value; + if (marks.row != nullptr) { + table.widget->setCellMarks(*marks.row, marks.column, value); + } + }); + } + if (accented != nullptr) { + auto& accent = scope.make(); + cell.accent = &accent; + bind(scope, accented->accent, [&table, &accent](CellAccent const& value) { + accent.last = value; + if (accent.row != nullptr) { + table.widget->setCellAccent(*accent.row, accent.column, value); + } + }); + } + cell.widget = widget; + row.children.push_back(widget); + ++_stats.cellsCreated; + return cell; +} + +void Mounter::setRecord(reactive::Signal& signal, Value const& record) { + if (signal.peek() != record) { + ++_stats.cellBinds; + signal.set(record); + } +} + +void Mounter::assignRow(SourceTable& table, SourceTable::Realized& slot, std::int64_t index, TableRowRef const& ref) { + if (slot.key && *slot.key != ref.key) { + closeEditor(table, slot); + dropRowScoped(table, slot); + } + slot.index = index; + slot.key = ref.key; + if (slot.row->peek() != ref.row) { + ++_stats.rowBinds; + slot.row->set(ref.row); + } + if (slot.headingWidget != nullptr) { + std::erase(slot.children, slot.headingWidget); + slot.headingWidget = nullptr; + } + slot.look.reset(); + slot.look = std::make_unique(*_rt, table.depth + 1); + reactive::Scope& lookScope = *slot.look; + TableRowLook look; + if (table.source.rowView) { + look = table.source.rowView(*slot.row); + lookScope.make>(look.keep); + } + table.widget->setRowKey(*slot.widget, *slot.key); + slot.summary = look.summary; + if (look.summary) { + table.widget->setRowSummary(*slot.widget); + } + slot.heading = look.heading != nullptr; + if (slot.heading) { + Node const& heading = lookScope.make(look.heading); + if (Widget* const made = mount(lookScope, heading, dynamic_cast(slot.widget))) { + slot.children.push_back(made); + slot.headingWidget = made; + } + table.widget->setRowHeading(*slot.widget); + } + if (table.spans != nullptr && (look.heading || look.spans)) { + SpanTable& spans = *table.spans; + spans.rows[*slot.key].heading = static_cast(look.heading); + if (look.spans) { + bind(lookScope, *look.spans, [this, &table, &spans, key = *slot.key](std::vector const& asked) { + spans.rows[key].requested = asked; + spans.anyAsked = spans.anyAsked || !asked.empty(); + resolveSpans(*table.widget, spans); + }); + } + } + if (look.tone) { + bind(lookScope, *look.tone, [&table, widget = slot.widget](std::optional const& tone) { + table.widget->setRowTone(*widget, tone); + }); + } + if (look.label) { + bind(lookScope, *look.label, + [&table, widget = slot.widget](std::string const& label) { table.widget->setRowLabel(*widget, label); }); + } + if (look.marks) { + bind(lookScope, *look.marks, + [&table, widget = slot.widget](RowMarks const& marks) { table.widget->setRowMarks(*widget, marks); }); + } + if (look.modified) { + bind(lookScope, *look.modified, + [&table, widget = slot.widget](bool modified) { table.widget->setRowModified(*widget, modified); }); + } + for (auto& [column, placed] : slot.cells) { + placed.fresh = false; + } +} + +void Mounter::closeEditor(SourceTable& table, SourceTable::Realized& slot) { + if (slot.editor == nullptr) { + return; + } + Widget const* const editor = std::exchange(slot.editorWidget, nullptr); + table.widget->setCellEditor(*slot.widget, slot.editorColumn, nullptr); + std::erase(slot.children, editor); + slot.editor.reset(); +} + +void Mounter::syncEditor(SourceTable& table) { + std::optional column; + if (table.editWanted) { + auto const found = std::ranges::find(table.columns, table.editWanted->column, &TableColumn::id); + if (found != table.columns.end()) { + column = static_cast(found - table.columns.begin()); + } + } + for (SourceTable::Realized& slot : table.realized) { + bool const wanted = + column && slot.key && table.editWanted && *slot.key == table.editWanted->key && !slot.heading; + if (slot.editor != nullptr && (!wanted || slot.editorColumn != *column)) { + closeEditor(table, slot); + } + if (!wanted || slot.editor != nullptr || !table.editor) { + continue; + } + auto scope = std::make_unique(*_rt, table.depth + 1); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): `wanted` holds only while an edit is wanted. + Node const& node = scope->make(table.editor(*table.editWanted)); + Widget* const made = + mountPass([&] { return mount(*scope, node, dynamic_cast(slot.widget)); }); + if (made == nullptr) { + continue; + } + slot.editor = std::move(scope); + slot.editorWidget = made; + slot.editorColumn = *column; + slot.children.push_back(made); + table.widget->setCellEditor(*slot.widget, *column, made); + try { + made->focus(); + } catch (...) { // NOLINT(bugprone-empty-catch) + // Focus is a request: a backend that cannot move it leaves it where it was. + } + } +} + +Mounter::SourceTable::Realized Mounter::makeRow(SourceTable& table, std::int64_t index) { + SourceTable::Realized made; + made.index = index; + made.scope = std::make_unique(*_rt, table.depth); + StackWidget& stack = made.scope->adopt(_backend->createStack(table.widget, Axis::Horizontal)); + made.scope->make(_offChain, &stack); + made.widget = &stack; + std::optional const ref = table.source.rows->row(index); + made.row = &made.scope->make>(*_rt, ref ? ref->row : Value{}); + if (ref) { + assignRow(table, made, index, *ref); + } + return made; +} + +void Mounter::park(SourceTable& table, SourceTable::Realized& slot, std::size_t column) { + auto const found = slot.cells.find(column); + if (found == slot.cells.end()) { + return; + } + SourceTable::Cell cell = std::move(found->second.cell); + slot.cells.erase(found); + if (cell.accent != nullptr) { + cell.accent->row = nullptr; + } + if (cell.marks != nullptr) { + cell.marks->row = nullptr; + } + table.widget->setCellColumn(*slot.widget, *cell.widget, std::nullopt); + slot.pool[cell.pool].push_back(std::move(cell)); +} + +void Mounter::realizeCell(SourceTable& table, SourceTable::Realized& slot, std::size_t column, Value const& record) { + if (auto const placed = slot.cells.find(column); placed != slot.cells.end()) { + setRecord(*placed->second.cell.row, record); + placed->second.fresh = true; + ++_stats.cellsRebound; + return; + } + SourceTable::PoolKey const key = poolOf(table, column); + SourceTable::Cell cell; + if (auto const pooled = slot.pool.find(key); pooled != slot.pool.end() && !pooled->second.empty()) { + cell = std::move(pooled->second.back()); + pooled->second.pop_back(); + if (cell.accent != nullptr) { + cell.accent->row = nullptr; + } + if (cell.marks != nullptr) { + cell.marks->row = nullptr; + } + if (cell.column != nullptr && cell.column->peek() != column) { + cell.column->set(column); + } + setRecord(*cell.row, record); + ++_stats.cellsRebound; + } else { + cell = mountPass([&] { return makeCell(table, slot, column, record); }); + } + table.widget->setCellColumn(*slot.widget, *cell.widget, column); + // Attached to this row at this column: the accent is told here whether or not it changed. + if (cell.accent != nullptr) { + cell.accent->row = slot.widget; + cell.accent->column = column; + table.widget->setCellAccent(*slot.widget, column, cell.accent->last); + } + // The marks likewise: a cell rebound to another row re-evaluates them with its content, and this row is told + // them even when they equal the ones it showed. + if (cell.marks != nullptr) { + cell.marks->row = slot.widget; + cell.marks->column = column; + table.widget->setCellMarks(*slot.widget, column, cell.marks->last); + } + slot.cells.emplace(column, SourceTable::Placed{.cell = std::move(cell), .fresh = true}); +} + +void Mounter::tellLoads(SourceTable& table, SourceTable::Realized& slot) { + table::UnloadedLevels const levels = table.source.rows->unloadedLevels(slot.index); + for (auto const& [column, placed] : slot.cells) { + if (!placed.fresh) { + continue; + } + CellLoad const load = cellLoadOf(table, levels, column); + auto const [was, made] = slot.loads.try_emplace(column, CellLoad::Loaded); + if (was->second != load) { + was->second = load; + table.widget->setCellLoad(*slot.widget, column, load); + } + } +} + +void Mounter::realizeWindow(SourceTable& table, std::function const& updated) { + if (table.closing) { + return; + } + if (table.realizing) { + table.realizeAgain = true; + return; + } + table.realizing = true; + try { + realizeWindowPass(table, updated); + while (std::exchange(table.realizeAgain, false) && !table.closing) { + realizeWindowPass(table, [](std::int64_t) { return true; }); + } + } catch (...) { + table.realizing = false; + table.realizeAgain = false; + throw; + } + table.realizing = false; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): rows, cells, the budget, focus and the reports. +void Mounter::realizeWindowPass(SourceTable& table, std::function const& updated) { + TableRows const& rows = *table.source.rows; + TableTotal const total = rows.mountedTotal(); + auto const count = static_cast(std::max(total.rows, 0)); + refreshColumns(table, count); + // A short table over a document's rows realizes every row. A windowed one realizes the rows in view and + // `overscan` either side. + bool const everyRow = !table.source.alwaysWindowed && count < table.virtualize.threshold; + VisibleRange const shown = shownOf(table); + std::size_t const overscan = table.virtualize.overscan; + std::size_t const low = everyRow || shown.first <= overscan ? 0 : shown.first - overscan; + std::size_t const high = everyRow ? count : std::min(count, shown.first + shown.count + overscan); + std::vector targets; + targets.reserve(high > low ? high - low + 1 : 1); + for (std::size_t at = low; at < high; ++at) { + targets.push_back(static_cast(at)); + } + // The focused row stays realized: one row beyond the window at most. + if (table.focused && table.focusIndex >= 0 && std::cmp_less(table.focusIndex, count) && + (std::cmp_less(table.focusIndex, low) || std::cmp_greater_equal(table.focusIndex, high))) { + targets.insert(std::ranges::upper_bound(targets, table.focusIndex), table.focusIndex); + } + if (table.spans != nullptr) { + ++table.spans->reconciling; + } + std::vector old = std::move(table.realized); + table.realized.clear(); + std::unordered_map keyed; + std::unordered_map placeholders; + for (std::size_t at = 0; at < old.size(); ++at) { + if (old.at(at).key) { + keyed.emplace(*old.at(at).key, at); + } else { + placeholders.emplace(old.at(at).index, at); + } + } + std::vector current; + current.reserve(old.size()); + for (SourceTable::Realized const& row : old) { + current.push_back(row.widget); + } + std::vector> match(targets.size()); + std::vector taken(old.size(), false); + for (std::size_t at = 0; at < targets.size(); ++at) { + std::optional const ref = rows.row(targets.at(at)); + if (ref) { + if (auto const found = keyed.find(ref->key); found != keyed.end() && !taken.at(found->second)) { + match.at(at) = found->second; + } + } else if (auto const found = placeholders.find(targets.at(at)); + found != placeholders.end() && !taken.at(found->second)) { + match.at(at) = found->second; + } + if (match.at(at)) { + taken.at(*match.at(at)) = true; + } + } + // Slots no row kept, for the rows that enter: keyed ones only for a keyed row, so no stack keeps a key it no + // longer shows; a placeholder's for either. A heading's or a summary row's slot is never given another row: + // the backend has no call that makes a row a data row again, so it goes, and the entering row gets a new one. + std::vector freeKeyed; + std::vector freePlain; + for (std::size_t at = old.size(); at-- > 0;) { + if (!taken.at(at) && !old.at(at).heading && !old.at(at).summary) { + (old.at(at).key ? freeKeyed : freePlain).push_back(at); + } + } + std::exception_ptr failure; + std::vector next; + next.reserve(targets.size()); + std::vector const moved; + for (std::size_t at = 0; at < targets.size(); ++at) { + std::int64_t const index = targets.at(at); + std::optional const ref = rows.row(index); + if (match.at(at)) { + SourceTable::Realized row = std::move(old.at(*match.at(at))); + bool const shifted = row.index != index; + row.index = index; + if (ref && (shifted || updated(index))) { + if (row.row->peek() != ref->row) { + ++_stats.rowBinds; + row.row->set(ref->row); + } + for (auto& [column, placed] : row.cells) { + if (placed.fresh) { + setRecord(*placed.cell.row, ref->row); + } + } + } + next.push_back(std::move(row)); + continue; + } + try { + std::vector* pool = !freePlain.empty() ? &freePlain : nullptr; + if (ref && !freeKeyed.empty()) { + pool = &freeKeyed; + } + if (pool != nullptr) { + SourceTable::Realized row = std::move(old.at(pool->back())); + pool->pop_back(); + row.index = index; + if (ref) { + mountPass([&] { + assignRow(table, row, index, *ref); + return 0; + }); + } + next.push_back(std::move(row)); + } else { + next.push_back(mountPass([&] { return makeRow(table, index); })); + current.push_back(next.back().widget); + } + } catch (...) { + if (!failure) { + failure = std::current_exception(); + } + } + } + // What was not taken goes, last first; the container forgets its widgets. + for (SourceTable::Realized& row : old | std::views::reverse) { + if (row.scope) { + std::erase(current, row.widget); + row.editor.reset(); + row.pool.clear(); + row.cells.clear(); + row.look.reset(); + row.scope.reset(); + } + } + std::vector target; + target.reserve(next.size()); + for (SourceTable::Realized const& row : next) { + target.push_back(row.widget); + } + try { + reorderChildren(*table.widget, current, target); + } catch (...) { + if (!failure) { + failure = std::current_exception(); + } + } + table.realized = std::move(next); + for (SourceTable::Realized& row : table.realized) { + if (row.toldIndex != row.index) { + row.toldIndex = row.index; + table.widget->setRowIndex(*row.widget, static_cast(row.index)); + } + } + if (!table.source.alwaysWindowed && !everyRow) { + // A backend's own selection needs to know a key exists without a realized row for it. + std::vector keys; + keys.reserve(count); + for (std::size_t at = 0; at < count; ++at) { + if (std::optional const ref = rows.row(static_cast(at))) { + keys.push_back(ref->key); + } + } + table.widget->setExistingKeys(keys); + } + if (table.spans != nullptr) { + SpanTable& spans = *table.spans; + --spans.reconciling; + spans.windowed = !everyRow; + spans.order.clear(); + std::unordered_set present; + for (SourceTable::Realized const& row : table.realized) { + if (row.key) { + spans.order.push_back({.key = *row.key, .widget = row.widget}); + present.insert(*row.key); + } + } + std::erase_if(spans.rows, [&present](auto const& entry) { return !present.contains(entry.first); }); + resolveSpans(*table.widget, spans); + } + realizeCells(table, shown); + syncEditor(table); + // The contiguous range only: a focused row kept beyond it is placed by its own `setRowIndex`. Every source + // table is told it, one that realizes every row as the whole view: a backend takes the view's count from it. + // Whether spans are drawn is the span table's (`SpanTable::windowed`), not this call's. + table.widget->setRealizedWindow(low, high > low ? high - low : 0, count); + afterPass(table, total); + table.lastCount = count; + if (failure) { + std::rethrow_exception(failure); + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): pooling, the budget, and the order in each row. +void Mounter::realizeCells(SourceTable& table, VisibleRange const& shown) { + TableRows const& rows = *table.source.rows; + std::unordered_set const inWindow(table.window.begin(), table.window.end()); + auto const centreRow = static_cast(shown.first + (shown.count / 2)); + std::size_t const centreColumn = table.window.empty() ? 0 : table.window.size() / 2; + std::vector work; + for (std::size_t at = 0; at < table.realized.size(); ++at) { + SourceTable::Realized& slot = table.realized.at(at); + bool const keyed = slot.key.has_value() && !slot.heading; + std::vector leaving; + for (auto const& [column, placed] : slot.cells) { + if (!keyed || !inWindow.contains(column)) { + leaving.push_back(column); + } + } + for (std::size_t const column : leaving) { + park(table, slot, column); + } + // A row the rows do not hold now takes none of the budget: its cells wait for its arrival, which is a + // change of the rows and so a pass of its own. + if (!keyed || !rows.row(slot.index)) { + continue; + } + auto const rowDistance = static_cast(std::abs(slot.index - centreRow)); + for (std::size_t place = 0; place < table.window.size(); ++place) { + std::size_t const column = table.window.at(place); + auto const placed = slot.cells.find(column); + if (placed != slot.cells.end() && placed->second.fresh) { + continue; + } + std::size_t const columnDistance = place > centreColumn ? place - centreColumn : centreColumn - place; + work.push_back( + CellWork{.slot = at, .column = column, .distance = (rowDistance * 1'000'000) + columnDistance}); + } + } + std::ranges::stable_sort(work, {}, &CellWork::distance); + std::size_t const budget = table.virtualize.realizePerFrame; + std::exception_ptr failure; + std::size_t done = 0; + std::unordered_set waiting; + for (std::size_t at = 0; at < work.size(); ++at) { + SourceTable::Realized& slot = table.realized.at(work.at(at).slot); + std::size_t const column = work.at(at).column; + if (at >= budget) { + // Past the budget: a stale cell leaves its column blank rather than show another row. + park(table, slot, column); + waiting.insert(work.at(at).slot); + ++_stats.placeholders; + continue; + } + std::optional const ref = rows.row(slot.index); + if (!ref) { + continue; + } + try { + realizeCell(table, slot, column, ref->row); + ++done; + } catch (...) { + if (!failure) { + failure = std::current_exception(); + } + } + } + for (std::size_t at = 0; at < table.realized.size(); ++at) { + SourceTable::Realized& slot = table.realized.at(at); + // A row with nothing left to realize keeps no pooled cell: the widgets alive are the cells in the window. + if (!waiting.contains(at)) { + dropPools(slot); + } + tellLoads(table, slot); + orderCells(table, slot); + } + // A pass that realized nothing (every build it tried threw) posts no other: it would fail the same way. + if (work.size() > budget && done > 0) { + continueLater(table); + } + if (failure) { + std::rethrow_exception(failure); + } +} + +void Mounter::dropRowScoped(SourceTable const& table, SourceTable::Realized& slot) { + std::erase_if(slot.cells, [&table, &slot](auto const& entry) { + if (!rowScoped(table, entry.first)) { + return false; + } + std::erase(slot.children, entry.second.cell.widget); + return true; + }); + std::erase_if(slot.pool, [&table, &slot](auto const& entry) { + if (entry.first.first || !rowScoped(table, entry.first.second)) { + return false; + } + for (SourceTable::Cell const& cell : entry.second) { + std::erase(slot.children, cell.widget); + } + return true; + }); +} + +void Mounter::dropPools(SourceTable::Realized& slot) { + for (auto& [key, cells] : slot.pool) { + for (SourceTable::Cell const& cell : cells) { + std::erase(slot.children, cell.widget); + } + } + slot.pool.clear(); +} + +void Mounter::orderCells(SourceTable const& table, SourceTable::Realized& slot) { + if (slot.heading || slot.children.empty()) { + return; + } + std::vector target; + target.reserve(slot.children.size()); + for (std::size_t const column : table.window) { + if (auto const placed = slot.cells.find(column); placed != slot.cells.end()) { + target.push_back(placed->second.cell.widget); + } + } + std::ranges::copy_if(slot.children, std::back_inserter(target), + [&target](Widget const* child) { return !std::ranges::contains(target, child); }); + if (target != slot.children) { + reorderChildren(*dynamic_cast(slot.widget), slot.children, target); + } +} + +void Mounter::continueLater(SourceTable& table) { + if (table.continuing) { + return; + } + table.continuing = true; + try { + _rt->owner().post([this, &table, alive = std::weak_ptr{table.alive}] { + if (alive.expired()) { + return; + } + table.continuing = false; + static_cast(runCallback(*_rt, [&] { realizeWindow(table, [](std::int64_t) { return false; }); })); + }); + } catch (...) { + table.continuing = false; + throw; + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity, readability-convert-member-functions-to-static): the pass's reports (counts, focused cell, highlighted row) each read the same table state in turn +void Mounter::afterPass(SourceTable& table, TableTotal const& total) { + std::pair, std::size_t> const counts{ + total.known && total.kind == table::TotalKind::Exact ? std::optional{total.rows} : std::nullopt, + table.visible.size()}; + if (table.counts != counts) { + table.counts = counts; + table.widget->setCounts(counts.first, counts.second); + } + if (table.highlightKey && table.highlightSearching) { + if (std::optional const now = placeOfKey(table, *table.highlightKey, table.highlightIndex)) { + table.highlightSearching = false; + table.highlightIndex = *now; + table.widget->setHighlightedRow(static_cast(*now)); + } + } + if (table.focused && table.focusSearching && table.focusKey) { + if (std::optional const now = placeOfKey(table, *table.focusKey, table.focusIndex)) { + table.focusLocate.request_stop(); + table.focusSearching = false; + table.focusIndex = *now; + table.widget->setFocusCell(static_cast(*now), table.focusColumn); + } + return; + } + if (table.focused && table.focusUntold && total.known) { + if (table.focusLeft) { + table.focusIndex = std::min(table.focusIndex, std::max(total.rows - 1, 0)); + } + if (table.focusIndex < total.rows) { + table.focusUntold = false; + tellLocatedFocus(table); + } + } + if (table.focused && table.focusUnconfirmed && table.focusKey) { + std::optional const ref = table.source.rows->row(table.focusIndex); + std::optional const now = ref && ref->key == *table.focusKey + ? std::optional{table.focusIndex} + : placeOfKey(table, *table.focusKey, table.focusIndex); + if (now) { + table.focusUnconfirmed = false; + table.focusIndex = *now; + table.widget->setFocusCell(static_cast(*now), table.focusColumn); + } + } + if (table.focused) { + std::optional const ref = table.source.rows->row(table.focusIndex); + // The row at the focused index arrived, or took the place of the focused row that left the view; a row + // that is there for any other reason (a reset that moved the focused key away) does not take focus. + if (ref && table.focusKey != ref->key && (!table.focusKey || table.focusLeft)) { + table.focusKey = ref->key; + reportFocus(table); + } + table.focusLeft = table.focusLeft && !ref; + } +} + +void Mounter::locateFocus(SourceTable& table) { + if (!table.focusKey) { + return; + } + table.focusLocate.request_stop(); + table.focusLocate = ::core::async::StopSource{}; + ::core::async::StopToken const stop = table.focusLocate.get_token(); + table.source.rows->locateRow(*table.focusKey, stop, + [this, &table, stop, alive = std::weak_ptr{table.alive}](RowLocation const& found) { + if (alive.expired() || stop.stop_requested()) { + return; + } + static_cast(runCallback(*_rt, [&] { focusLocated(table, found); })); + }); +} + +void Mounter::focusLocated(SourceTable& table, RowLocation const& found) { + if (!table.focused || !table.focusSearching || !found) { + return; + } + table.focusSearching = false; + table.focusUntold = true; + if (*found && **found >= 0) { + table.focusIndex = **found; + } else { + table.focusWas = table.focusKey; + table.focusLeft = true; + } + realizeWindow(table, [](std::int64_t) { return false; }); +} + +void Mounter::tellLocatedFocus(SourceTable& table) { + auto const index = static_cast(table.focusIndex); + // A row held at the located index with another key is of the view before the change that moved the key + // there: the index is scrolled to, so its rows are realized, and focus waits for a realized row to hold the + // key. A row not held names no key, and is fetched. + std::optional const ref = table.source.rows->row(table.focusIndex); + bool const other = !table.focusLeft && table.focusKey && ref && ref->key != *table.focusKey; + if (!table.focusLeft && table.focusKey) { + table.focusUnconfirmed = !ref || other; + } + VisibleRange range = focusRangeOf(table); + if ((!ref || other) && (index < range.first || index >= range.first + range.count)) { + range.first = index < range.first ? index : index + 1 - range.count; + table.range = range; + table.widget->scrollToRow(index); + tellVisible(table); + } + if (!other) { + table.widget->setFocusCell(index, table.focusColumn); + } +} + +void Mounter::reportFocus(SourceTable const& table) { + // A grid holds its own focus: the key that took focus is handed to it, as a gesture's cell is. + if (table.grid) { + if (table.onGridFocus && table.focusColumn < table.columns.size()) { + table.onGridFocus( + GridFocus{.key = table.focusKey, + .viewRow = static_cast(std::max(table.focusIndex, 0)), + .column = table.columns.at(table.focusColumn).id}); + } + return; + } + if (!table.onFocusCell || !table.focusKey) { + return; + } + std::string const& columnId = + table.focusColumn < table.columns.size() ? table.columns.at(table.focusColumn).id : std::string{}; + table.onFocusCell(CellRef{.key = *table.focusKey, .column = columnId}); +} + +} // namespace morph::ui::detail diff --git a/src/ui/mount_3.cpp b/src/ui/mount_3.cpp new file mode 100644 index 000000000..b83a485ed --- /dev/null +++ b/src/ui/mount_3.cpp @@ -0,0 +1,1367 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui::detail { + +std::optional Mounter::followIndex(table::ViewChange const& change, std::int64_t index) { + auto position = static_cast(std::max(index, 0)); + for (table::ViewOp const& op : change.ops) { + switch (op.kind) { + case table::ViewOp::Kind::Removed: + if (position >= op.first && position < op.first + op.count) { + return std::nullopt; + } + if (position >= op.first + op.count) { + position -= op.count; + } + break; + case table::ViewOp::Kind::Inserted: + if (position >= op.first) { + position += op.count; + } + break; + case table::ViewOp::Kind::Moved: + if (position == op.first) { + position = op.to; + } else if (op.first < position && position <= op.to) { + --position; + } else if (op.to <= position && position < op.first) { + ++position; + } + break; + case table::ViewOp::Kind::Reset: + case table::ViewOp::Kind::Changed: + default: + break; + } + } + return static_cast(position); +} + +void Mounter::moveFocus(SourceTable& table, FocusMove move) { + TableTotal const total = table.source.rows->mountedTotal(); + std::int64_t const last = std::max(total.rows - 1, 0); + std::int64_t const page = std::max(static_cast(focusRangeOf(table).count), 1); + std::int64_t index = table.focused ? table.focusIndex : 0; + std::optional const focusPlace = + table.focused && table.focusColumn < table.placeOf.size() ? table.placeOf.at(table.focusColumn) : std::nullopt; + std::size_t place = focusPlace.value_or(0); + std::size_t const lastPlace = table.visible.empty() ? 0 : table.visible.size() - 1; + switch (move) { + case FocusMove::Up: + index = std::max(index - 1, 0); + break; + case FocusMove::Down: + index = std::min(index + 1, last); + break; + case FocusMove::PageUp: + index = std::max(index - page, 0); + break; + case FocusMove::PageDown: + index = std::min(index + page, last); + break; + case FocusMove::Left: + place = place > 0 ? place - 1 : 0; + break; + case FocusMove::Right: + place = std::min(place + 1, lastPlace); + break; + case FocusMove::Home: + place = 0; + break; + case FocusMove::End: + place = lastPlace; + break; + case FocusMove::First: + index = 0; + break; + case FocusMove::Last: + index = last; + // A total that is a lower bound: the last row known. + if (total.kind == table::TotalKind::AtLeast) { + while (index > 0 && !table.source.rows->row(index)) { + --index; + } + } + break; + default: + break; + } + if (table.visible.empty()) { + return; + } + if (table.grid) { + handFocus(table, index, table.visible.at(place)); + return; + } + placeFocus(table, index, table.visible.at(place)); + reportFocus(table); +} + +std::optional Mounter::viewRowOf(SourceTable const& table, Key const& key) { + TableTotal const total = table.source.rows->mountedTotal(); + for (std::int64_t index = 0; index < total.rows; ++index) { + std::optional const ref = table.source.rows->row(index); + if (ref && ref->key == key) { + return static_cast(index); + } + } + return std::nullopt; +} + +void Mounter::showCells(SourceTable& table) { + if (!table.cells) { + return; + } + std::optional> rect; + if (table.cellRange) { + auto const placeOf = [&table](std::string const& columnId) -> std::optional { + auto const column = std::ranges::find(table.columns, columnId, &TableColumn::id); + auto const index = static_cast(column - table.columns.begin()); + return column == table.columns.end() ? std::nullopt : table.placeOf.at(index); + }; + std::optional const anchorRow = viewRowOf(table, table.cellRange->anchor.key); + std::optional const focusRow = viewRowOf(table, table.cellRange->focus.key); + std::optional const anchorPlace = placeOf(table.cellRange->anchor.column); + std::optional const focusPlace = placeOf(table.cellRange->focus.column); + if (anchorRow && focusRow && anchorPlace && focusPlace) { + rect = std::array{ + std::min(*anchorRow, *focusRow), std::max(*anchorRow, *focusRow) - std::min(*anchorRow, *focusRow) + 1, + std::min(*anchorPlace, *focusPlace), + std::max(*anchorPlace, *focusPlace) - std::min(*anchorPlace, *focusPlace) + 1}; + } + } + if (table.cellRectTold && rect == table.cellRect) { + return; + } + table.cellRectTold = true; + table.cellRect = rect; + table.widget->setCellSelection(rect); +} + +std::optional Mounter::cellsAt( + SourceTable const& table, std::size_t anchorRow, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`anchorPlace`, `focusRow`): the selection's anchor then its focus, passed in that order by the one caller + std::size_t anchorPlace, std::size_t focusRow, std::size_t focusPlace) { + auto const cell = [&table](std::size_t row, std::size_t place) -> std::optional { + std::optional const ref = table.source.rows->row(static_cast(row)); + if (!ref || place >= table.visible.size() || table.visible.at(place) >= table.columns.size()) { + return std::nullopt; + } + return CellRef{.key = ref->key, .column = table.columns.at(table.visible.at(place)).id}; + }; + std::optional anchor = cell(anchorRow, anchorPlace); + std::optional focus = cell(focusRow, focusPlace); + if (!anchor || !focus) { + return std::nullopt; + } + return CellRange{.anchor = std::move(*anchor), .focus = std::move(*focus)}; +} + +void Mounter::handFocus(SourceTable const& table, std::int64_t index, std::size_t column) { + if (!table.onGridFocus || column >= table.columns.size()) { + return; + } + std::optional const ref = table.source.rows->row(index); + table.onGridFocus(GridFocus{.key = ref ? std::optional{ref->key} : std::nullopt, + .viewRow = static_cast(std::max(index, 0)), + .column = table.columns.at(column).id}); +} + +void Mounter::gridFocusFrom(SourceTable& table, std::optional const& focus) { + if (!focus) { + return; + } + auto const column = std::ranges::find(table.columns, focus->column, &TableColumn::id); + if (column == table.columns.end()) { + return; + } + auto index = static_cast(focus->viewRow); + if (focus->key) { + std::optional const ref = table.source.rows->row(index); + if (!ref || ref->key != *focus->key) { + index = placeOfKey(table, *focus->key, index).value_or(index); + } + } + placeFocus(table, index, static_cast(column - table.columns.begin())); +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`index`, `column`): row index then column, the order every focus seam in this file uses +void Mounter::placeFocus(SourceTable& table, std::int64_t index, std::size_t column) { + table.focused = true; + table.focusSearching = false; + table.focusUntold = false; + table.focusWas.reset(); + table.focusUnconfirmed = false; + table.focusLocate.request_stop(); + table.focusIndex = index; + table.focusColumn = column; + std::optional const ref = table.source.rows->row(index); + table.focusKey = ref ? std::optional{ref->key} : std::nullopt; + VisibleRange range = focusRangeOf(table); + auto const position = static_cast(index); + if (position < range.first || position >= range.first + range.count) { + range.first = position < range.first ? position : position + 1 - range.count; + table.range = range; + table.widget->scrollToRow(position); + tellVisible(table); + } + table.windowDirty = true; + realizeWindow(table, [](std::int64_t) { return false; }); + table.widget->setFocusCell(position, table.focusColumn); +} + +void Mounter::focusFrom(SourceTable& table, std::optional const& cell) { + if (!cell) { + return; + } + auto const column = std::ranges::find(table.columns, cell->column, &TableColumn::id); + if (column == table.columns.end()) { + return; + } + auto const row = std::ranges::find(table.realized, std::optional{cell->key}, &SourceTable::Realized::key); + if (row == table.realized.end()) { + return; + } + table.focused = true; + table.focusSearching = false; + table.focusUntold = false; + table.focusWas.reset(); + table.focusUnconfirmed = false; + table.focusLocate.request_stop(); + table.focusKey = cell->key; + table.focusIndex = row->index; + table.focusColumn = static_cast(column - table.columns.begin()); + table.windowDirty = true; + realizeWindow(table, [](std::int64_t) { return false; }); + table.widget->setFocusCell(static_cast(table.focusIndex), table.focusColumn); +} + +void Mounter::focusAt(SourceTable& table, Key const& key, std::size_t column) { + if (column >= table.columns.size()) { + return; + } + // The focused cell's own entries, asked for a key, leave the focus and the view where they are. + if (table.focused && table.focusKey == key && table.focusColumn == column) { + return; + } + auto const row = std::ranges::find(table.realized, std::optional{key}, &SourceTable::Realized::key); + if (row == table.realized.end()) { + return; + } + if (table.grid) { + handFocus(table, row->index, column); + return; + } + table.focused = true; + table.focusSearching = false; + table.focusUntold = false; + table.focusWas.reset(); + table.focusUnconfirmed = false; + table.focusLocate.request_stop(); + table.focusKey = key; + table.focusIndex = row->index; + table.focusColumn = column; + table.windowDirty = true; + realizeWindow(table, [](std::int64_t) { return false; }); + table.widget->setFocusCell(static_cast(table.focusIndex), table.focusColumn); + reportFocus(table); +} + +void Mounter::applyKeyMoves(SourceTable& table, KeyMoves const& moves) { + if (moves.generation <= table.keyMovesApplied) { + return; + } + table.keyMovesApplied = moves.generation; + // A key focus left is followed by the first generation of moves after it left, and by no later one. + std::optional const left = std::exchange(table.focusWas, std::nullopt); + for (auto const& [from, target] : moves.moves) { + if (table.highlightKey == from) { + table.highlightKey = target; + if (std::optional const now = placeOfKey(table, target, table.highlightIndex)) { + table.highlightSearching = false; + table.highlightIndex = *now; + table.widget->setHighlightedRow(static_cast(*now)); + } else { + table.highlightSearching = true; + } + } + if (!table.focused || (table.focusKey != from && left != from)) { + continue; + } + table.focusKey = target; + table.focusUnconfirmed = false; + table.focusLeft = false; + table.focusUntold = false; + table.focusLocate.request_stop(); + if (std::optional const now = placeOfKey(table, target, table.focusIndex)) { + table.focusSearching = false; + table.focusIndex = *now; + table.widget->setFocusCell(static_cast(*now), table.focusColumn); + } else { + table.focusSearching = true; + locateFocus(table); + } + reportFocus(table); + } +} + +void Mounter::highlightFrom(SourceTable& table, std::optional const& highlight) { + table.highlightSearching = false; + if (!highlight) { + if (table.highlightKey) { + table.highlightKey.reset(); + table.widget->setHighlightedRow(std::nullopt); + } + return; + } + table.highlightKey = highlight->key; + table.highlightIndex = static_cast(highlight->row); + std::size_t const overscan = table.virtualize.overscan; + std::size_t const first = highlight->row > overscan ? highlight->row - overscan : 0; + table.source.rows->visible(static_cast(first), + static_cast(table.range.count + (2 * overscan)), table.fetched); + table.widget->scrollToRow(highlight->row); + table.widget->setHighlightedRow(highlight->row); +} + +std::optional Mounter::placeOfKey(SourceTable const& table, Key const& key, std::int64_t also) { + TableRows const& rows = *table.source.rows; + auto const holds = [&rows, &key](std::int64_t index) { + std::optional const ref = rows.row(index); + return ref && ref->key == key; + }; + if (holds(also)) { + return also; + } + for (SourceTable::Realized const& row : table.realized) { + if (holds(row.index)) { + return row.index; + } + } + return std::nullopt; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): follows the focused and the highlighted rows through each operation of a change, which shifts both by the operation kind +void Mounter::follow(SourceTable& table, table::ViewChange const& change) { + bool const reset = + std::ranges::any_of(change.ops, [](table::ViewOp const& op) { return op.kind == table::ViewOp::Kind::Reset; }); + if (reset) { + table.lastCount = 0; + } + auto const followed = [&table, &change](std::int64_t index) -> std::optional { + if (std::cmp_greater_equal(index, table.lastCount)) { + return index; + } + return followIndex(change, index); + }; + if (table.highlightKey && !table.highlightSearching) { + std::optional const now = + reset ? placeOfKey(table, *table.highlightKey, table.highlightIndex) : followed(table.highlightIndex); + if (now) { + if (*now != table.highlightIndex) { + table.highlightIndex = *now; + table.widget->setHighlightedRow(static_cast(*now)); + } + } else if (reset) { + table.highlightSearching = true; + table.widget->setHighlightedRow(std::nullopt); + } else { + table.highlightKey.reset(); + table.widget->setHighlightedRow(std::nullopt); + } + } + if (table.focused && reset && table.focusKey) { + if (std::optional const now = placeOfKey(table, *table.focusKey, table.focusIndex)) { + table.focusLocate.request_stop(); + table.focusSearching = false; + if (*now != table.focusIndex) { + table.focusIndex = *now; + table.widget->setFocusCell(static_cast(*now), table.focusColumn); + } + } else { + table.focusSearching = true; + table.focusUntold = false; + locateFocus(table); + } + return; + } + if (table.focused && !table.focusSearching) { + TableTotal const total = table.source.rows->mountedTotal(); + // A focused row the change removed leaves focus at its view index, on the row now there, or the last; a + // count not known yet names no last row. + std::optional const now = followed(table.focusIndex); + if (!now && !table.focusLeft) { + table.focusWas = table.focusKey; + } + table.focusLeft = table.focusLeft || !now.has_value(); + table.focusIndex = now.value_or(table.focusIndex); + if (total.known) { + table.focusIndex = std::min(table.focusIndex, std::max(total.rows - 1, 0)); + } + } +} + +bool Mounter::namesUpdated(table::ViewChange const& change, std::int64_t index) { + auto const position = static_cast(index); + return std::ranges::any_of(change.ops, [position](table::ViewOp const& op) { + switch (op.kind) { + case table::ViewOp::Kind::Reset: + return true; + case table::ViewOp::Kind::Changed: + case table::ViewOp::Kind::Inserted: + return position >= op.first && position < op.first + op.count; + case table::ViewOp::Kind::Moved: + return position == op.to; + case table::ViewOp::Kind::Removed: + default: + return false; + } + }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): binds what an editable table adds (focus, click, typed text, keys, focus loss), each handler capturing the same table state +void Mounter::bindGrid(reactive::Scope& scope, Table const& spec, TableWidget& widget, SourceTable& table) { + table.grid = spec.gridFocus.has_value(); + table.onGridFocus = event(spec.onGridFocus); + table.editor = spec.editor; + if (spec.onText) { + widget.setOnText(event(spec.onText)); + } + if (spec.onFocusOut) { + widget.setOnFocusOut(event(spec.onFocusOut)); + } + if (table.grid || spec.onActivateCell || spec.onClickCell) { + widget.setOnCellClick( + [this, &table, activate = spec.onActivateCell, clicked = spec.onClickCell]( + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): (`viewRow`, `column`, `doubleClick`): the backend callback's contract, in the order the conformance suite fires it + std::size_t viewRow, std::size_t column, bool doubleClick) { + static_cast(runCallback(*_rt, [&] { + if (column >= table.columns.size()) { + return; + } + auto const index = static_cast(viewRow); + std::optional const ref = table.source.rows->row(index); + if (!doubleClick) { + if (table.grid) { + handFocus(table, index, column); + } else if (ref) { + focusAt(table, ref->key, column); + } + if (ref && clicked) { + clicked(CellRef{.key = ref->key, .column = table.columns.at(column).id}); + } + return; + } + if (ref && activate) { + activate(CellRef{.key = ref->key, .column = table.columns.at(column).id}); + } + })); + }); + } + if (!spec.onKey) { + return; + } + // The table's own chords join the document's keys in one declaration; a chord of both is the table's. + bind(scope, spec.keyChords, + [this, &widget, onKey = spec.onKey, common = spec.common.keys](std::vector const& chords) { + std::vector all; + all.reserve(common.size()); + for (KeyBinding const& binding : common) { + all.push_back(binding.chord); + } + for (std::string const& chord : chords) { + if (!std::ranges::contains(all, chord)) { + all.push_back(chord); + } + } + widget.setKeys(all, [this, &widget, onKey, common, chords](std::string const& chord) { + static_cast(runCallback(*_rt, [&] { + if (std::ranges::contains(chords, chord)) { + KeyOutcome const outcome = onKey(chord); + if (outcome == KeyOutcome::FocusNext || outcome == KeyOutcome::FocusPrevious) { + static_cast(focusAlong(widget, outcome == KeyOutcome::FocusNext)); + } + return; + } + auto const bound = std::ranges::find(common, chord, &KeyBinding::chord); + if (bound != common.end() && bound->onPress) { + bound->onPress(); + } + })); + }); + }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one handler per table seam. +Widget& Mounter::mountSourceTable(reactive::Scope& scope, Table const& spec, ContainerWidget* parent) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): the mount dispatches here only for a spec with a source. + TableSource const& source = *spec.source; + if (!source.rows || !source.cellView) { + throw std::logic_error{"morph::ui: a table source needs its rows and its cell view"}; + } + TableWidget& widget = scope.adopt(_backend->createTable(parent)); + applyCommon(scope, widget, spec.common); + checkNoShare(spec.columns); + if (spec.bands.empty()) { + widget.setColumns(spec.columns); + } else { + // A column under a band that shows its unit does not repeat it. + std::vector headed = spec.columns; + for (TableColumn& column : headed) { + if (!columnUnitShown(spec.bands, column.id, column.unit)) { + column.unit.clear(); + } + } + widget.setColumns(headed); + } + widget.setShowHeader(spec.showHeader); + widget.setSelectionMode(spec.selectionMode); + if (spec.selectColumn) { + widget.setSelectColumn(true); + bind(scope, spec.selectAllLabel, [&widget](std::string const& label) { widget.setSelectAllLabel(label); }); + } + widget.setOnActivate(event(spec.onActivate)); + if (spec.onSelectAll) { + widget.setOnSelectAll(event(spec.onSelectAll)); + } + auto& table = scope.make(); + table.bands = spec.bands; + if (!source.alwaysWindowed) { + auto& spans = scope.make(); + spans.columns = spec.columns.size(); + spans.threshold = spec.virtualize.threshold; + table.spans = &spans; + } + if (std::ranges::any_of(spec.columns, &TableColumn::sortable)) { + bind(scope, spec.sort, [this, &widget, &table](std::vector const& chain) { + widget.setSort(chain); + if (table.spans != nullptr) { + table.spans->sorted = !chain.empty(); + resolveSpans(widget, *table.spans); + } + }); + widget.setOnSort(event(spec.onSort)); + } + bindTableConfig(scope, spec, widget, + [this, &table](Key const& key, std::size_t column) { focusAt(table, key, column); }); + bind(scope, spec.status, [&widget](TableStatus const& status) { widget.setStatus(status); }); + widget.setOnRetry(event(spec.onRetry)); + table.source = source; + table.widget = &widget; + table.columns = spec.columns; + table.virtualize = spec.virtualize; + table.depth = scope.depth() + 1; + table.onFocusCell = event(spec.onFocusCell); + _extents = table.extents; + arrange(table, TableArrangement{}); + auto const pass = [this, &table] { + if (table.mounted) { + static_cast(runCallback(*_rt, [&] { realizeWindow(table, [](std::int64_t) { return false; }); })); + } + }; + bind(scope, spec.arrangement, [&table, pass](TableArrangement const& arrangement) { + if (arrangement != table.arrangement) { + arrange(table, arrangement); + pass(); + showCells(table); + } + }); + table.source.rows->onChange([this, &table, alive = std::weak_ptr{table.alive}](table::ViewChange const& change) { + if (alive.expired()) { + return; + } + ++_stats.viewChanges; + if (std::ranges::any_of(change.ops, + [](table::ViewOp const& op) { return op.kind == table::ViewOp::Kind::Reset; })) { + ++_stats.viewResets; + } + static_cast(runCallback(*_rt, [&] { + follow(table, change); + realizeWindow(table, [&change](std::int64_t index) { return namesUpdated(change, index); }); + showCells(table); + })); + }); + widget.setOnVisibleRangeChanged([this, &table](std::size_t first, std::size_t count) { + static_cast(runCallback(*_rt, [&] { + table.range = VisibleRange{.first = first, .count = count}; + realizeWindow(table, [](std::int64_t) { return false; }); + tellVisible(table); + })); + }); + widget.setOnHorizontalRange([this, &table](int scrollX, int viewport) { + static_cast(runCallback(*_rt, [&] { + table.horizontal = true; + table.scrollX = std::max(scrollX, 0); + table.viewport = std::max(viewport, 0); + table.windowDirty = true; + table.stretchDirty = true; + realizeWindow(table, [](std::int64_t) { return false; }); + })); + }); + widget.setOnColumnMeasured([this, &table](std::size_t column, ColumnMeasure const& measure) { + static_cast(runCallback(*_rt, [&] { measured(table, column, measure); })); + }); + widget.setOnFocusMove( + [this, &table](FocusMove move) { static_cast(runCallback(*_rt, [&] { moveFocus(table, move); })); }); + widget.setOnSelectRange(event(spec.onSelectRange)); + bindGrid(scope, spec, widget, table); + _rt->untracked([&] { + realizeWindow(table, [](std::int64_t) { return false; }); + tellVisible(table); + table.mounted = true; + }); + bind(scope, spec.focus, [this, &table](std::optional const& cell) { + static_cast(runCallback(*_rt, [&] { focusFrom(table, cell); })); + }); + bind(scope, spec.highlight, [this, &table](std::optional const& highlight) { + static_cast(runCallback(*_rt, [&] { highlightFrom(table, highlight); })); + }); + bind(scope, spec.keyMoves, [this, &table](KeyMoves const& moves) { + static_cast(runCallback(*_rt, [&] { applyKeyMoves(table, moves); })); + }); + if (spec.gridFocus) { + bind(scope, *spec.gridFocus, [this, &table](std::optional const& focus) { + static_cast(runCallback(*_rt, [&] { gridFocusFrom(table, focus); })); + }); + } + if (spec.cellSelection) { + table.cells = true; + widget.setSelectionMode(SelectionMode::None); + widget.setOnCellSelect( + [this, &table, onSelect = spec.onCellSelect](std::size_t anchorRow, std::size_t anchorPlace, + std::size_t focusRow, std::size_t focusPlace) { + static_cast(runCallback(*_rt, [&] { + std::optional range = cellsAt(table, anchorRow, anchorPlace, focusRow, focusPlace); + if (range && onSelect) { + onSelect(std::move(range)); + } + })); + }); + bind(scope, *spec.cellSelection, [this, &table](std::optional const& range) { + static_cast(runCallback(*_rt, [&] { + table.cellRange = range; + showCells(table); + })); + }); + } + if (spec.editing) { + bind(scope, *spec.editing, [this, &table](std::optional const& cell) { + static_cast(runCallback(*_rt, [&] { + table.editWanted = cell; + syncEditor(table); + })); + }); + } + // While the selection is of the view the backend marks it, and the key list it holds is not sent over it. + auto& viewing = scope.make(false); + widget.setOnSelectionChange(inputEvent( + spec.onSelectionChange, controlled(scope, spec.selection, [&widget, &viewing](std::vector const& keys) { + if (!viewing) { + widget.setSelection(keys); + } + }))); + bindSelectionView(scope, spec, widget, viewing); + return widget; +} + +void Mounter::measured(SourceTable& table, std::size_t column, ColumnMeasure const& reported) { + if (column >= table.measures.size()) { + return; + } + ColumnMeasure& known = table.measures.at(column); + ColumnMeasure const next{.header = std::max(known.header, reported.header), + .natural = std::max(known.natural, reported.natural), + .least = std::max(known.least, reported.least)}; + if (next == known) { + return; + } + known = next; + std::optional const placed = column < table.placeOf.size() ? table.placeOf.at(column) : std::nullopt; + if (!placed) { + return; + } + std::size_t const place = *placed; + ColumnExtents& extents = *table.extents; + if (std::ranges::contains(table.stretchPlaces, place)) { + table.stretchDirty = true; + table.windowDirty = true; + realizeWindow(table, [](std::int64_t) { return false; }); + return; + } + if (table.columns.at(column).width.kind != Sizing::Kind::Content) { + return; + } + int const width = contentWidthOf(next, table.measure); + int const before = extents.offsetOf(place + 1) - extents.offsetOf(place); + std::size_t const firstFull = firstFullPlace(table); + if (!extents.fit(place, width)) { + return; + } + if (table.horizontal && place >= table.pinnedShown && place < firstFull) { + table.scrollX += width - before; + table.widget->setHorizontalOffset(table.scrollX); + } + table.windowDirty = true; + table.stretchDirty = true; + realizeWindow(table, [](std::int64_t) { return false; }); +} + +void Mounter::mountRows(reactive::Scope& scope, std::shared_ptr const& model, + ContainerWidget& container, RowHook onRow, Virtualization const* virtualize, + RowsObserver observer) { + if (!model) { + return; + } + scope.make>(model); + ForEachSession& session = scope.adopt(model->open(*_rt)); + auto& rows = scope.make(); + TableWidget* const table = virtualize != nullptr ? dynamic_cast(&container) : nullptr; + if (table == nullptr) { + scope.effect([this, &session, &rows, &container, depth = scope.depth() + 1, onRow, overlay = _overlay] { + std::vector const keys = session.pull(); // tracked: the rows are this Effect's only source + // Untracked: what a row view reads while it is built, or what a kept row's update touches, must + // not become a dependency of the whole list. + underOverlay(overlay, [&] { + _rt->untracked([&] { reconcile(depth, session, rows.list, container, keys, onRow); }); + }); + }); + return; + } + // The windowing state: written by the backend's own scroll callback (via widgetEvent, so this is never + // written from inside a flush this Effect caused), read by both Effects below -- the rows Effect, so a + // brand-new row's very first mount already respects the window instead of needing a later windowing pass + // to correct it; the windowing Effect, so a scroll alone realizes/releases without re-running reconcile. + auto& range = scope.make>(*_rt, VisibleRange{}); + table->setOnVisibleRangeChanged([this, &range](std::size_t first, std::size_t count) { + runCallback(*_rt, [&] { range.set({.first = first, .count = count}); }); + }); + // The observer sees every pass that changes the rows, the windowing one included. + auto const observerTrack = observer.track; + auto const around = observedPass(std::move(observer), rows); + // Whether the backend was last told the rows are windowed: a count that falls back below the threshold then + // owes it the end of the window. + auto& windowed = scope.make(false); + scope.effect([this, &session, &rows, &container, &range, &windowed, setting = *virtualize, + depth = scope.depth() + 1, onRow, table, overlay = _overlay, around, track = observerTrack] { + // tracked: the rows are one source, and the sort that `track` reads is the other + std::vector const keys = session.pull(); + if (track) { + track(); + } + VisibleRange const window = range.peek(); // untracked: a scroll alone must not re-run this Effect + around([&] { + underOverlay(overlay, [&] { + _rt->untracked([&] { + reconcileWindowed(depth, session, rows, container, *table, keys, onRow, window, setting, windowed); + }); + }); + }); + publishRealizedWindow(*table, rows, keys.size(), setting, windowed); + }); + scope.effect([this, &rows, &container, &range, setting = *virtualize, depth = scope.depth() + 1, onRow, table, + overlay = _overlay, around] { + VisibleRange const window = range.get(); // tracked: this Effect's own trigger + // Below threshold, every row is already realized (reconcile's own unconditional path, §4.4), and + // setRealizedWindow is not called at all -- not even once with "everything realized" -- so a table + // that never crosses its threshold is indistinguishable, on the backend, from one with no + // virtualization machinery at all. + if (rows.list.size() < setting.threshold) { + return; + } + around([&] { + underOverlay(overlay, [&] { applyWindow(depth, rows.list, container, window, setting.overscan, onRow); }); + }); + auto const [first, count] = realizedExtent(rows.list); + table->setRealizedWindow(first, count, rows.list.size()); + }); +} + +std::vector Mounter::firstOccurrences(std::vector const& keys) { + std::unordered_set seen; + std::vector order; + order.reserve(keys.size()); + for (std::size_t index = 0; index < keys.size(); ++index) { + if (seen.insert(keys.at(index)).second) { + order.push_back(index); + } else { + _rt->core()->report(site::kDuplicateKey); + } + } + return order; +} + +KeyedRow Mounter::mountRow(std::size_t depth, ForEachSession& session, ContainerWidget& container, Key const& key, + std::size_t index, RowHook const& onRow) { + return mountPass([&] { + KeyedRow row{.key = key, .stateScope = std::make_unique(*_rt, depth)}; + row.slot = &row.stateScope->adopt(session.makeRow(index)); + row.widgetScope = std::make_unique(*_rt, depth); + row.widget = mount(*row.widgetScope, row.slot->view(), &container); + row.widgetState = row.widget != nullptr ? RowWidgetState::Realized : RowWidgetState::NullView; + if (row.widget != nullptr && onRow) { + onRow(*row.widgetScope, row.slot->view(), *row.widget, key); + } + return row; + }); +} + +void Mounter::realizeRowWidget(std::size_t depth, KeyedRow& row, ContainerWidget& container, RowHook const& onRow) { + row.widgetScope = std::make_unique(*_rt, depth); + row.widget = mount(*row.widgetScope, row.slot->view(), &container); + row.widgetState = row.widget != nullptr ? RowWidgetState::Realized : RowWidgetState::NullView; + if (row.widget != nullptr && onRow) { + onRow(*row.widgetScope, row.slot->view(), *row.widget, row.key); + } +} + +void Mounter::dewindowRowWidget(KeyedRow& row) { + row.widgetScope.reset(); + row.widget = nullptr; + row.widgetState = RowWidgetState::Dewindowed; +} + +KeyedRow Mounter::mountRowState(std::size_t depth, ForEachSession& session, Key const& key, std::size_t index) { + KeyedRow row{.key = key, .stateScope = std::make_unique(*_rt, depth)}; + row.slot = &row.stateScope->adopt(session.makeRow(index)); + row.widgetState = RowWidgetState::Dewindowed; + return row; +} + +void Mounter::reorder(std::vector& rows, ContainerWidget& container, std::vector const& keys, + std::vector const& order, std::exception_ptr& failure) { + std::unordered_map position; // key -> index in `rows` + std::unordered_map rowOf; + std::vector present; + for (std::size_t i = 0; i < rows.size(); ++i) { + KeyedRow const& row = rows.at(i); + position.emplace(row.key, i); + if (row.widget != nullptr) { + rowOf.emplace(row.widget, i); + present.push_back(row.widget); + } + } + std::vector target; + target.reserve(present.size()); + for (std::size_t const index : order) { + if (auto const found = position.find(keys.at(index)); found != position.end()) { + if (KeyedRow const& row = rows.at(found->second); row.widget != nullptr) { + target.push_back(row.widget); + } + } + } + std::vector ordered; + ordered.reserve(rows.size()); + try { + reorderChildren(container, present, target); + } catch (...) { + if (!failure) { + failure = std::current_exception(); + } + } + reorderChain(container, present); + // `present` is the container's order now: the snapshot's, unless a move threw. Rows without a widget have + // no place in the container and go last. + for (Widget const* const widget : present) { + ordered.push_back(std::move(rows.at(rowOf.at(widget)))); + } + for (KeyedRow& row : rows) { + if (row.widget == nullptr) { + ordered.push_back(std::move(row)); + } + } + rows = std::move(ordered); +} + +void Mounter::reconcile(std::size_t depth, ForEachSession& session, std::vector& rows, + ContainerWidget& container, std::vector const& keys, RowHook const& onRow, + std::pair const* windowAndOverscan) { + std::vector const order = firstOccurrences(keys); + std::unordered_map wanted; // key -> snapshot index + std::unordered_map viewPositionOf; // key -> position in view order (order's own index) + for (std::size_t viewPos = 0; viewPos < order.size(); ++viewPos) { + wanted.emplace(keys.at(order.at(viewPos)), order.at(viewPos)); + viewPositionOf.emplace(keys.at(order.at(viewPos)), viewPos); + } + + // Unmount the gone keys, last first as KeyedRows does, then update the kept ones in place, which keeps + // their widgets. A gone key's widget goes first (the Effect stops first within each row, mirroring the + // order mountRow itself builds the two scopes in: state first, then widget), then its state. + for (KeyedRow& row : std::views::reverse(rows)) { + if (!wanted.contains(row.key)) { + row.widgetScope.reset(); + row.stateScope.reset(); + } + } + std::erase_if(rows, [](KeyedRow const& row) { return row.stateScope == nullptr; }); + std::unordered_set kept; + for (KeyedRow& row : rows) { + kept.insert(row.key); + row.slot->assign(wanted.at(row.key)); + row.viewPosition = viewPositionOf.at(row.key); + } + + std::size_t const bootstrapFirst = 0; + std::size_t const bootstrapCount = windowAndOverscan != nullptr ? windowAndOverscan->second : 0; + VisibleRange const window = windowAndOverscan != nullptr && windowAndOverscan->first.count > 0 + ? windowAndOverscan->first + : VisibleRange{.first = bootstrapFirst, .count = bootstrapCount}; + + // Mount the new keys; each realized widget is appended to the container, and every new row (realized or + // state-only) to `rows`. `viewPos` is the row's position in view order -- order's own index -- which is + // what the window means positions in, not `index` (a position in the raw, possibly-reordered `keys`). + std::exception_ptr failure; + rows.reserve(order.size()); + for (std::size_t viewPos = 0; viewPos < order.size(); ++viewPos) { + std::size_t const index = order.at(viewPos); + if (kept.contains(keys.at(index))) { + continue; + } + bool const inWindow = + windowAndOverscan == nullptr || (viewPos >= window.first && viewPos < window.first + window.count); + try { + KeyedRow row = inWindow ? mountRow(depth, session, container, keys.at(index), index, onRow) + : mountRowState(depth, session, keys.at(index), index); + row.viewPosition = viewPos; + rows.push_back(std::move(row)); + } catch (...) { + if (!failure) { + failure = std::current_exception(); + } + } + } + + reorder(rows, container, keys, order, failure); + if (failure) { + std::rethrow_exception(failure); + } +} + +void Mounter::applyWindow(std::size_t depth, std::vector& rows, ContainerWidget& container, + VisibleRange const& window, std::size_t overscan, RowHook const& onRow) { + std::size_t const low = window.first > overscan ? window.first - overscan : 0; + std::size_t const high = + window.first + window.count + overscan; // exclusive; saturates harmlessly past rows.size() + std::exception_ptr failure; + for (KeyedRow& row : rows) { + bool const shouldBeRealized = row.viewPosition >= low && row.viewPosition < high; + if (shouldBeRealized && row.widgetState != RowWidgetState::Realized && + row.widgetState != RowWidgetState::NullView) { + try { + realizeRowWidget(depth, row, container, onRow); + } catch (...) { + if (!failure) { + failure = std::current_exception(); + } + } + } else if (!shouldBeRealized && row.widgetState == RowWidgetState::Realized) { + dewindowRowWidget(row); + } + } + // Realized widgets may now be a different subset of `rows` than before; bring the container back to the + // rows' own view order (`viewPosition`), restricted to what is realized -- `reorder` needs `order` as + // positions into `keys` in the target (view) order, not `rows`' own current array order, which groups + // realized ahead of dewindowed and so is not view order once any row is dewindowed. + std::vector const keys = [&] { + std::vector out; + out.reserve(rows.size()); + for (KeyedRow const& row : rows) { + out.push_back(row.key); + } + return out; + }(); + std::vector order(rows.size()); + // NOLINTNEXTLINE(modernize-use-ranges): std::ranges::iota is missing from Emscripten's libc++. + std::iota(order.begin(), order.end(), std::size_t{0}); + std::ranges::sort(order, {}, [&rows](std::size_t index) { return rows.at(index).viewPosition; }); + reorder(rows, container, keys, order, failure); + if (failure) { + std::rethrow_exception(failure); + } +} + +std::pair Mounter::realizedExtent(std::vector const& rows) { + std::optional first; + std::size_t last = 0; + for (KeyedRow const& row : rows) { + if (row.widgetState == RowWidgetState::Realized) { + first = first ? std::min(*first, row.viewPosition) : row.viewPosition; + last = std::max(last, row.viewPosition); + } + } + return first ? std::pair{*first, last - *first + 1} : std::pair{std::size_t{0}, std::size_t{0}}; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Busy const& spec, ContainerWidget* parent) { + BusyWidget& widget = scope.adopt(_backend->createBusy(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.active, [&widget](bool active) { widget.setActive(active); }); + bind(scope, spec.label, [&widget](std::string const& label) { widget.setLabel(label); }); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Banner const& spec, ContainerWidget* parent) { + BannerWidget& widget = scope.adopt(_backend->createBanner(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.tone, [&widget](Tone tone) { widget.setTone(tone); }); + if (hasSpans(spec.spans)) { + bind(scope, spec.spans, [&widget](std::vector const& spans) { widget.setSpans(spans); }); + } else { + bind(scope, spec.text, [&widget](std::string const& text) { widget.setText(text); }); + } + bind(scope, spec.action.label, [&widget](std::string const& label) { widget.setActionLabel(label); }); + widget.setOnAction(event(spec.action.onClick)); + widget.setDismissible(spec.dismissible); + widget.setOnDismiss(event(spec.onDismiss)); + if (spec.actionStyle != BannerActionStyle::Ghost || spec.actionStretch) { + widget.setActionStyle(spec.actionStyle, spec.actionStretch); + } + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Badge const& spec, ContainerWidget* parent) { + BadgeWidget& widget = scope.adopt(_backend->createBadge(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.tone, [&widget](Tone tone) { widget.setTone(tone); }); + bind(scope, spec.text, [&widget](std::string const& text) { widget.setText(text); }); + widget.setIcon(spec.icon); + if (spec.style != BadgeStyle::Filled) { + widget.setStyle(spec.style); + } + if (spec.shape != ControlShape::Default) { + widget.setShape(spec.shape); + } + if (spec.mono) { + widget.setMono(true); + } + if (spec.onRemove) { + // An empty label names the control after the badge's text, which may be bound as well. + auto const labelOf = [removeLabel = spec.removeLabel, text = spec.text] { + std::string const label = removeLabel.evaluate(); + return label.empty() ? "Remove " + text.evaluate() : label; + }; + Prop const label = spec.removeLabel.isBound() || spec.text.isBound() + ? Prop(labelOf) + : Prop(labelOf()); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks): the analyzer loses the owner of the callable `std::function` heap-allocates for this capture; the function object owns it and frees it + bind(scope, label, [&widget, onRemove = event(spec.onRemove)](std::string const& shown) { + widget.setOnRemove(onRemove, shown); + }); + } + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Progress const& spec, ContainerWidget* parent) { + ProgressWidget& widget = scope.adopt(_backend->createProgress(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.value, [&widget](std::optional value) { widget.setValue(value); }); + bind(scope, spec.label, [&widget](std::string const& label) { widget.setLabel(label); }); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Steps const& spec, ContainerWidget* parent) { + StepsWidget& widget = scope.adopt(_backend->createSteps(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.items, [&widget](std::vector const& steps) { widget.setSteps(steps); }); + bind(scope, spec.current, [&widget](std::optional index) { widget.setCurrent(index); }); + if (spec.labelled.isBound() || !spec.labelled.constant()) { + bind(scope, spec.labelled, [&widget](bool labelled) { widget.setLabelled(labelled); }); + } + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Chart const& spec, ContainerWidget* parent) { + ChartWidget& widget = scope.adopt(_backend->createChart(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.data, [&widget](ChartData const& data) { widget.setData(data); }); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, KeyValue const& spec, ContainerWidget* parent) { + KeyValueWidget& widget = scope.adopt(_backend->createKeyValue(parent)); + applyCommon(scope, widget, spec.common); + if (spec.captions != CaptionPlacement::Beside) { + widget.setCaptionPlacement(spec.captions); + } + if (spec.captionWidth) { + if (*spec.captionWidth < 1) { + throw std::invalid_argument{"morph::ui::mount: `captionWidth` is at least 1 unit"}; + } + if (spec.captions == CaptionPlacement::Above) { + throw std::invalid_argument{"morph::ui::mount: `captionWidth` needs the captions beside their values"}; + } + widget.setCaptionWidth(*spec.captionWidth); + } + bind(scope, spec.items, [&widget](std::vector const& items) { widget.setItems(items); }); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, EmptyState const& spec, ContainerWidget* parent) { + EmptyStateWidget& widget = scope.adopt(_backend->createEmptyState(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.title, [&widget](std::string const& title) { widget.setTitle(title); }); + bind(scope, spec.text, [&widget](std::string const& text) { widget.setText(text); }); + widget.setIcon(spec.icon); + bind(scope, spec.action.label, [&widget](std::string const& label) { widget.setActionLabel(label); }); + widget.setOnAction(event(spec.action.onClick)); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Splitter const& spec, ContainerWidget* parent) { + SplitterWidget& widget = scope.adopt(_backend->createSplitter(parent, spec.orientation)); + if (spec.orientation == Axis::Horizontal) { + scope.make(_shareParents, &widget); + } + applyCommon(scope, widget, spec.common); + mountChildren(scope, spec.children, widget); + widget.setOnResize(inputEvent( + spec.onResize, + controlled(scope, spec.sizes, [&widget](std::vector const& sizes) { widget.setSizes(sizes); }))); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Collapsible const& spec, ContainerWidget* parent) { + CollapsibleWidget& widget = scope.adopt(_backend->createCollapsible(parent)); + applyCommon(scope, widget, spec.common); + bind(scope, spec.title, [&widget](std::string const& title) { widget.setTitle(title); }); + if (Widget* const header = mount(scope, spec.header, &widget); header != nullptr) { + widget.setHeader(*header); + } + static_cast(mount(scope, spec.child, &widget)); + widget.setOnToggle( + inputEvent(spec.onToggle, controlled(scope, spec.open, [&widget](bool open) { widget.setOpen(open); }))); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, DropZone const& spec, ContainerWidget* parent) { + DropZoneWidget& widget = scope.adopt(_backend->createDropZone(parent)); + applyCommon(scope, widget, spec.common); + widget.setAccept(spec.accept); + widget.setMultiple(spec.multiple); + widget.setOnDrop(event(spec.onDrop)); + static_cast(mount(scope, spec.child, &widget)); + return widget; +} + +std::logic_error Mounter::pageRefusal(Common const& common, std::string const& what) { + return std::logic_error{"morph::ui::mount: " + what + + (common.testId.empty() ? std::string{} : " (node `" + common.testId + "`)")}; +} + +void Mounter::checkPageLayout(Common const& common, bool isPage) { + LayoutHints hints = common.layout; + if (isPage) { + if (hints.alignSelf && *hints.alignSelf == Align::Stretch) { + throw pageRefusal(common, "a page is never stretched; `alignSelf` places the sheet"); + } + hints.alignSelf.reset(); + } + if (hints != LayoutHints{}) { + throw pageRefusal(common, isPage ? "a page is sized by its sheet; its layout hints are refused" + : "a page region is sized by its geometry; its layout hints are refused"); + } +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Page const& spec, ContainerWidget* parent) { + checkPageLayout(spec.common, true); + if (std::optional const problem = spec.geometry.problem()) { + throw pageRefusal(spec.common, *problem); + } + for (Node const& child : spec.children) { + if (child && !std::holds_alternative(child->kind)) { + throw pageRefusal(spec.common, "a page holds page regions and nothing else"); + } + } + PageWidget& widget = scope.adopt(_backend->createPage(parent, spec.geometry)); + applyCommon(scope, widget, spec.common); + if (spec.common.a11y.role.empty()) { + widget.setAccessibleRole("document"); + } + if (!spec.common.surface.isBound() && spec.common.surface.constant().empty()) { + widget.setSurface("paper"); + } + PageGuard const guard{*this, &spec.geometry}; + mountChildren(scope, spec.children, widget); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, PageRegion const& spec, ContainerWidget* parent) { + auto* const page = dynamic_cast(parent); + if (page == nullptr || _page == nullptr) { + throw pageRefusal(spec.common, "a page region belongs in a page"); + } + checkPageLayout(spec.common, false); + if (std::optional const problem = spec.geometry.problem(*_page)) { + throw pageRefusal(spec.common, *problem); + } + PageRegionWidget& widget = scope.adopt(_backend->createPageRegion(page, spec.geometry)); + applyCommon(scope, widget, spec.common); + mountChildren(scope, spec.children, widget); + return widget; +} + +void Mounter::bindCustomProp(reactive::Scope& scope, CustomWidget& widget, CustomProp const& prop) { + std::string const& name = prop.name; + if (auto const* const text = std::get_if>(&prop.value)) { + bind(scope, *text, [&widget, name](std::string const& value) { widget.setTextProp(name, value); }); + } else if (auto const* const flag = std::get_if>(&prop.value)) { + bind(scope, *flag, [&widget, name](bool value) { widget.setBoolProp(name, value); }); + } else if (auto const* const number = std::get_if>(&prop.value)) { + bind(scope, *number, [&widget, name](double value) { widget.setNumberProp(name, value); }); + } +} + +Widget& Mounter::mountKind(reactive::Scope& scope, ActionBar const& spec, ContainerWidget* parent) { + ContainerWidget* const footer = overlayFooter(); + if (spec.wrap && footer != nullptr) { + throw std::invalid_argument{ + "morph::ui::Mounted: an overlay's footer is one row of actions; `wrap` is for an action bar in place"}; + } + StackWidget& widget = scope.adopt(_backend->createStack(footer != nullptr ? footer : parent, Axis::Horizontal)); + // A wrapping row shares no width with its parent, as a wrapping ForEach does. + if (footer == nullptr && !spec.wrap) { + scope.make(_shareParents, &widget); + } + widget.setActionRow(); + if (spec.wrap) { + widget.setWrap(true); + } + applyCommon(scope, widget, spec.common); + widget.setGap(spacingStep(2)); + if (spec.align != Align::Stretch) { + widget.setAlign(spec.align); + } + if (spec.justify != Justify::Start) { + widget.setJustify(spec.justify); + } + // While the children mount, a horizontal ForEach whose parent is this bar is part of its row. + class Restore { + public: + Restore(Mounter& self, StackWidget* bar) : _self{&self}, _saved{std::exchange(self._actionBar, bar)} {} + Restore(Restore const&) = delete; + Restore& operator=(Restore const&) = delete; + Restore(Restore&&) = delete; + Restore& operator=(Restore&&) = delete; + ~Restore() { _self->_actionBar = _saved; } + + private: + Mounter* _self; + StackWidget* _saved; + }; + Restore const restore{*this, &widget}; + for (Node const& child : spec.children) { + static_cast(mount(scope, child, &widget)); + } + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Custom const& spec, ContainerWidget* parent) { + CustomRequest request{.name = spec.name, .props = {}, .minVersion = spec.minVersion}; + request.props.reserve(spec.props.size()); + for (CustomProp const& prop : spec.props) { + request.props.push_back(prop.name); + } + if (std::unique_ptr loaded = _backend->createCustom(parent, request)) { + CustomWidget& widget = scope.adopt(std::move(loaded)); + for (CustomProp const& prop : spec.props) { + bindCustomProp(scope, widget, prop); + } + widget.setOnEvent(spec.onEvent); + return widget; + } + Widget* const fallback = mount(scope, spec.fallback, parent); + if (fallback == nullptr) { + throw std::invalid_argument{"morph::ui::Mounted: the custom node " + spec.name + " has no fallback"}; + } + return *fallback; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, DateTimeInput const& spec, ContainerWidget* parent) { + DateTimeInputWidget& widget = scope.adopt(_backend->createDateTimeInput(parent, spec.mode, spec.offsetMinutes)); + applyCommon(scope, widget, spec.common); + applyField(scope, widget, spec.field); + // Before the value, which is then shown in it; an input with no pattern is told none. + if (spec.pattern.isBound() || !spec.pattern.constant().empty()) { + bind(scope, spec.pattern, [&widget](std::string const& pattern) { widget.setPattern(pattern); }); + } + widget.setOnChange(inputEvent( + spec.onChange, controlled(scope, spec.value, [&widget](std::optional const& value) { + widget.setValue(value); + }))); + applyCaption(scope, widget, spec.label, spec.showLabel); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, Slider const& spec, ContainerWidget* parent) { + SliderWidget& widget = scope.adopt(_backend->createSlider(parent)); + applyCommon(scope, widget, spec.common); + applyField(scope, widget, spec.field); + widget.setRange(spec.minimum, spec.maximum, spec.step); + widget.setOnChange(inputEvent( + spec.onChange, controlled(scope, spec.value, [&widget](std::int64_t value) { widget.setValue(value); }))); + widget.setOnCommit(event(spec.onCommit)); + return widget; +} + +Widget& Mounter::mountKind(reactive::Scope& scope, FilePicker const& spec, ContainerWidget* parent) { + FilePickerWidget& widget = scope.adopt(_backend->createFilePicker(parent, spec.mode)); + applyCommon(scope, widget, spec.common); + applyField(scope, widget, spec.field); + widget.setOnPicked(inputEvent( + spec.onPicked, controlled(scope, spec.path, [&widget](std::string const& path) { widget.setPath(path); }))); + return widget; +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +Node Mounted::nonNull(Node root) { + if (!root) { + throw std::invalid_argument{"morph::ui::Mounted: the root node is null"}; + } + return root; +} + +} // namespace morph::ui diff --git a/src/ui/process_state.cpp b/src/ui/process_state.cpp index f2f4cb5aa..daf823083 100644 --- a/src/ui/process_state.cpp +++ b/src/ui/process_state.cpp @@ -19,6 +19,8 @@ #include #include #include +#include +#include #include #include #include @@ -155,6 +157,23 @@ const RunOrigin*& tlsOrigin() { } // namespace morph::session::detail +namespace morph::table { + +TableRuntime const*& detail::tableRuntimeSlot() noexcept { + thread_local TableRuntime const* tls = nullptr; + return tls; +} + +TableRuntime const* currentTableRuntime() noexcept { return detail::tableRuntimeSlot(); } + +std::shared_ptr makeViewCache(ViewCacheOptions options) { + return std::make_shared(std::move(options)); +} + +ViewCacheStats viewCacheStats(ViewCache const& cache) { return cache.stats(); } + +} // namespace morph::table + namespace morph::effects::detail { EffectsMap& mutableEffectsRegistry() { diff --git a/src/ui/table_config.cpp b/src/ui/table_config.cpp new file mode 100644 index 000000000..2bb93fe5f --- /dev/null +++ b/src/ui/table_config.cpp @@ -0,0 +1,937 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +std::string groupedCount(std::int64_t n, std::string_view separator) { + // The magnitude as unsigned, so the most negative count has one too. + std::uint64_t magnitude = n < 0 ? std::uint64_t{0} - static_cast(n) : static_cast(n); + std::string digits; + for (bool more = true; more; more = magnitude != 0U) { + digits.push_back(static_cast('0' + (magnitude % 10U))); + magnitude /= 10U; + } + std::string out = n < 0 ? "-" : ""; + for (std::size_t at = digits.size(); at-- > 0;) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < digits.size() by the loop's decrement test + out.push_back(digits[at]); + if (at != 0 && at % 3 == 0) { + out.append(separator); + } + } + return out; +} + +} // namespace morph::ui + +namespace morph::ui::tableText { + +std::string copied(std::size_t rows, std::size_t unloaded, std::string_view separator) { + std::string out = + "Copied " + groupedCount(static_cast(rows), separator) + (rows == 1 ? " row" : " rows"); + if (unloaded != 0) { + out += ", " + groupedCount(static_cast(unloaded), separator) + + (unloaded == 1 ? " cell was not loaded" : " cells were not loaded"); + } + return out; +} + +std::string notConfigurable(Configure what) { + std::string_view verb = "moved"; + if (!allows(what, Configure::Reorder)) { + if (allows(what, Configure::Hide)) { + verb = "hidden"; + } else if (allows(what, Configure::Pin)) { + verb = "pinned"; + } else if (allows(what, Configure::Resize)) { + verb = "resized"; + } + } + return "This table's columns cannot be " + std::string{verb}; +} + +std::string unreadable(std::size_t cells, std::string_view separator) { + return groupedCount(static_cast(cells), separator) + + (cells == 1 ? " cell could not be read" : " cells could not be read"); +} + +} // namespace morph::ui::tableText + +namespace morph::ui { + +SortChange applySortGesture(SortChain const& chain, std::string const& column, SortGesture gesture, + std::size_t maxSortKeys) { + using table::SortDirection; + auto const held = std::ranges::find(chain, column, &table::SortKey::column); + auto const append = [&]() -> SortChange { + if (chain.size() >= maxSortKeys) { + return {.chain = chain, .refusal = tableText::sortBound(maxSortKeys)}; + } + SortChain out = chain; + out.push_back({.column = column, .dir = SortDirection::Ascending}); + return {.chain = std::move(out), .refusal = std::nullopt}; + }; + switch (gesture) { + case SortGesture::Click: { + bool const firstAscending = + !chain.empty() && chain.front().column == column && chain.front().dir == SortDirection::Ascending; + return {.chain = {{.column = column, + .dir = firstAscending ? SortDirection::Descending : SortDirection::Ascending}}, + .refusal = std::nullopt}; + } + case SortGesture::Ascending: + return {.chain = {{.column = column, .dir = SortDirection::Ascending}}, .refusal = std::nullopt}; + case SortGesture::Descending: + return {.chain = {{.column = column, .dir = SortDirection::Descending}}, .refusal = std::nullopt}; + case SortGesture::Extend: { + if (held == chain.end()) { + return append(); + } + SortChain out = chain; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): held points into chain, and out is a copy of chain + auto& key = out[static_cast(held - chain.begin())]; + key.dir = key.dir == SortDirection::Ascending ? SortDirection::Descending : SortDirection::Ascending; + return {.chain = std::move(out), .refusal = std::nullopt}; + } + case SortGesture::Add: + return held == chain.end() ? append() : SortChange{.chain = chain, .refusal = std::nullopt}; + case SortGesture::Remove: { + SortChain out = chain; + std::erase_if(out, [&](table::SortKey const& key) { return key.column == column; }); + return {.chain = std::move(out), .refusal = std::nullopt}; + } + default: + break; + } + return {.chain = chain, .refusal = std::nullopt}; +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +GestureNeeds needsOf(LayoutGesture const& gesture) { + return std::visit( + [](auto const& alternative) -> GestureNeeds { + using G = std::decay_t; + if constexpr (std::is_same_v || std::is_same_v) { + return {.capability = Configure::Reorder, .lockable = true, .column = alternative.id}; + } else if constexpr (std::is_same_v) { + return {.capability = Configure::Hide, .lockable = true, .column = alternative.id}; + } else if constexpr (std::is_same_v) { + return {.capability = Configure::Hide, .lockable = false, .column = alternative.id}; + } else if constexpr (std::is_same_v || std::is_same_v) { + return {.capability = Configure::Pin, .lockable = true, .column = alternative.id}; + } else if constexpr (std::is_same_v) { + return {.capability = Configure::Resize, .lockable = true, .column = alternative.id}; + } else { + return {}; + } + }, + gesture); +} + +void placeBeside(table::ColumnLayout& layout, std::string const& columnId, std::string const& anchor, bool after) { + if (anchor == columnId) { + return; + } + std::vector order(layout.order().begin(), layout.order().end()); + std::erase(order, columnId); + auto const anchorIndex = static_cast(std::ranges::find(order, anchor) - order.begin()); + layout.move(columnId, after ? anchorIndex + 1 : anchorIndex); +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one visit over every gesture kind. +LayoutResult applyLayoutGesture(table::ColumnLayout& layout, std::span columns, Configure allowed, + LayoutGesture const& gesture) { + auto const find = [&](std::string_view columnId) -> LayoutColumn const* { + auto const found = std::ranges::find(columns, columnId, &LayoutColumn::id); + return found == columns.end() ? nullptr : &*found; + }; + detail::GestureNeeds const needs = detail::needsOf(gesture); + LayoutColumn const* const column = needs.column.empty() ? nullptr : find(needs.column); + if (needs.capability != Configure::None && column == nullptr) { + return {}; + } + if (needs.lockable && column->locked) { + return {.changed = false, .refusal = tableText::locked(column->label)}; + } + if (needs.capability != Configure::None && !allows(allowed, needs.capability)) { + return {.changed = false, .refusal = tableText::notConfigurable(needs.capability)}; + } + if (std::holds_alternative(gesture) && allowed == Configure::None) { + return {.changed = false, .refusal = tableText::notConfigurable(Configure::None)}; + } + bool const grouping = std::holds_alternative(gesture) || std::holds_alternative(gesture); + if (grouping && (allowed & (Configure::Reorder | Configure::Hide)) == Configure::None) { + return {.changed = false, .refusal = tableText::notConfigurable(Configure::Reorder)}; + } + + table::ColumnLayoutValue const before = layout.value(); + std::optional refusal; + std::visit( + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the visitor's arms are the same decision table. + [&](auto const& change) { + using G = std::decay_t; + std::vector const visible = layout.visible(); + [[maybe_unused]] std::size_t const pinned = layout.pinned(); + if constexpr (std::is_same_v) { + std::size_t const from = detail::visibleIndex(visible, change.id); + if (from == visible.size() || change.by == 0) { + return; + } + // A move stays on its side of the pin boundary; crossing it is Pin's and Unpin's. + bool const isPinned = from < pinned; + auto const first = static_cast(isPinned ? 0 : pinned); + auto const last = static_cast(isPinned ? pinned : visible.size()) - 1; + auto const target = std::clamp(static_cast(from) + change.by, first, last); + if (static_cast(target) != from) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): target is clamped to the visible columns' range + detail::placeBeside(layout, change.id, visible[static_cast(target)], change.by > 0); + } + } else if constexpr (std::is_same_v) { + std::size_t const from = detail::visibleIndex(visible, change.id); + if (from == visible.size()) { + return; + } + std::vector others = visible; + std::erase(others, change.id); + if (others.empty()) { + return; + } + std::size_t const target = std::min(change.position, others.size()); + if (target == others.size()) { + detail::placeBeside(layout, change.id, others.back(), true); + } else { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): target < others.size() by the branch above + detail::placeBeside(layout, change.id, others[target], false); + } + // The other pinned columns stay pinned: a drop among them pins the column, a drop past them unpins + // it, and a drop on the boundary keeps its state. + bool const wasPinned = from < pinned; + std::size_t const otherPinned = pinned - (wasPinned ? 1 : 0); + bool const nowPinned = target < otherPinned || (target == otherPinned && wasPinned); + layout.setPinned(otherPinned + (nowPinned ? 1 : 0)); + } else if constexpr (std::is_same_v) { + bool const wasPinned = detail::visibleIndex(visible, change.id) < pinned; + if (!layout.setVisible(change.id, false)) { + refusal = tableText::lastVisible(); + } else if (wasPinned) { + layout.setPinned(pinned - 1); + } + } else if constexpr (std::is_same_v) { + if (detail::visibleIndex(visible, change.id) != visible.size() || + !layout.setVisible(change.id, true)) { + return; + } + // A column shown among the pinned columns joins them, so none of them is pushed out. + if (detail::visibleIndex(layout.visible(), change.id) < pinned) { + layout.setPinned(pinned + 1); + } + } else if constexpr (std::is_same_v) { + std::size_t const index = detail::visibleIndex(visible, change.id); + if (index == visible.size() || index < pinned) { + return; + } + if (pinned == 0) { + detail::placeBeside(layout, change.id, visible.front(), false); + } else { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): pinned is at most the visible count, and nonzero here + detail::placeBeside(layout, change.id, visible[pinned - 1], true); + } + layout.setPinned(pinned + 1); + } else if constexpr (std::is_same_v) { + std::size_t const index = detail::visibleIndex(visible, change.id); + if (index >= pinned) { + return; + } + std::vector others = visible; + std::erase(others, change.id); + if (pinned >= 2) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): pinned is at most the visible count, and others lacks at most the moved column + detail::placeBeside(layout, change.id, others[pinned - 2], true); + } else if (!others.empty()) { + detail::placeBeside(layout, change.id, others.front(), false); + } + layout.setPinned(pinned - 1); + } else if constexpr (std::is_same_v) { + static_cast(layout.setWidth(change.id, change.units)); + } else if constexpr (std::is_same_v) { + layout.reset(); + } else if constexpr (std::is_same_v) { + static_cast(layout.setUnit(change.id, change.dimension, change.unit)); + } else if constexpr (std::is_same_v) { + if (std::ranges::any_of(change.columns, + [&](std::string const& columnId) { return find(columnId) == nullptr; })) { + return; + } + if (change.columns.size() < 2 || change.columns.size() > kMaxGroupColumns) { + refusal = tableText::groupSize(); + return; + } + LayoutColumn const& first = *find(change.columns.front()); + for (std::string const& columnId : change.columns) { + LayoutColumn const& member = *find(columnId); + if (member.kind != first.kind) { + refusal = tableText::groupKind(); + return; + } + for (table::ColumnGroupInfo const& group : layout.groups()) { + if (std::ranges::find(group.columns, columnId) != group.columns.end()) { + refusal = tableText::alreadyGrouped(member.label, group.label); + return; + } + } + } + if (auto formed = layout.formGroup(change.label, change.columns); !formed) { + refusal = std::move(formed.error().message); + } + } else if constexpr (std::is_same_v) { + static_cast(layout.removeGroup(change.id)); + } + }, + gesture); + if (refusal) { + return {.changed = false, .refusal = std::move(refusal)}; + } + return {.changed = layout.value() != before, .refusal = std::nullopt}; +} + +ResolvedTicks resolveTicks(ValueTicks const& ticks, + std::function(std::string const& search)> const& valuesUnder) { + ResolvedTicks out{.ticked = ticks.ticked, .covered = {}, .blanks = ticks.blanks}; + for (TickOp const& op : ticks.ops) { + if (op.operand) { + out.covered.insert_or_assign(*op.operand, op.ticked); + } else if (op.search.empty()) { + out.covered.clear(); + out.ticked = op.ticked; + } else { + for (std::string const& operand : valuesUnder(op.search)) { + out.covered.insert_or_assign(operand, op.ticked); + } + } + } + return out; +} + +ValueFilterPlan planValueFilter(std::int64_t distinct, ResolvedTicks const& ticks, std::size_t maxSetValues) { + using PlanSide = ValueFilterPlan::Side; + std::size_t const total = distinct < 0 ? 0 : static_cast(distinct); + std::size_t const reached = std::min(ticks.covered.size(), total); + auto const tickedCovered = + static_cast(std::ranges::count_if(ticks.covered, [](auto const& entry) { return entry.second; })); + std::size_t const ticked = std::min(total, (ticks.ticked ? total - reached : 0) + tickedCovered); + std::size_t const unticked = total - ticked; + if (ticked == total && ticks.blanks != false) { + return {.side = PlanSide::All, .members = 0, .needsComplement = false}; + } + if (ticked == 0 && ticks.blanks != true) { + return {.side = PlanSide::Nothing, .members = 0, .needsComplement = false}; + } + bool const include = ticked < unticked; + std::size_t const members = include ? ticked : unticked; + if (members > maxSetValues) { + return {.side = PlanSide::Disabled, .members = members, .needsComplement = false}; + } + // The values outside C are on the side `ticks.ticked` puts them. + bool const outsideOnSide = total > reached && (include == ticks.ticked); + return { + .side = include ? PlanSide::Include : PlanSide::Exclude, .members = members, .needsComplement = outsideOnSide}; +} + +std::optional valueFilter(ValueFilterPlan::Side side, std::vector members, + std::optional blanks, ValueForm form) { + using PlanSide = ValueFilterPlan::Side; + if (side != PlanSide::Include && side != PlanSide::Exclude) { + return std::nullopt; + } + std::vector entries; + if (!members.empty()) { + if (form == ValueForm::Set) { + table::FilterEntry entry; + entry.oneOf = std::move(members); + entries.push_back(std::move(entry)); + } else { + for (std::string const& member : members) { + std::size_t const cut = member.find(".."); + table::FilterEntry entry; + entry.between = std::array{member.substr(0, cut), + cut == std::string::npos ? member : member.substr(cut + 2)}; + entries.push_back(std::move(entry)); + } + } + } + if (blanks == (side == PlanSide::Include)) { + table::FilterEntry entry; + entry.isEmpty = true; + entries.push_back(std::move(entry)); + } + if (entries.empty()) { + return std::nullopt; + } + table::ColumnFilter filter{.combine = table::Combine::Any, .include = {}, .exclude = {}}; + (side == PlanSide::Include ? filter.include : filter.exclude) = std::move(entries); + return filter; +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +std::size_t operatorCount(table::FilterEntry const& entry) { + return static_cast(entry.eq.has_value()) + static_cast(entry.ne.has_value()) + + static_cast(entry.lt.has_value()) + static_cast(entry.le.has_value()) + + static_cast(entry.gt.has_value()) + static_cast(entry.ge.has_value()) + + static_cast(entry.between.has_value()) + static_cast(entry.contains.has_value()) + + static_cast(entry.startsWith.has_value()) + + static_cast(entry.endsWith.has_value()) + static_cast(entry.isEmpty.has_value()) + + static_cast(entry.notEmpty.has_value()) + static_cast(entry.oneOf.has_value()); +} + +bool valuesShape(std::span entries, table::ColumnKind kind) { + bool const dates = kind == table::ColumnKind::Date || kind == table::ColumnKind::DateTime; + std::size_t oneOf = 0; + std::size_t between = 0; + std::size_t blanks = 0; + for (table::FilterEntry const& entry : entries) { + if (operatorCount(entry) != 1 || entry.caseSensitive.has_value()) { + return false; + } + if (entry.oneOf) { + ++oneOf; + } else if (entry.between && dates) { + ++between; + } else if (entry.isEmpty == true) { + ++blanks; + } else { + return false; + } + } + if (oneOf > 1 || blanks > 1 || (oneOf == 1 && between != 0)) { + return false; + } + if (oneOf == 0 && between == 0) { + return blanks == 1 && kind != table::ColumnKind::Custom; + } + return true; +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +FilterPart classifyFilter(table::ColumnFilter const& filter, table::ColumnKind kind) { + if (filter.include.empty() && filter.exclude.empty()) { + return FilterPart::None; + } + if (filter.combine != table::Combine::Any || (!filter.include.empty() && !filter.exclude.empty())) { + return FilterPart::Conditions; + } + auto const& side = filter.include.empty() ? filter.exclude : filter.include; + return detail::valuesShape(side, kind) ? FilterPart::Values : FilterPart::Conditions; +} + +std::optional canonicalOperand(std::string_view typed, table::ColumnKind kind, LocaleFacts const& locale, + std::span units, std::string_view chosenUnit) { + using table::ColumnKind; + auto const number = [&](bool fraction) -> std::optional { + std::size_t const first = typed.find_first_not_of(' '); + std::size_t const last = typed.find_last_not_of(' '); + if (first == std::string_view::npos) { + return std::nullopt; + } + auto canonical = render::normalizeLocaleNumber(typed.substr(first, last - first + 1), locale.numeric); + if (!canonical) { + return std::nullopt; + } + std::string_view digits = *canonical; + if (digits.starts_with('-')) { + digits.remove_prefix(1); + } + std::size_t const point = digits.find('.'); + std::string_view const whole = digits.substr(0, point); + std::string_view const part = point == std::string_view::npos ? std::string_view{} : digits.substr(point + 1); + if (whole.empty() || (point != std::string_view::npos && (!fraction || part.empty()))) { + return std::nullopt; + } + return canonical; + }; + switch (kind) { + case ColumnKind::Integer: + case ColumnKind::Key: + return number(false); + case ColumnKind::Decimal: + case ColumnKind::Quantity: + case ColumnKind::Number: + return number(true); + case ColumnKind::Measure: { + auto const measure = parseMeasure(typed, units, locale, chosenUnit); + if (!measure) { + return std::nullopt; + } + return measureOperand(*measure); + } + case ColumnKind::Text: + case ColumnKind::Date: + case ColumnKind::DateTime: + case ColumnKind::Bool: + case ColumnKind::Custom: + return std::string{typed}; + default: + break; + } + return std::string{typed}; +} + +std::expected groupValueFilter(std::string group, std::size_t groupColumns, + std::vector ticked, + std::optional blanks, GroupMatch match, + std::int64_t n) { + table::GroupFilter filter{.group = std::move(group)}; + if (match == GroupMatch::Together) { + if (ticked.size() < 2 || ticked.size() > groupColumns) { + return std::unexpected("All of them, each in a column, takes 2 to " + std::to_string(groupColumns) + + " values"); + } + filter.mode = table::GroupMode::Together; + for (std::string& value : ticked) { + table::FilterEntry entry; + entry.eq = std::move(value); + filter.include.push_back(std::move(entry)); + } + return filter; + } + auto const columns = static_cast(groupColumns); + switch (match) { + case GroupMatch::AnyColumn: + filter.match = {.kind = table::ColumnCount::Kind::Any, .n = 1}; + break; + case GroupMatch::EveryColumn: + filter.match = {.kind = table::ColumnCount::Kind::All, .n = 1}; + break; + case GroupMatch::AtLeast: + case GroupMatch::Exactly: + if (n < (match == GroupMatch::AtLeast ? 1 : 0) || n > columns) { + return std::unexpected("N is " + std::string{match == GroupMatch::AtLeast ? "1" : "0"} + " to " + + std::to_string(groupColumns)); + } + filter.match = {.kind = match == GroupMatch::AtLeast ? table::ColumnCount::Kind::AtLeast + : table::ColumnCount::Kind::Exactly, + .n = n}; + break; + case GroupMatch::Together: + default: + break; + } + bool const withBlanks = match == GroupMatch::AnyColumn && blanks == true; + if (ticked.empty() && !withBlanks) { + return std::unexpected(std::string{"No value is ticked"}); + } + if (!ticked.empty()) { + table::FilterEntry entry; + entry.oneOf = std::move(ticked); + filter.include.push_back(std::move(entry)); + } + if (withBlanks) { + table::FilterEntry entry; + entry.isEmpty = true; + filter.include.push_back(std::move(entry)); + } + return filter; +} + +std::vector conditionOps(table::ColumnKind kind) { + using enum ConditionOp; + using table::ColumnKind; + switch (kind) { + case ColumnKind::Text: + return {Equals, NotEquals, Contains, BeginsWith, EndsWith}; + case ColumnKind::Integer: + case ColumnKind::Key: + case ColumnKind::Decimal: + case ColumnKind::Quantity: + case ColumnKind::Number: + case ColumnKind::Date: + case ColumnKind::DateTime: + case ColumnKind::Measure: + return {Equals, NotEquals, Less, LessOrEqual, Greater, GreaterOrEqual, Between}; + case ColumnKind::Bool: + return {}; + case ColumnKind::Custom: + return {IsEmpty, IsNotEmpty}; + default: + break; + } + return {}; +} + +std::string_view conditionLabel(ConditionOp op, table::ColumnKind kind) { + bool const words = kind == table::ColumnKind::Text; + switch (op) { + case ConditionOp::Equals: + return words ? "equals" : "="; + case ConditionOp::NotEquals: + return words ? "does not equal" : "≠"; + case ConditionOp::Contains: + return "contains"; + case ConditionOp::BeginsWith: + return "begins with"; + case ConditionOp::EndsWith: + return "ends with"; + case ConditionOp::Less: + return "<"; + case ConditionOp::LessOrEqual: + return "≤"; + case ConditionOp::Greater: + return ">"; + case ConditionOp::GreaterOrEqual: + return "≥"; + case ConditionOp::Between: + return "between"; + case ConditionOp::IsEmpty: + return "is empty"; + case ConditionOp::IsNotEmpty: + return "is not empty"; + default: + break; + } + return {}; +} + +table::FilterEntry conditionEntry(ConditionOp op, std::string operand, std::string second, bool matchCase) { + table::FilterEntry entry; + bool text = false; + switch (op) { + case ConditionOp::Equals: + entry.eq = std::move(operand); + text = true; + break; + case ConditionOp::NotEquals: + entry.ne = std::move(operand); + text = true; + break; + case ConditionOp::Contains: + entry.contains = std::move(operand); + text = true; + break; + case ConditionOp::BeginsWith: + entry.startsWith = std::move(operand); + text = true; + break; + case ConditionOp::EndsWith: + entry.endsWith = std::move(operand); + text = true; + break; + case ConditionOp::Less: + entry.lt = std::move(operand); + break; + case ConditionOp::LessOrEqual: + entry.le = std::move(operand); + break; + case ConditionOp::Greater: + entry.gt = std::move(operand); + break; + case ConditionOp::GreaterOrEqual: + entry.ge = std::move(operand); + break; + case ConditionOp::Between: + entry.between = std::array{std::move(operand), std::move(second)}; + break; + case ConditionOp::IsEmpty: + entry.isEmpty = true; + break; + case ConditionOp::IsNotEmpty: + entry.notEmpty = true; + break; + default: + break; + } + if (text && matchCase) { + entry.caseSensitive = true; + } + return entry; +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +TableMenuEntry command(std::string label, MenuCommand command, bool enabled, std::string keys, std::string argument) { + MenuEntry entry; + entry.label = std::move(label); + entry.keys = std::move(keys); + entry.enabled = enabled; + return {.entry = std::move(entry), .command = command, .argument = std::move(argument), .items = {}}; +} + +std::vector joinSections(std::vector> sections) { + std::vector out; + for (auto& section : sections) { + if (section.empty()) { + continue; + } + if (!out.empty()) { + MenuEntry line; + line.separator = true; + out.push_back( + {.entry = std::move(line), .command = MenuCommand::SortAscending, .argument = {}, .items = {}}); + } + std::ranges::move(section, std::back_inserter(out)); + } + return out; +} + +TableMenuEntry heading(std::string label) { + MenuEntry entry; + entry.label = std::move(label); + entry.heading = true; + entry.enabled = false; + return {.entry = std::move(entry), .command = MenuCommand::None, .argument = {}, .items = {}}; +} + +TableMenuEntry viewEntry(std::string const& name, MenuCommand command, bool current, bool modified) { + TableMenuEntry entry = detail::command(current && modified ? name + " (modified)" : name, command, true, {}, name); + entry.entry.checked = current; + return entry; +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +TableMenuEntry viewsMenu(ViewsMenuInput const& input) { + using detail::command; + bool const onOwn = + input.current.has_value() && !input.currentShared && std::ranges::contains(input.own, *input.current); + bool const onShared = + input.current.has_value() && input.currentShared && std::ranges::contains(input.shared, *input.current); + std::vector own; + own.reserve(input.own.size()); + for (std::string const& name : input.own) { + own.push_back( + detail::viewEntry(name, MenuCommand::ApplyView, onOwn && name == *input.current, input.modified)); + } + std::vector manage; + manage.push_back(command("Save view…", MenuCommand::SaveView)); + manage.push_back(command("Rename view…", MenuCommand::RenameView, onOwn)); + manage.push_back(command("Remove view", MenuCommand::RemoveView, onOwn)); + manage.push_back(command("Set as default", MenuCommand::SetDefaultView, onOwn)); + TableMenuEntry start = command("Start from the default view", MenuCommand::DefaultOnMount); + start.entry.checked = input.defaultOnMount; + manage.push_back(std::move(start)); + std::vector shared; + if (!input.shared.empty()) { + shared.push_back(detail::heading("Shared views")); + for (std::string const& name : input.shared) { + shared.push_back(detail::viewEntry(name, MenuCommand::ApplySharedView, onShared && name == *input.current, + input.modified)); + } + } + std::vector sharing; + if (onShared) { + sharing.push_back(command("Save as my view", MenuCommand::SaveAsMyView, true, {}, *input.current)); + } + if (input.shares) { + sharing.push_back(command("Publish view…", MenuCommand::PublishView)); + } + TableMenuEntry views = command("Views", MenuCommand::None); + views.items = detail::joinSections({std::move(own), std::move(manage), std::move(shared), std::move(sharing)}); + return views; +} + +std::vector headerMenu(HeaderMenuInput const& input) { + using detail::command; + std::vector sort; + if (input.sortable) { + bool const held = input.sortPlace.has_value(); + sort.push_back(command("Sort ascending", MenuCommand::SortAscending)); + sort.push_back(command("Sort descending", MenuCommand::SortDescending)); + sort.push_back(command("Add to sort", MenuCommand::AddToSort, !held && input.chainSize < input.maxSortKeys)); + sort.push_back(command("Remove from sort", MenuCommand::RemoveFromSort, held)); + } + std::vector filter; + if (input.filterable) { + filter.push_back(command("Filter…", MenuCommand::Filter)); + } + for (MenuGroup const& group : input.groups) { + filter.push_back(command(detail::groupLabel(group), MenuCommand::FilterGroup, true, {}, group.id)); + } + std::vector arrange; + bool const free = !input.column.locked; + if (allows(input.allowed, Configure::Reorder)) { + arrange.push_back(command("Move left", MenuCommand::MoveLeft, + free && input.visibleIndex > 0 && input.visibleIndex != input.pinned, + "Ctrl+Shift+Left")); + arrange.push_back( + command("Move right", MenuCommand::MoveRight, + free && input.visibleIndex + 1 < input.visibleCount && input.visibleIndex + 1 != input.pinned, + "Ctrl+Shift+Right")); + } + if (allows(input.allowed, Configure::Pin)) { + bool const pinned = input.visibleIndex < input.pinned; + arrange.push_back(pinned ? command("Unpin", MenuCommand::UnpinColumn, free) + : command("Pin column", MenuCommand::PinColumn, free)); + } + if (allows(input.allowed, Configure::Hide)) { + arrange.push_back(command("Hide column", MenuCommand::HideColumn, free && input.visibleCount > 1)); + } + std::vector units; + if (!input.dimensions.empty()) { + TableMenuEntry display = command("Display unit", MenuCommand::DisplayUnit); + for (MenuDimension const& dimension : input.dimensions) { + for (std::string const& unit : dimension.units) { + TableMenuEntry item = command(dimension.dimension + ": " + unit, MenuCommand::DisplayUnit, true, {}, + dimension.dimension + '\x1F' + unit); + item.entry.checked = unit == dimension.chosen; + display.items.push_back(std::move(item)); + } + } + units.push_back(std::move(display)); + } + return detail::joinSections({std::move(sort), std::move(filter), std::move(arrange), std::move(units)}); +} + +std::vector tableMenu(TableMenuInput const& input) { + using detail::command; + bool const arranging = input.allowed != Configure::None; + std::vector configure; + if (arranging) { + configure.push_back(command("Columns…", MenuCommand::Columns)); + } + configure.push_back(command("Sort…", MenuCommand::SortDialog)); + for (MenuGroup const& group : input.groups) { + configure.push_back(command(detail::groupLabel(group), MenuCommand::FilterGroup, true, {}, group.id)); + } + configure.push_back(command("Clear all filters", MenuCommand::ClearAllFilters, input.anyFilter)); + if (arranging) { + configure.push_back(command("Reset columns", MenuCommand::ResetColumns)); + } + std::vector views; + if (input.views) { + views.push_back(viewsMenu(*input.views)); + } + std::vector copy; + copy.push_back(command("Copy", MenuCommand::Copy, true, "Ctrl+C")); + copy.push_back(command("Copy with headers", MenuCommand::CopyWithHeaders)); + return detail::joinSections({std::move(configure), std::move(views), std::move(copy)}); +} + +// NOLINTNEXTLINE(misc-no-recursion): one call per submenu level, bounded by the menu's depth. +std::vector menuEntries(std::span entries) { + std::vector out; + out.reserve(entries.size()); + for (TableMenuEntry const& entry : entries) { + MenuEntry shown = entry.entry; + shown.items = menuEntries(entry.items); + out.push_back(std::move(shown)); + } + return out; +} + +TableMenuEntry const* chosen(std::span entries, std::span path) { + TableMenuEntry const* found = nullptr; + for (std::size_t const index : path) { + if (index >= entries.size()) { + return nullptr; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < entries.size() by the check above + found = &entries[index]; + if (found->entry.separator || found->entry.heading || !found->entry.enabled) { + return nullptr; + } + entries = found->items; + } + return found != nullptr && found->items.empty() ? found : nullptr; +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +void appendField(std::string& out, std::string_view text) { + for (std::size_t at = 0; at < text.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < text.size() by the loop; at + 1 by the condition + char const character = text[at]; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < text.size() by the loop; at + 1 by the condition + if (character == '\r' && at + 1 < text.size() && text[at + 1] == '\n') { + ++at; + out.push_back(' '); + } else if (character == '\t' || character == '\r' || character == '\n') { + out.push_back(' '); + } else { + out.push_back(character); + } + } +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +CopiedText copyText(std::span labels, + std::span> const> rows) { + CopiedText out; + auto const line = [&](auto const& cells, auto const& textOf) { + bool first = true; + for (auto const& cell : cells) { + if (!first) { + out.text.push_back('\t'); + } + first = false; + detail::appendField(out.text, textOf(cell)); + } + }; + bool any = false; + if (!labels.empty()) { + line(labels, [](std::string const& label) -> std::string_view { return label; }); + any = true; + } + for (auto const& row : rows) { + if (any) { + out.text.push_back('\n'); + } + any = true; + line(row, [&](std::optional const& cell) -> std::string_view { + if (!cell) { + ++out.unloaded; + return {}; + } + return *cell; + }); + } + return out; +} + +} // namespace morph::ui diff --git a/src/ui/table_dialogs.cpp b/src/ui/table_dialogs.cpp new file mode 100644 index 000000000..f0dde6883 --- /dev/null +++ b/src/ui/table_dialogs.cpp @@ -0,0 +1,386 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +ChooserState chooserState(table::ColumnLayout const& layout, std::span columns, + Configure allowed) { + ChooserState out; + out.reorder = allows(allowed, Configure::Reorder); + out.hide = allows(allowed, Configure::Hide); + out.grouping = out.reorder || out.hide; + std::vector const visible = layout.visible(); + std::size_t const pinned = layout.pinned(); + for (std::string const& columnId : layout.order()) { + auto const found = std::ranges::find(columns, columnId, &LayoutColumn::id); + if (found == columns.end()) { + continue; + } + std::size_t const index = detail::visibleIndex(visible, columnId); + bool const shown = index < visible.size(); + bool const free = !found->locked; + out.columns.push_back(ChooserColumn{ + .id = columnId, + .label = found->label, + .kind = found->kind, + .shown = shown, + .toggles = out.hide && free && (!shown || visible.size() != 1), + // A move stays on its side of the pin boundary, as the header's "Move left" and "Move right" do. + .up = out.reorder && free && shown && index > 0 && index != pinned, + .down = out.reorder && free && shown && index + 1 < visible.size() && index + 1 != pinned, + .movable = out.reorder, + }); + } + for (table::ColumnGroupInfo const& group : layout.groups()) { + out.groups.push_back(ChooserGroup{.id = group.id, .label = group.label, .columns = group.columns.size()}); + } + return out; +} + +bool canFormGroup(GroupDraft const& draft) { + bool const named = draft.label.find_first_not_of(" \t") != std::string::npos; + return named && draft.ticked.size() >= 2 && draft.ticked.size() <= kMaxGroupColumns; +} + +Node columnChooser(ColumnChooserView view) { + auto const viewPtr = std::make_shared(std::move(view)); + Node const rows = forEach( + [viewPtr] { return viewPtr->state().columns; }, + [](ChooserColumn const& column) -> Key { return Key{column.id}; }, + [viewPtr](reactive::Signal const& row) { + std::string const columnId = row.peek().id; + Checkbox show{.label = [&row] { return row.get().label; }, + .checked = [&row] { return row.get().shown; }, + .onToggle = [viewPtr, columnId](bool checked) { viewPtr->onShow(columnId, checked); }}; + show.common.enabled = [&row] { return row.get().toggles; }; + show.common.testId = "table_columns_show_" + columnId; + show.common.layout.width = Sizing::stretch(); + Button moveUp{.label = std::string{"Move up"}, + .onClick = [viewPtr, columnId] { viewPtr->onMove(columnId, -1); }}; + moveUp.common.enabled = [&row] { return row.get().up; }; + moveUp.common.visible = row.peek().movable; + moveUp.common.testId = "table_columns_up_" + columnId; + Button down{.label = std::string{"Move down"}, + .onClick = [viewPtr, columnId] { viewPtr->onMove(columnId, 1); }}; + down.common.enabled = [&row] { return row.get().down; }; + down.common.visible = row.peek().movable; + down.common.testId = "table_columns_down_" + columnId; + return ui::row( + Row{.children = {checkbox(std::move(show)), button(std::move(moveUp)), button(std::move(down))}, + .gap = 1}); + }, + Axis::Vertical, 1); + + Button reset{.label = std::string{"Reset columns"}, .onClick = [viewPtr] { viewPtr->onReset(); }}; + reset.common.testId = "table_columns_reset"; + Button group{.label = std::string{"Group columns…"}, .onClick = [viewPtr] { + GroupDraft draft = viewPtr->draft(); + draft.open = true; + viewPtr->setDraft(std::move(draft)); + }}; + group.common.testId = "table_columns_group"; + group.common.visible = [viewPtr] { return viewPtr->state().grouping && !viewPtr->draft().open; }; + + TextInput label{.value = [viewPtr] { return viewPtr->draft().label; }, + .onChange = + [viewPtr](std::string text) { + GroupDraft draft = viewPtr->draft(); + draft.label = std::move(text); + viewPtr->setDraft(std::move(draft)); + }, + .placeholder = std::string{"Group name"}}; + label.label = std::string{"Group name"}; + label.common.testId = "table_group_label"; + Node const ticks = forEach( + [viewPtr] { return viewPtr->state().columns; }, + [](ChooserColumn const& column) -> Key { return Key{column.id}; }, + [viewPtr](reactive::Signal const& row) { + std::string const columnId = row.peek().id; + Checkbox tick{ + .label = [&row] { return row.get().label; }, + .checked = [viewPtr, columnId] { return std::ranges::contains(viewPtr->draft().ticked, columnId); }, + .onToggle = + [viewPtr, columnId](bool checked) { + GroupDraft draft = viewPtr->draft(); + std::erase(draft.ticked, columnId); + if (checked) { + draft.ticked.push_back(columnId); + } + viewPtr->setDraft(std::move(draft)); + }}; + // Once a column is ticked, only columns of its kind can join it. + tick.common.enabled = [viewPtr, &row] { + GroupDraft const draft = viewPtr->draft(); + if (draft.ticked.empty()) { + return true; + } + std::vector const columns = viewPtr->state().columns; + auto const first = std::ranges::find(columns, draft.ticked.front(), &ChooserColumn::id); + return first == columns.end() || first->kind == row.get().kind; + }; + tick.common.testId = "table_group_column_" + columnId; + return checkbox(std::move(tick)); + }, + Axis::Vertical, 0); + Button create{.label = std::string{"Create group"}, .onClick = [viewPtr] { + GroupDraft const draft = viewPtr->draft(); + if (!canFormGroup(draft)) { + return; + } + std::vector columns; + for (ChooserColumn const& column : viewPtr->state().columns) { + if (std::ranges::contains(draft.ticked, column.id)) { + columns.push_back(column.id); + } + } + if (viewPtr->onFormGroup(draft.label, std::move(columns))) { + viewPtr->setDraft(GroupDraft{}); + } + }}; + create.common.testId = "table_group_create"; + create.common.enabled = [viewPtr] { return canFormGroup(viewPtr->draft()); }; + Column form{.children = {textInput(std::move(label)), ticks, button(std::move(create))}, .gap = 1}; + form.common.visible = [viewPtr] { return viewPtr->draft().open; }; + + Node const groups = forEach( + [viewPtr] { return viewPtr->state().groups; }, [](ChooserGroup const& line) -> Key { return Key{line.id}; }, + [viewPtr](reactive::Signal const& line) { + std::string const columnId = line.peek().id; + Text text{.text = [&line] { return chooserGroupText(line.get()); }}; + text.common.testId = "table_group_" + columnId; + text.common.layout.width = Sizing::stretch(); + Button remove{.label = std::string{"Remove group"}, + .onClick = [viewPtr, columnId] { viewPtr->onRemoveGroup(columnId); }}; + remove.common.testId = "table_group_remove_" + columnId; + return ui::row(Row{.children = {ui::text(std::move(text)), button(std::move(remove))}, .gap = 1}); + }, + Axis::Vertical, 1); + + Button done{.label = std::string{"Done"}, .emphasis = ButtonEmphasis::Primary, .onClick = [viewPtr] { + viewPtr->onClose(); + }}; + done.common.testId = "table_columns_done"; + Node const actions = ui::row(Row{.children = {button(std::move(reset)), button(std::move(group))}, .gap = 1}); + Node const content = ui::column( + Column{.children = {rows, actions, ui::column(std::move(form)), groups, button(std::move(done))}, .gap = 2}); + Dialog dialog{.open = [viewPtr] { return viewPtr->open(); }, + .title = std::string{"Columns"}, + .child = content, + .onDismiss = [viewPtr] { viewPtr->onClose(); }}; + dialog.common.testId = "table_columns"; + return ui::dialog(std::move(dialog)); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one visit over the edit kinds. +SortChange applySortEdit(SortChain const& chain, std::span sortable, SortEdit const& edit, + std::size_t maxSortKeys) { + auto const unchanged = [&chain] { return SortChange{.chain = chain, .refusal = std::nullopt}; }; + return std::visit( + [&](auto const& alternative) -> SortChange { + using E = std::decay_t; + if constexpr (std::is_same_v) { + auto const free = std::ranges::find_if(sortable, [&](std::string const& columnId) { + return std::ranges::find(chain, columnId, &table::SortKey::column) == chain.end(); + }); + if (chain.size() >= maxSortKeys) { + return {.chain = chain, .refusal = tableText::sortBound(maxSortKeys)}; + } + return free == sortable.end() ? unchanged() + : applySortGesture(chain, *free, SortGesture::Add, maxSortKeys); + } else { + if (alternative.index >= chain.size()) { + return unchanged(); + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < chain.size() by the check above + table::SortKey const& key = chain[alternative.index]; + if constexpr (std::is_same_v) { + return applySortGesture(chain, key.column, SortGesture::Remove, maxSortKeys); + } else if constexpr (std::is_same_v) { + return key.dir == alternative.direction + ? unchanged() + : applySortGesture(chain, key.column, SortGesture::Extend, maxSortKeys); + } else if constexpr (std::is_same_v) { + auto const target = static_cast(alternative.index) + alternative.by; + if (alternative.by == 0 || target < 0 || static_cast(target) >= chain.size()) { + return unchanged(); + } + SortChain out = chain; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): target < chain.size() by the test above + std::swap(out[alternative.index], out[static_cast(target)]); + return {.chain = std::move(out), .refusal = std::nullopt}; + } else { + bool const sorts = std::ranges::contains(sortable, alternative.column); + auto const held = std::ranges::find(chain, alternative.column, &table::SortKey::column); + if (!sorts || (held != chain.end() && + held != chain.begin() + static_cast(alternative.index))) { + return unchanged(); + } + SortChain out = chain; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < chain.size() by the check above + out[alternative.index].column = alternative.column; + return {.chain = std::move(out), .refusal = std::nullopt}; + } + } + }, + edit); +} + +std::vector sortDialogKeys(SortChain const& chain, std::span sortable) { + std::vector out; + out.reserve(chain.size()); + for (std::size_t at = 0; at < chain.size(); ++at) { + SortDialogKey key{ + .index = at, + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < chain.size() by the loop + .column = chain[at].column, + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < chain.size() by the loop + .direction = chain[at].dir, + .columns = {}, + .up = at > 0, + .down = at + 1 < chain.size()}; + for (SortColumnOption const& option : sortable) { + auto const held = std::ranges::find(chain, option.id, &table::SortKey::column); + if (held == chain.end() || held == chain.begin() + static_cast(at)) { + key.columns.push_back(SelectOption{.key = Key{option.id}, .label = option.label}); + } + } + out.push_back(std::move(key)); + } + return out; +} + +Node sortDialog(SortDialogView view) { + auto const viewPtr = std::make_shared(std::move(view)); + Node const keys = forEach( + [viewPtr] { + std::vector const sortable = viewPtr->sortable(); + return sortDialogKeys(viewPtr->chain(), sortable); + }, + [](SortDialogKey const& key) -> Key { return Key{static_cast(key.index)}; }, + [viewPtr](reactive::Signal const& row) { + std::size_t const index = row.peek().index; + std::string const position = std::to_string(index); + Select column{.options = [&row] { return row.get().columns; }, + .selected = [&row] { return std::optional{Key{row.get().column}}; }, + .onSelect = + [viewPtr, index](Key const& key) { + if (std::string const* const columnId = std::get_if(&key)) { + viewPtr->onEdit(SetSortColumn{.index = index, .column = *columnId}); + } + }}; + column.label = std::string{"Column"}; + column.common.testId = "table_sort_column_" + position; + column.common.layout.width = Sizing::stretch(); + Select direction{ + .options = std::vector{{.key = Key{std::string{"ascending"}}, .label = "ascending"}, + {.key = Key{std::string{"descending"}}, .label = "descending"}}, + .selected = + [&row] { + return std::optional{Key{std::string{ + row.get().direction == table::SortDirection::Descending ? "descending" : "ascending"}}}; + }, + .onSelect = + [viewPtr, index](Key const& key) { + std::string const* const name = std::get_if(&key); + if (name != nullptr && (*name == "ascending" || *name == "descending")) { + viewPtr->onEdit(SetSortDirection{.index = index, + .direction = *name == "descending" + ? table::SortDirection::Descending + : table::SortDirection::Ascending}); + } + }}; + direction.label = std::string{"Direction"}; + direction.common.testId = "table_sort_direction_" + position; + Button moveUp{.label = std::string{"Move up"}, + .onClick = [viewPtr, index] { viewPtr->onEdit(MoveSortKey{.index = index, .by = -1}); }}; + moveUp.common.enabled = [&row] { return row.get().up; }; + moveUp.common.testId = "table_sort_up_" + position; + Button down{.label = std::string{"Move down"}, + .onClick = [viewPtr, index] { viewPtr->onEdit(MoveSortKey{.index = index, .by = 1}); }}; + down.common.enabled = [&row] { return row.get().down; }; + down.common.testId = "table_sort_down_" + position; + Button remove{.label = std::string{"Remove"}, + .onClick = [viewPtr, index] { viewPtr->onEdit(RemoveSortKey{.index = index}); }}; + remove.common.testId = "table_sort_remove_" + position; + return ui::row( + Row{.children = {select(std::move(column)), select(std::move(direction)), button(std::move(moveUp)), + button(std::move(down)), button(std::move(remove))}, + .gap = 1}); + }, + Axis::Vertical, 1); + Button add{.label = std::string{"Add key"}, .onClick = [viewPtr] { viewPtr->onEdit(AddSortKey{}); }}; + add.common.testId = "table_sort_add"; + add.common.enabled = [viewPtr] { + SortChain const chain = viewPtr->chain(); + return std::ranges::any_of(viewPtr->sortable(), [&chain](SortColumnOption const& option) { + return std::ranges::find(chain, option.id, &table::SortKey::column) == chain.end(); + }); + }; + Button done{.label = std::string{"Done"}, .emphasis = ButtonEmphasis::Primary, .onClick = [viewPtr] { + viewPtr->onClose(); + }}; + done.common.testId = "table_sort_done"; + Node const content = + ui::column(Column{.children = {keys, button(std::move(add)), button(std::move(done))}, .gap = 2}); + Dialog dialog{.open = [viewPtr] { return viewPtr->open(); }, + .title = std::string{"Sort"}, + .child = content, + .onDismiss = [viewPtr] { viewPtr->onClose(); }}; + dialog.common.testId = "table_sort"; + return ui::dialog(std::move(dialog)); +} + +Node viewNameDialog(ViewNameDialogView view) { + auto const viewPtr = std::make_shared(std::move(view)); + TextInput name{.value = [viewPtr] { return viewPtr->name(); }, + .onChange = [viewPtr](std::string text) { viewPtr->onName(std::move(text)); }, + .onSubmit = + [viewPtr](std::string text) { + if (!blankViewName(text)) { + viewPtr->onName(std::move(text)); + viewPtr->onSave(); + } + }, + .placeholder = std::string{"View name"}}; + name.label = std::string{"View name"}; + name.common.testId = "table_view_name"; + Button save{.label = std::string{"Save"}, .emphasis = ButtonEmphasis::Primary, .onClick = [viewPtr] { + viewPtr->onSave(); + }}; + save.common.testId = "table_view_save"; + save.common.enabled = [viewPtr] { return !blankViewName(viewPtr->name()); }; + Button cancel{.label = std::string{"Cancel"}, .onClick = [viewPtr] { viewPtr->onClose(); }}; + cancel.common.testId = "table_view_cancel"; + Node const content = ui::column( + Column{.children = {textInput(std::move(name)), + ui::row(Row{.children = {button(std::move(save)), button(std::move(cancel))}, .gap = 1})}, + .gap = 2}); + Dialog dialog{.open = [viewPtr] { return viewPtr->open(); }, + .title = [viewPtr] { return viewPtr->title(); }, + .child = content, + .onDismiss = [viewPtr] { viewPtr->onClose(); }}; + dialog.common.testId = "table_view_dialog"; + return ui::dialog(std::move(dialog)); +} + +} // namespace morph::ui diff --git a/src/ui/table_filter_menu.cpp b/src/ui/table_filter_menu.cpp new file mode 100644 index 000000000..b9e5bdcfb --- /dev/null +++ b/src/ui/table_filter_menu.cpp @@ -0,0 +1,1518 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +std::optional groupFilterIndex(table::FilterSpec const& filters, FilterTarget const& target) { + for (std::size_t at = 0; at < filters.groups.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < filters.groups.size() by the loop + table::GroupFilter const& group = filters.groups[at]; + bool const same = target.formed ? group.group.empty() && group.columns == target.columns + : !target.group.empty() && group.group == target.group; + if (same) { + return at; + } + } + return std::nullopt; +} + +bool FilterMenuState::operator==(FilterMenuState const& other) const { + return open == other.open && opening == other.opening && search == other.search && list == other.list && + distinct == other.distinct && total == other.total && blanks == other.blanks && invalid == other.invalid && + partial == other.partial && listedOnce == other.listedOnce && ticks.ticked == other.ticks.ticked && + ticks.blanks == other.ticks.blanks && ticks.ops.size() == other.ticks.ops.size() && + std::ranges::equal(ticks.ops, other.ticks.ops, + [](TickOp const& lhs, TickOp const& rhs) { + return lhs.search == rhs.search && lhs.operand == rhs.operand && + lhs.ticked == rhs.ticked; + }) && + dates == other.dates && conditions == other.conditions && matchCase == other.matchCase && + combine == other.combine && match == other.match && count == other.count && refusal == other.refusal && + target.column == other.target.column && target.group == other.target.group && + target.columns == other.target.columns; +} + +} // namespace morph::ui + +namespace morph::ui::detail::filtermenu { + +std::string folded(std::string_view text) { + std::string out{text}; + for (char& letter : out) { + letter = static_cast(std::tolower(static_cast(letter))); + } + return out; +} + +std::optional dayOf(std::string_view text) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): text.size() >= 10 by the first clause + if (text.size() < 10 || text[4] != '-' || text[7] != '-') { + return std::nullopt; + } + int year = 0; + unsigned month = 0; + unsigned day = 0; + if (!readNumber(text, 0, 4, year) || !readNumber(text, 5, 2, month) || !readNumber(text, 8, 2, day)) { + return std::nullopt; + } + std::chrono::year_month_day const date{std::chrono::year{year}, std::chrono::month{month}, std::chrono::day{day}}; + if (!date.ok()) { + return std::nullopt; + } + return std::chrono::sys_days{date}.time_since_epoch().count(); +} + +std::optional> rangeOf(std::string_view operand) { + std::size_t const cut = operand.find(".."); + if (cut == std::string_view::npos) { + return std::nullopt; + } + auto const first = dayOf(operand.substr(0, cut)); + auto const last = dayOf(operand.substr(cut + 2)); + if (!first || !last) { + return std::nullopt; + } + return std::pair{*first, *last}; +} + +std::string rangeText(std::int64_t first, std::int64_t last, bool dateTime) { + return dateTime ? table::detail::isoDate(first) + "T00:00:00Z.." + table::detail::isoDate(last) + "T23:59:59Z" + : table::detail::isoDate(first) + ".." + table::detail::isoDate(last); +} + +std::pair coverOf(std::span ranges, std::string const& bucket) { + auto const range = rangeOf(bucket); + bool covered = false; + bool own = false; + for (std::string const& ticked : ranges) { + if (ticked == bucket) { + covered = true; + own = true; + continue; + } + if (auto const held = rangeOf(ticked); + held && range && held->first <= range->first && range->second <= held->second) { + covered = true; + } + } + return {covered, own}; +} + +std::optional draftOf(table::FilterEntry const& entry) { + if (::morph::ui::detail::operatorCount(entry) != 1) { + return std::nullopt; + } + ConditionDraft draft; + auto const take = [&](ConditionOp op, std::optional const& operand) { + if (operand) { + draft.op = op; + draft.operand = *operand; + } + }; + take(ConditionOp::Equals, entry.eq); + take(ConditionOp::NotEquals, entry.ne); + take(ConditionOp::Contains, entry.contains); + take(ConditionOp::BeginsWith, entry.startsWith); + take(ConditionOp::EndsWith, entry.endsWith); + take(ConditionOp::Less, entry.lt); + take(ConditionOp::LessOrEqual, entry.le); + take(ConditionOp::Greater, entry.gt); + take(ConditionOp::GreaterOrEqual, entry.ge); + if (entry.between) { + draft.op = ConditionOp::Between; + draft.operand = std::get<0>(*entry.between); + draft.second = std::get<1>(*entry.between); + } + if (entry.isEmpty == true) { + draft.op = ConditionOp::IsEmpty; + } + if (entry.notEmpty == true) { + draft.op = ConditionOp::IsNotEmpty; + } + return draft.op ? std::optional{draft} : std::nullopt; +} + +} // namespace morph::ui::detail::filtermenu + +namespace morph::ui { + +std::vector mergeDateRanges(std::span ticked, bool dateTime) { + std::vector> ranges; + for (std::string const& operand : ticked) { + if (auto const range = detail::filtermenu::rangeOf(operand)) { + ranges.push_back(*range); + } + } + std::ranges::sort(ranges); + std::vector> merged; + for (auto const& range : ranges) { + if (!merged.empty() && range.first <= merged.back().second + 1) { + merged.back().second = std::max(merged.back().second, range.second); + } else { + merged.push_back(range); + } + } + std::vector out; + out.reserve(merged.size()); + for (auto const& [first, last] : merged) { + out.push_back(detail::filtermenu::rangeText(first, last, dateTime)); + } + return out; +} + +ValueTicks ticksOfFilter(table::ColumnFilter const& filter) { + bool const include = !filter.include.empty(); + auto const& side = include ? filter.include : filter.exclude; + ValueTicks ticks{.ticked = !include, .ops = {}, .blanks = !include}; + for (table::FilterEntry const& entry : side) { + if (entry.oneOf) { + for (std::string const& member : *entry.oneOf) { + ticks.ops.push_back(TickOp{.search = {}, .operand = member, .ticked = include}); + } + } + if (entry.isEmpty == true) { + ticks.blanks = include; + } + } + return ticks; +} + +std::optional> draftsOf(std::span entries) { + if (entries.size() > 2) { + return std::nullopt; + } + std::array out; + for (std::size_t at = 0; at < entries.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < entries.size() by the loop + auto draft = detail::filtermenu::draftOf(entries[at]); + if (!draft) { + return std::nullopt; + } + out.at(at) = std::move(*draft); + } + return out; +} + +table::ColumnCount columnCountOf(GroupMatch match, std::int64_t n) { + switch (match) { + case GroupMatch::EveryColumn: + return {.kind = table::ColumnCount::Kind::All, .n = 1}; + case GroupMatch::AtLeast: + return {.kind = table::ColumnCount::Kind::AtLeast, .n = n}; + case GroupMatch::Exactly: + return {.kind = table::ColumnCount::Kind::Exactly, .n = n}; + case GroupMatch::AnyColumn: + case GroupMatch::Together: + default: + break; + } + return {.kind = table::ColumnCount::Kind::Any, .n = 1}; +} + +std::string_view matchLabel(GroupMatch match) { + switch (match) { + case GroupMatch::AnyColumn: + return "in any column"; + case GroupMatch::EveryColumn: + return "in every column"; + case GroupMatch::AtLeast: + return "in at least N columns"; + case GroupMatch::Exactly: + return "in exactly N columns"; + case GroupMatch::Together: + return "all of them, each in a column"; + default: + break; + } + return {}; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one ordered setup sharing `next`. +void FilterMenu::open(FilterTarget target) { + _searchTimer.cancel(); + _sendTimer.cancel(); + ++_serial; + FilterMenuState next; + next.open = true; + next.opening = _state.peek().opening + 1; + next.target = std::move(target); + FilterTarget const& focus = next.target; + bool const isGroup = focus.column.empty(); + table::ColumnKind const kind = focus.shown.info.kind; + table::FilterSpec const filters = _host.filters ? _host.filters() : table::FilterSpec{}; + if (isGroup) { + next.ticks.ticked = false; + if (auto const index = groupFilterIndex(filters, focus)) { + readGroup(next, filters.groups.at(*index)); + } + } else if (auto const held = filters.columns.find(focus.column); held != filters.columns.end()) { + if (classifyFilter(held->second, kind) == FilterPart::Values && valuesListed(next)) { + if (dates(next)) { + for (table::FilterEntry const& entry : held->second.include) { + if (entry.between) { + next.dates.push_back(std::get<0>(*entry.between) + ".." + std::get<1>(*entry.between)); + } + if (entry.isEmpty == true) { + next.ticks.blanks = true; + } + } + } else { + next.ticks = ticksOfFilter(held->second); + } + } else if (auto drafts = draftsOf(held->second.include); drafts && held->second.exclude.empty()) { + next.conditions = std::move(*drafts); + next.combine = held->second.combine; + next.matchCase = std::ranges::any_of( + held->second.include, [](table::FilterEntry const& entry) { return entry.caseSensitive == true; }); + } + } + // A date tree is include-only: no bucket starts ticked, and neither does "(Blanks)" unless the stored + // filter ticks it. + if (dates(next)) { + next.ticks.ticked = false; + next.ticks.blanks = next.ticks.blanks.value_or(false); + } + for (ConditionDraft& draft : next.conditions) { + if (draft.unit.empty() && !focus.unitChoices.empty()) { + draft.unit = focus.unitChoices.front(); + } + } + _state.set(std::move(next)); + if (_host.listing) { + _host.listing(columnsOf(_state.peek().target)); + } + if (valuesListed(_state.peek())) { + load(false); + } +} + +void FilterMenu::close() { + if (!_state.peek().open) { + return; + } + _searchTimer.cancel(); + _sendTimer.cancel(); + ++_serial; + _state.mutate([](FilterMenuState& state) { + state.open = false; + state.list.clear(); + }); + if (_host.listing) { + _host.listing({}); + } +} + +void FilterMenu::search(std::string text) { + touch(); + _state.mutate([&](FilterMenuState& state) { state.search = std::move(text); }); + _searchTimer.cancel(); + later(_searchTimer, [this] { load(false); }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one tick, by the kind of row it lands on. +void FilterMenu::tick(std::size_t index, bool checked) { + touch(); + _sendTimer.cancel(); + _state.mutate([&](FilterMenuState& state) { + if (index >= state.list.size()) { + return; + } + clearConditions(state); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < state.list.size() by the check above + FilterListEntry const& entry = state.list[index]; + if (dates(state)) { + std::erase(state.dates, entry.value.operand); + if (!checked) { + // A range that holds the bucket and more, as Apply merged it, keeps the rest: its days before + // and after the bucket. + auto const bucket = detail::filtermenu::rangeOf(entry.value.operand); + bool const dateTime = state.target.shown.info.kind == table::ColumnKind::DateTime; + std::vector kept; + for (std::string const& held : state.dates) { + auto const range = detail::filtermenu::rangeOf(held); + if (!bucket || !range || range->first > bucket->first || bucket->second > range->second) { + kept.push_back(held); + continue; + } + if (range->first < bucket->first) { + kept.push_back(detail::filtermenu::rangeText(range->first, bucket->first - 1, dateTime)); + } + if (bucket->second < range->second) { + kept.push_back(detail::filtermenu::rangeText(bucket->second + 1, range->second, dateTime)); + } + } + state.dates = std::move(kept); + } + if (checked) { + // A ticked bucket covers those under it: their own ticks go. + auto const range = detail::filtermenu::rangeOf(entry.value.operand); + std::erase_if(state.dates, [&](std::string const& held) { + auto const inner = detail::filtermenu::rangeOf(held); + return range && inner && range->first <= inner->first && inner->second <= range->second; + }); + state.dates.push_back(entry.value.operand); + } + return; + } + state.ticks.ops.push_back(TickOp{.search = {}, .operand = entry.value.operand, .ticked = checked}); + leaveTogether(state); + }); +} + +void FilterMenu::tickAll(bool checked) { + touch(); + _sendTimer.cancel(); + _state.mutate([&](FilterMenuState& state) { + clearConditions(state); + state.ticks.ops.push_back(TickOp{.search = state.search, .operand = std::nullopt, .ticked = checked}); + if (state.search.empty() && state.ticks.blanks) { + state.ticks.blanks = checked; + } + leaveTogether(state); + }); +} + +void FilterMenu::tickBlanks(bool checked) { + touch(); + _sendTimer.cancel(); + _state.mutate([&](FilterMenuState& state) { + clearConditions(state); + state.ticks.blanks = checked; + }); +} + +void FilterMenu::more() { + touch(); + load(true); +} + +void FilterMenu::openBucket(std::size_t index) { + touch(); + FilterMenuState const& now = _state.peek(); + if (index >= now.list.size()) { + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < now.list.size() by the check above + FilterListEntry const entry = now.list[index]; + if (entry.bucket != table::DateBucket::Year && entry.bucket != table::DateBucket::Month) { + return; + } + if (entry.opened) { + _state.mutate([&](FilterMenuState& state) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): index < the list's size by the check above; the list is unchanged since + state.list[index].opened = false; + std::size_t end = index + 1; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): end < state.list.size() in the same condition + while (end < state.list.size() && state.list[end].depth > entry.depth) { + ++end; + } + state.list.erase(state.list.begin() + static_cast(index) + 1, + state.list.begin() + static_cast(end)); + }); + return; + } + table::DateBucket const bucket = + entry.bucket == table::DateBucket::Year ? table::DateBucket::Month : table::DateBucket::Day; + table::DistinctRequest request = requestOf(now); + request.bucket = bucket; + request.search = entry.value.text + "-"; + request.offset = 0; + std::uint64_t const serial = _serial; + std::string const operand = entry.value.operand; + ask(request, [this, serial, operand, bucket, + depth = entry.depth + 1](std::expected const& reply) { + if (serial != _serial || !reply) { + return; + } + _state.mutate([&](FilterMenuState& state) { + auto const found = std::ranges::find_if(state.list, [&](FilterListEntry const& held) { + return held.value.operand == operand && held.depth + 1 == depth; + }); + if (found == state.list.end() || found->opened) { + return; + } + found->opened = true; + std::vector children; + for (table::DistinctValue const& value : reply->values) { + children.push_back(FilterListEntry{.value = value, .bucket = bucket, .depth = depth, .opened = false}); + } + state.list.insert(found + 1, children.begin(), children.end()); + }); + }); +} + +void FilterMenu::setMatch(GroupMatch match) { + touch(); + _state.mutate([&](FilterMenuState& state) { state.match = match; }); + if (hasConditions(_state.peek())) { + scheduleSend(); + } +} + +void FilterMenu::setCount(std::string text) { + touch(); + _state.mutate([&](FilterMenuState& state) { state.count = std::move(text); }); + if (hasConditions(_state.peek())) { + scheduleSend(); + } +} + +void FilterMenu::apply() { + touch(); + FilterMenuState const& now = _state.peek(); + if (hasConditions(now)) { + _sendTimer.cancel(); + if (sendConditions()) { + close(); + } + return; + } + if (now.target.column.empty() && now.target.formed) { + return; + } + if (dates(now)) { + applyDates(); + } else if (now.target.column.empty()) { + applyGroupValues(); + } else { + applyValues(); + } +} + +void FilterMenu::clearFilter() { + touch(); + _sendTimer.cancel(); + FilterMenuState const& now = _state.peek(); + table::FilterSpec spec = _host.filters ? _host.filters() : table::FilterSpec{}; + if (now.target.column.empty()) { + if (auto const index = groupFilterIndex(spec, now.target)) { + spec.groups.erase(spec.groups.begin() + static_cast(*index)); + } + } else { + spec.columns.erase(now.target.column); + } + if (_host.apply) { + static_cast(_host.apply(std::move(spec))); + } + _state.mutate([](FilterMenuState& state) { + clearConditions(state); + state.ticks = ValueTicks{.ticked = !dates(state) && !state.target.column.empty(), + .ops = {}, + .blanks = state.blanks > 0 ? std::optional{!dates(state)} : std::nullopt}; + state.dates.clear(); + state.refusal.clear(); + leaveTogether(state); + }); +} + +std::vector FilterMenu::rows() const { + FilterMenuState const& state = _state.get(); + std::vector out; + if (!state.open) { + return out; + } + std::vector values; + values.reserve(state.list.size()); + for (FilterListEntry const& entry : state.list) { + values.push_back(entry.value); + } + std::vector const texts = distinctTexts(values, state.target.shown, _host.format, state.target.units); + bool const tree = dates(state); + std::string dimension; + for (std::size_t at = 0; at < state.list.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < state.list.size() by the loop + FilterListEntry const& entry = state.list[at]; + if (!entry.value.dimension.empty() && entry.value.dimension != dimension) { + dimension = entry.value.dimension; + out.push_back(FilterListRow{.kind = FilterListRow::Kind::Heading, + .key = "heading:" + dimension, + .id = dimension, + .label = dimension}); + } + FilterListRow row{ + .kind = FilterListRow::Kind::Value, + .key = "value:" + std::to_string(at) + ":" + entry.value.operand, + .id = std::to_string(at), + .label = texts.at(at) + " (" + groupedCount(entry.value.count, _host.format.numeric.groupSeparator) + ")", + .checked = false, + .enabled = true, + .opens = tree && entry.bucket != table::DateBucket::Day, + .index = at, + .depth = entry.depth}; + if (tree) { + // A bucket under a ticked bucket of the tree is ticked with it and cannot be toggled alone; one a + // range covers that no listed bucket is (a stored or merged range) is ticked and can be unticked. + auto const [covered, own] = detail::filtermenu::coverOf(state.dates, entry.value.operand); + row.checked = covered; + row.enabled = !covered || own || !underTicked(state, at); + } else { + row.checked = tickedNow(state, entry.value); + } + out.push_back(std::move(row)); + } + return out; +} + +bool FilterMenu::allTicked() const { + FilterMenuState const& state = _state.get(); + return !state.list.empty() && std::ranges::all_of(state.list, [&](FilterListEntry const& entry) { + return tickedNow(state, entry.value); + }); +} + +bool FilterMenu::canApply() const { + FilterMenuState const& state = _state.get(); + if (hasConditions(state) || dates(state)) { + return true; + } + if (state.target.formed) { + return false; + } + if (state.ticks.blanks == true || + std::ranges::any_of(state.list, [&](FilterListEntry const& entry) { return tickedNow(state, entry.value); })) { + return true; + } + // No listed value is ticked; one the list does not show may be: every value is, after the last operation + // that set them all, unless the list shows them all; and a "(Select all)" under a search since may tick + // values past the page. + auto const last = std::ranges::find_if(state.ticks.ops.rbegin(), state.ticks.ops.rend(), + [](TickOp const& op) { return !op.operand && op.search.empty(); }); + bool const base = last == state.ticks.ops.rend() ? state.ticks.ticked : last->ticked; + bool const unlisted = !state.search.empty() || state.total < 0 || std::cmp_less(state.list.size(), state.total); + return (base && unlisted) || + std::any_of(state.ticks.ops.rbegin(), last, [](TickOp const& op) { return !op.operand && op.ticked; }); +} + +std::string FilterMenu::note() const { + FilterMenuState const& state = _state.get(); + std::vector lines; + if (state.partial) { + lines.push_back(tableText::mayGrow()); + } + if (state.invalid > 0) { + lines.push_back( + tableText::unreadable(static_cast(state.invalid), _host.format.numeric.groupSeparator)); + } + if (!state.refusal.empty()) { + lines.push_back(state.refusal); + } + std::string out; + for (std::string const& line : lines) { + out += (out.empty() ? "" : "\n") + line; + } + return out; +} + +bool FilterMenu::valuesListed(FilterMenuState const& state) { + return !state.target.formed && state.target.listed && state.target.shown.info.kind != table::ColumnKind::Custom; +} + +bool FilterMenu::dates(FilterMenuState const& state) { + table::ColumnKind const kind = state.target.shown.info.kind; + return !state.target.column.empty() && (kind == table::ColumnKind::Date || kind == table::ColumnKind::DateTime); +} + +void FilterMenu::clearConditions(FilterMenuState& state) { + for (ConditionDraft& draft : state.conditions) { + std::string const unit = draft.unit; + draft = ConditionDraft{}; + draft.unit = unit; + } + state.matchCase = false; + state.combine = table::Combine::Any; +} + +void FilterMenu::leaveTogether(FilterMenuState& state) { + if (state.match == GroupMatch::Together && std::ranges::count_if(state.list, [&](FilterListEntry const& listed) { + return tickedNow(state, listed.value); + }) < 2) { + state.match = GroupMatch::AnyColumn; + } +} + +bool FilterMenu::underTicked(FilterMenuState const& state, std::size_t index) { + auto const inner = detail::filtermenu::rangeOf(state.list.at(index).value.operand); + for (std::size_t at = 0; at < state.list.size(); ++at) { + FilterListEntry const& above = state.list.at(at); + auto const outer = detail::filtermenu::rangeOf(above.value.operand); + if (at == index || above.depth >= state.list.at(index).depth || !outer || !inner || + outer->first > inner->first || inner->second > outer->second) { + continue; + } + if (std::ranges::contains(state.dates, above.value.operand)) { + return true; + } + } + return false; +} + +bool FilterMenu::tickedNow(FilterMenuState const& state, table::DistinctValue const& value) { + bool ticked = state.ticks.ticked; + for (TickOp const& op : state.ticks.ops) { + if (op.operand) { + if (*op.operand == value.operand) { + ticked = op.ticked; + } + } else if (op.search.empty() || + detail::filtermenu::folded(value.text).contains(detail::filtermenu::folded(op.search))) { + ticked = op.ticked; + } + } + return ticked; +} + +void FilterMenu::readGroup(FilterMenuState& next, table::GroupFilter const& group) { + bool const values = + !next.target.formed && group.exclude.empty() && + (group.mode == table::GroupMode::Together + ? std::ranges::all_of(group.include, + [](table::FilterEntry const& entry) { + return entry.eq.has_value() && ::morph::ui::detail::operatorCount(entry) == 1; + }) + : ::morph::ui::detail::valuesShape(group.include, next.target.shown.info.kind) && + std::ranges::any_of(group.include, + [](table::FilterEntry const& entry) { return entry.oneOf.has_value(); })); + if (values) { + for (table::FilterEntry const& entry : group.include) { + if (entry.oneOf) { + for (std::string const& member : *entry.oneOf) { + next.ticks.ops.push_back(TickOp{.search = {}, .operand = member, .ticked = true}); + } + } + if (entry.eq) { + next.ticks.ops.push_back(TickOp{.search = {}, .operand = entry.eq, .ticked = true}); + } + if (entry.isEmpty == true) { + next.ticks.blanks = true; + } + } + } else if (auto drafts = draftsOf(group.include); drafts && group.exclude.empty()) { + next.conditions = std::move(*drafts); + next.combine = group.combine; + } + if (group.mode == table::GroupMode::Together) { + next.match = GroupMatch::Together; + return; + } + switch (group.match.kind) { + case table::ColumnCount::Kind::Any: + next.match = GroupMatch::AnyColumn; + break; + case table::ColumnCount::Kind::All: + next.match = GroupMatch::EveryColumn; + break; + case table::ColumnCount::Kind::AtLeast: + next.match = GroupMatch::AtLeast; + next.count = std::to_string(group.match.n); + break; + case table::ColumnCount::Kind::Exactly: + next.match = GroupMatch::Exactly; + next.count = std::to_string(group.match.n); + break; + default: + break; + } +} + +void FilterMenu::touch() const { + if (_host.touch) { + _host.touch(); + } +} + +void FilterMenu::later(reactive::TimerHandle& timer, std::function fn) { + if (_host.scheduler == nullptr || _host.debounce.count() <= 0) { + fn(); + return; + } + timer = _host.scheduler->after(_host.debounce, _scope.token().guard(std::move(fn))); +} + +void FilterMenu::scheduleSend() { + _sendTimer.cancel(); + later(_sendTimer, [this] { static_cast(sendConditions()); }); +} + +table::DistinctRequest FilterMenu::requestOf(FilterMenuState const& state) const { + table::DistinctRequest request; + if (state.target.column.empty()) { + request.group = state.target.group; + } else { + request.column = state.target.column; + } + request.search = state.search; + request.bucket = dates(state) ? table::DateBucket::Year : table::DateBucket::Value; + request.limit = _host.pageSize; + return request; +} + +void FilterMenu::ask(table::DistinctRequest request, std::function done) { + TableRows* const rows = _host.rows ? _host.rows() : nullptr; + if (rows == nullptr) { + done(Reply{std::unexpected(table::TableError{ + .code = table::TableErrorCode::Unavailable, .column = {}, .message = "the table has no rows"})}); + return; + } + rows->distinctValues(std::move(request)).then(_scope, std::move(done)); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): the request and its reply share one edit. +void FilterMenu::load(bool next) { + FilterMenuState const& now = _state.peek(); + if (!now.open || !valuesListed(now)) { + return; + } + table::DistinctRequest request = requestOf(now); + // Assigned, not cast: the count's type is the platform's difference type, which is `std::int64_t` on some + // targets and a different 64-bit type on others. + std::int64_t const listed = + std::ranges::count_if(now.list, [](FilterListEntry const& entry) { return entry.depth == 0; }); + request.offset = next ? listed : 0; + std::uint64_t const serial = ++_serial; + bool const searched = !request.search.empty(); + ask(request, [this, serial, next, searched](Reply const& reply) { + if (serial != _serial) { + return; + } + _state.mutate([&](FilterMenuState& state) { + state.listedOnce = true; + if (!reply) { + // Rows that list no values: the conditions alone show. + if (reply.error().code == table::TableErrorCode::Unavailable) { + state.target.listed = false; + } + state.list.clear(); + return; + } + if (!next) { + state.list.clear(); + } + for (table::DistinctValue const& value : reply->values) { + state.list.push_back( + FilterListEntry{.value = value, + .bucket = dates(state) ? table::DateBucket::Year : table::DateBucket::Value, + .depth = 0, + .opened = false}); + } + state.distinct = reply->distinct; + if (!searched) { + state.total = reply->distinct; + } + state.blanks = reply->blanks; + state.invalid = reply->invalid; + state.partial = reply->partial; + // "(Blanks)" is a box only while the column has empty cells; with none it is on no side. + if (reply->blanks == 0 && !searched && !dates(state)) { + state.ticks.blanks.reset(); + } else if (reply->blanks > 0 && !state.ticks.blanks) { + state.ticks.blanks = !dates(state) && state.ticks.ticked; + } + }); + }); +} // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the function object owns the callable it heap-allocates for the capture. + +void FilterMenu::pageAll( + std::string search, + std::function, std::string>, std::int64_t distinct)> done) { + struct Paging { + table::DistinctRequest request; + std::vector values; + std::function, std::string>, std::int64_t)> done; + }; + auto const paging = std::make_shared(); + paging->request = requestOf(_state.peek()); + paging->request.search = std::move(search); + paging->request.limit = _host.maxLimit; + paging->request.offset = 0; + paging->done = std::move(done); + auto const step = std::make_shared>(); + std::weak_ptr> const weakStep = step; + *step = [this, paging, weakStep] { + ask(paging->request, [paging, keep = weakStep.lock()](Reply const& reply) { + if (!reply) { + paging->done(std::unexpected(reply.error().message), 0); + return; + } + paging->values.insert(paging->values.end(), reply->values.begin(), reply->values.end()); + paging->request.offset += static_cast(reply->values.size()); + if (reply->values.empty() || paging->request.offset >= reply->distinct) { + paging->done(std::move(paging->values), reply->distinct); + return; + } + if (keep) { + (*keep)(); + } + }); + }; // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the step is kept alive by its continuation. + (*step)(); +} + +void FilterMenu::resolve( + std::function, std::string>)> const& done) { + FilterMenuState const& now = _state.peek(); + auto const searches = std::make_shared>(); + for (TickOp const& op : now.ticks.ops) { + if (!op.operand && !op.search.empty() && !std::ranges::contains(*searches, op.search)) { + searches->push_back(op.search); + } + } + auto reached = std::make_shared, std::less<>>>(); + auto const finish = [reached, ticks = now.ticks, done](std::int64_t distinct) { + ResolvedTicks resolved = resolveTicks(ticks, [&](std::string const& search) { return reached->at(search); }); + done(std::pair{std::move(resolved), distinct}); + }; + auto const counted = [this, total = now.total, finish, done] { + if (total >= 0) { + finish(total); + return; + } + table::DistinctRequest request = requestOf(_state.peek()); + request.search.clear(); + request.offset = 0; + request.limit = 1; + ask(request, [finish, done](Reply const& reply) { + if (!reply) { + done(std::unexpected(reply.error().message)); + return; + } + finish(reply->distinct); + }); + }; // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the reply's continuations are owned by the host. + auto const step = std::make_shared>(); + std::weak_ptr> const weakStep = step; + *step = [this, searches, reached, counted, done, weakStep](std::size_t index) { + if (index >= searches->size()) { + counted(); + return; + } + pageAll(searches->at(index), + [reached, searches, index, done, self = weakStep.lock()]( + std::expected, std::string> values, std::int64_t) { + if (!values) { + done(std::unexpected(values.error())); + return; + } + std::vector& operands = (*reached)[searches->at(index)]; + for (table::DistinctValue const& value : *values) { + operands.push_back(value.operand); + } + if (self) { + (*self)(index + 1); + } + }); + }; + (*step)(0); +} + +void FilterMenu::commit(table::FilterSpec spec) { + bool const applied = _host.apply ? _host.apply(std::move(spec)) : false; + if (applied) { + refuse({}); + close(); + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one resolve-then-write sequence. +void FilterMenu::applyValues() { + std::uint64_t const serial = _serial; + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the reply's cases are one decision. + resolve([this, serial](std::expected, std::string> resolved) { + if (serial != _serial) { + return; + } + if (!resolved) { + refuse(std::move(resolved.error())); + return; + } + auto const& [ticks, distinct] = *resolved; + ValueFilterPlan const plan = planValueFilter(distinct, ticks, _host.maxSetValues); + std::string const column = _state.peek().target.column; + using PlanSide = ValueFilterPlan::Side; + if (plan.side == PlanSide::Disabled) { + refuse(tableText::tooManyValues()); + return; + } + if (plan.side == PlanSide::Nothing) { + return; + } + if (plan.side == PlanSide::All) { + table::FilterSpec spec = _host.filters ? _host.filters() : table::FilterSpec{}; + spec.columns.erase(column); + commit(std::move(spec)); + return; + } + bool const include = plan.side == PlanSide::Include; + auto const write = [this, column, side = plan.side, blanks = ticks.blanks](std::vector members) { + table::FilterSpec spec = _host.filters ? _host.filters() : table::FilterSpec{}; + if (auto filter = valueFilter(side, std::move(members), blanks)) { + spec.columns.insert_or_assign(column, std::move(*filter)); + } else { + spec.columns.erase(column); + } + commit(std::move(spec)); + }; + if (!plan.needsComplement) { + std::vector members; + for (auto const& [operand, ticked] : ticks.covered) { + if (ticked == include) { + members.push_back(operand); + } + } + write(std::move(members)); + return; + } + // The side names values no operation reached: every value is paged to name them. + pageAll({}, [this, serial, ticks, include, write]( + std::expected, std::string> const& values, std::int64_t) { + if (serial != _serial) { + return; + } + if (!values) { + refuse(values.error()); + return; + } + std::vector members; + for (table::DistinctValue const& value : *values) { + auto const held = ticks.covered.find(value.operand); + bool const ticked = held != ticks.covered.end() ? held->second : ticks.ticked; + if (ticked == include) { + members.push_back(value.operand); + } + } + write(std::move(members)); + }); + }); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one resolve-then-write sequence. +void FilterMenu::applyGroupValues() { + std::uint64_t const serial = _serial; + // NOLINTNEXTLINE(readability-function-cognitive-complexity): the reply's cases are one decision. + resolve([this, serial](std::expected, std::string> resolved) { + if (serial != _serial) { + return; + } + if (!resolved) { + refuse(std::move(resolved.error())); + return; + } + ResolvedTicks const ticks = resolved->first; + auto const write = [this, ticks](std::vector ticked) { + FilterMenuState const& now = _state.peek(); + std::int64_t count = 0; + static_cast(detail::filtermenu::readNumber(now.count, 0, now.count.size(), count)); + auto filter = groupValueFilter(now.target.group, now.target.columns.size(), std::move(ticked), + ticks.blanks, now.match, count); + if (!filter) { + refuse(std::move(filter.error())); + return; + } + table::FilterSpec spec = _host.filters ? _host.filters() : table::FilterSpec{}; + if (auto const index = groupFilterIndex(spec, now.target)) { + spec.groups.at(*index) = std::move(*filter); + } else { + spec.groups.push_back(std::move(*filter)); + } + commit(std::move(spec)); + }; + if (!ticks.ticked) { + std::vector ticked; + for (auto const& [operand, covered] : ticks.covered) { + if (covered) { + ticked.push_back(operand); + } + } + // In the order the list shows them. + std::vector ordered; + for (FilterListEntry const& entry : _state.peek().list) { + if (std::ranges::contains(ticked, entry.value.operand)) { + ordered.push_back(entry.value.operand); + } + } + for (std::string const& operand : ticked) { + if (!std::ranges::contains(ordered, operand)) { + ordered.push_back(operand); + } + } + write(std::move(ordered)); + return; + } + pageAll({}, [this, serial, ticks, write]( + std::expected, std::string> const& values, std::int64_t) { + if (serial != _serial) { + return; + } + if (!values) { + refuse(values.error()); + return; + } + std::vector ticked; + for (table::DistinctValue const& value : *values) { + auto const held = ticks.covered.find(value.operand); + if (held != ticks.covered.end() ? held->second : ticks.ticked) { + ticked.push_back(value.operand); + } + } + if (ticked.size() > _host.maxSetValues) { + refuse(tableText::tooManyValues()); + return; + } + write(std::move(ticked)); + }); + }); +} + +void FilterMenu::applyDates() { + FilterMenuState const& now = _state.peek(); + bool const dateTime = now.target.shown.info.kind == table::ColumnKind::DateTime; + std::vector const ranges = mergeDateRanges(now.dates, dateTime); + bool const blanks = now.ticks.blanks == true; + table::FilterSpec spec = _host.filters ? _host.filters() : table::FilterSpec{}; + if (ranges.empty() && !blanks) { + spec.columns.erase(now.target.column); + commit(std::move(spec)); + return; + } + if (ranges.size() + (blanks ? 1U : 0U) > _host.maxEntries) { + refuse(tableText::tooManyDates()); + return; + } + if (auto filter = valueFilter(ValueFilterPlan::Side::Include, ranges, now.ticks.blanks, ValueForm::Ranges)) { + spec.columns.insert_or_assign(now.target.column, std::move(*filter)); + } + commit(std::move(spec)); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): reads both condition lines into one filter. +bool FilterMenu::sendConditions() { + FilterMenuState const& now = _state.peek(); + if (!now.open || !hasConditions(now)) { + return false; + } + FilterTarget const& target = now.target; + table::ColumnKind const kind = target.shown.info.kind; + LocaleFacts const locale{.tag = _host.format.locale, + .numeric = _host.format.numeric, + .currency = _host.format.currency, + .datePattern = _host.format.datePattern, + .dateTimePattern = _host.format.dateTimePattern}; + std::vector entries; + std::array invalid{false, false}; + bool incomplete = false; + for (std::size_t at = 0; at < now.conditions.size(); ++at) { + ConditionDraft const& draft = now.conditions.at(at); + if (!draft.op) { + continue; + } + std::string operand; + std::string second; + if (detail::filtermenu::takesOperand(*draft.op)) { + if (draft.operand.empty() || (*draft.op == ConditionOp::Between && draft.second.empty())) { + incomplete = true; + continue; + } + auto const read = canonicalOperand(draft.operand, kind, locale, target.unitList, draft.unit); + std::optional const upper = + *draft.op == ConditionOp::Between + ? canonicalOperand(draft.second, kind, locale, target.unitList, draft.unit) + : std::optional{std::string{}}; + if (!read || !upper) { + invalid.at(at) = true; + continue; + } + operand = *read; + second = *upper; + } + entries.push_back(conditionEntry(*draft.op, std::move(operand), std::move(second), + now.matchCase && kind == table::ColumnKind::Text)); + } + _state.mutate([&](FilterMenuState& state) { + for (std::size_t at = 0; at < state.conditions.size(); ++at) { + state.conditions.at(at).invalid = invalid.at(at); + } + }); + if (incomplete || std::get<0>(invalid) || std::get<1>(invalid)) { + return false; + } + table::FilterSpec spec = _host.filters ? _host.filters() : table::FilterSpec{}; + if (target.column.empty()) { + std::int64_t count = 1; + static_cast(detail::filtermenu::readNumber(now.count, 0, now.count.size(), count)); + auto const index = groupFilterIndex(spec, target); + if (entries.empty()) { + if (index) { + spec.groups.erase(spec.groups.begin() + static_cast(*index)); + } + } else { + table::GroupFilter filter{.group = target.formed ? std::string{} : target.group, + .columns = target.formed ? target.columns : std::vector{}, + .mode = table::GroupMode::Columns, + .match = columnCountOf(now.match, count), + .combine = now.combine, + .include = std::move(entries), + .exclude = {}}; + if (index) { + spec.groups.at(*index) = std::move(filter); + } else { + spec.groups.push_back(std::move(filter)); + } + } + } else if (entries.empty()) { + spec.columns.erase(target.column); + } else { + spec.columns.insert_or_assign( + target.column, table::ColumnFilter{.combine = now.combine, .include = std::move(entries), .exclude = {}}); + } + if (_host.filters && spec == _host.filters()) { + return true; + } + return _host.apply ? _host.apply(std::move(spec)) : false; +} + +} // namespace morph::ui + +namespace morph::ui::detail::filtermenu { + +std::optional instantOf(std::string_view text) { + auto const day = dayOf(text); + if (!day) { + return std::nullopt; + } + std::chrono::sys_days const days{std::chrono::days{*day}}; + std::int64_t seconds = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): text.size() >= 19 by the condition + if (text.size() >= 19 && text[10] == 'T') { + int hour = 0; + int minute = 0; + int second = 0; + static_cast(readNumber(text, 11, 2, hour)); + static_cast(readNumber(text, 14, 2, minute)); + static_cast(readNumber(text, 17, 2, second)); + seconds = (hour * 3600) + (minute * 60) + second; + } + return time::Timestamp{ + time::DateTime{std::chrono::sys_time{days} + std::chrono::seconds{seconds}}}; +} + +std::string operandOfInstant(time::DateTime const& instant, bool dateTime) { + std::int64_t const seconds = + std::chrono::duration_cast(instant.value.time_since_epoch()).count(); + return dateTime ? table::detail::isoDateTime(seconds) + : table::detail::isoDate(table::detail::dayOfSeconds(seconds)); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one line's controls, by condition kind. +Node conditionLine(FilterMenu& menu, std::size_t which, FilterTarget const& target) { + table::ColumnKind const kind = target.shown.info.kind; + std::string const position = std::to_string(which + 1); + std::vector options; + for (ConditionOp const op : conditionOps(kind)) { + std::string const label{conditionLabel(op, kind)}; + options.push_back(SelectOption{.key = Key{label}, .label = label}); + } + Select ops{.options = options, + .selected = [&menu, which, kind]() -> std::optional { + ConditionDraft const& draft = menu.state().conditions.at(which); + if (!draft.op) { + return std::nullopt; + } + return Key{std::string{conditionLabel(*draft.op, kind)}}; + }, + .onSelect = + [&menu, which, kind](Key const& key) { + std::string const* const label = std::get_if(&key); + for (ConditionOp const op : conditionOps(kind)) { + if (label != nullptr && conditionLabel(op, kind) == *label) { + menu.setOp(which, op); + } + } + }}; + ops.label = std::string{"Condition"}; + ops.common.testId = "table_filter_op_" + position; + auto const takes = [&menu, which] { + ConditionDraft const& draft = menu.state().conditions.at(which); + return draft.op && takesOperand(*draft.op); + }; + auto const between = [&menu, which] { return menu.state().conditions.at(which).op == ConditionOp::Between; }; + auto const errors = [&menu, which] { + return menu.state().conditions.at(which).invalid ? std::vector{"Not a value of this column"} + : std::vector{}; + }; + std::vector children{select(std::move(ops))}; + bool const dated = kind == table::ColumnKind::Date || kind == table::ColumnKind::DateTime; + for (bool const upper : {false, true}) { + std::string const testId = std::string{upper ? "table_filter_second_" : "table_filter_operand_"} + position; + auto const text = [&menu, which, upper] { + ConditionDraft const& draft = menu.state().conditions.at(which); + return upper ? draft.second : draft.operand; + }; + auto const set = [&menu, which, upper](std::string value) { + if (upper) { + menu.setSecond(which, std::move(value)); + } else { + menu.setOperand(which, std::move(value)); + } + }; + if (dated) { + bool const dateTime = kind == table::ColumnKind::DateTime; + DateTimeInput picker{ + .value = [text] { return instantOf(text()); }, + .onChange = + [set, dateTime](std::optional const& picked) { + set(picked && picked->hasValue() ? operandOfInstant(**picked, dateTime) : std::string{}); + }, + .mode = dateTime ? DateMode::DateTime : DateMode::Date}; + picker.common.testId = testId; + picker.common.visible = upper ? Prop{between} : Prop{takes}; + picker.field.errors = errors; + children.push_back(dateTimeInput(std::move(picker))); + } else { + TextInput input{.value = text, .onChange = set}; + input.common.testId = testId; + input.common.visible = upper ? Prop{between} : Prop{takes}; + input.field.errors = errors; + children.push_back(textInput(std::move(input))); + } + } + if (kind == table::ColumnKind::Measure && !target.unitChoices.empty()) { + std::vector units; + units.reserve(target.unitChoices.size()); + for (std::string const& unit : target.unitChoices) { + units.push_back(SelectOption{.key = Key{unit}, .label = unit}); + } + Select unit{.options = units, + .selected = [&menu, which]() -> std::optional { + std::string const& chosen = menu.state().conditions.at(which).unit; + return chosen.empty() ? std::nullopt : std::optional{Key{chosen}}; + }, + .onSelect = + [&menu, which](Key const& key) { + if (std::string const* const unitId = std::get_if(&key)) { + menu.setUnit(which, *unitId); + } + }}; + unit.label = std::string{"Unit"}; + unit.common.testId = "table_filter_unit_" + position; + children.push_back(select(std::move(unit))); + } + return ui::row(Row{.children = std::move(children), .gap = 1}); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one widget per part the spec lists. +Node menuContent(FilterMenu& menu, FilterTarget const& target) { + std::vector parts; + table::ColumnKind const kind = target.shown.info.kind; + bool const isGroup = target.column.empty(); + bool const tree = !isGroup && (kind == table::ColumnKind::Date || kind == table::ColumnKind::DateTime); + bool const listed = !target.formed && target.listed && kind != table::ColumnKind::Custom; + if (listed) { + auto const shows = [&menu] { return FilterMenu::valuesListed(menu.state()); }; + if (!tree) { + TextInput search{.value = [&menu] { return menu.state().search; }, + .onChange = [&menu](std::string text) { menu.search(std::move(text)); }, + .placeholder = std::string{"Search"}}; + search.label = std::string{"Search"}; + search.common.testId = "table_filter_search"; + search.common.visible = shows; + parts.push_back(textInput(std::move(search))); + Checkbox all{.label = std::string{"(Select all)"}, + .checked = [&menu] { return menu.allTicked(); }, + .onToggle = [&menu](bool checked) { menu.tickAll(checked); }}; + all.common.testId = "table_filter_all"; + all.common.visible = shows; + parts.push_back(checkbox(std::move(all))); + } + Checkbox blanks{.label = std::string{"(Blanks)"}, + .checked = [&menu] { return menu.state().ticks.blanks == true; }, + .onToggle = [&menu](bool checked) { menu.tickBlanks(checked); }}; + blanks.common.testId = "table_filter_blanks"; + blanks.common.visible = [&menu] { return FilterMenu::valuesListed(menu.state()) && menu.state().blanks > 0; }; + parts.push_back(checkbox(std::move(blanks))); + parts.push_back(forEach( + [&menu] { return menu.rows(); }, [](FilterListRow const& row) -> Key { return Key{row.key}; }, + [&menu](reactive::Signal const& row) -> Node { + FilterListRow const& first = row.peek(); + if (first.kind == FilterListRow::Kind::Heading) { + Text heading{.text = first.label, .role = TextRole::Muted}; + heading.common.testId = "table_filter_heading_" + first.id; + return ui::text(std::move(heading)); + } + std::size_t const index = first.index; + Checkbox box{.label = [&row] { return row.get().label; }, + .checked = [&row] { return row.get().checked; }, + .onToggle = [&menu, index](bool checked) { menu.tick(index, checked); }}; + box.common.testId = "table_filter_value_" + first.id; + box.common.enabled = [&row] { return row.get().enabled; }; + std::vector line; + if (first.depth > 0) { + Spacer indent; + indent.common.layout.width = Sizing::fixed(static_cast(2 * first.depth)); + line.push_back(spacer(std::move(indent))); + } + line.push_back(checkbox(std::move(box))); + if (first.opens) { + Button open{.label = std::string{"▸"}, .onClick = [&menu, index] { menu.openBucket(index); }}; + open.common.testId = "table_filter_open_" + first.id; + line.push_back(button(std::move(open))); + } + return ui::row(Row{.children = std::move(line), .gap = 1}); + }, + Axis::Vertical, 0)); + Button more{.label = std::string{"More values"}, .onClick = [&menu] { menu.more(); }}; + more.common.testId = "table_filter_more"; + more.common.visible = [&menu] { + FilterMenuState const& state = menu.state(); + auto const top = + std::ranges::count_if(state.list, [](FilterListEntry const& entry) { return entry.depth == 0; }); + return FilterMenu::valuesListed(state) && top < state.distinct; + }; + parts.push_back(button(std::move(more))); + } + Text note{.text = [&menu] { return menu.note(); }, .role = TextRole::Muted}; + note.common.testId = "table_filter_note"; + parts.push_back(ui::text(std::move(note))); + if (!conditionOps(kind).empty()) { + parts.push_back(conditionLine(menu, 0, target)); + Select combine{.options = std::vector{{.key = Key{std::string{"and"}}, .label = "and"}, + {.key = Key{std::string{"or"}}, .label = "or"}}, + .selected = + [&menu] { + return std::optional{ + Key{std::string{menu.state().combine == table::Combine::All ? "and" : "or"}}}; + }, + .onSelect = + [&menu](Key const& key) { + std::string const* const name = std::get_if(&key); + if (name != nullptr) { + menu.setCombine(*name == "and" ? table::Combine::All : table::Combine::Any); + } + }}; + combine.label = std::string{"Join"}; + combine.common.testId = "table_filter_combine"; + parts.push_back(select(std::move(combine))); + parts.push_back(conditionLine(menu, 1, target)); + if (kind == table::ColumnKind::Text) { + Checkbox matchCase{.label = std::string{"match case"}, + .checked = [&menu] { return menu.state().matchCase; }, + .onToggle = [&menu](bool enabled) { menu.setMatchCase(enabled); }}; + matchCase.common.testId = "table_filter_case"; + parts.push_back(checkbox(std::move(matchCase))); + } + } + if (isGroup) { + std::size_t const columns = target.columns.size(); + bool const formed = target.formed; + Select match{ + .options = + [&menu, columns, formed] { + std::vector out; + for (GroupMatch const choice : + {GroupMatch::AnyColumn, GroupMatch::EveryColumn, GroupMatch::AtLeast, GroupMatch::Exactly}) { + out.push_back(SelectOption{.key = Key{std::string{matchLabel(choice)}}, + .label = std::string{matchLabel(choice)}}); + } + // "all of them, each in a column" takes ticked values: 2 to k of them. + std::size_t ticked = 0; + for (FilterListRow const& row : menu.rows()) { + ticked += row.kind == FilterListRow::Kind::Value && row.checked ? 1U : 0U; + } + if (!formed && ticked >= 2 && ticked <= columns) { + std::string const label{matchLabel(GroupMatch::Together)}; + out.push_back(SelectOption{.key = Key{label}, .label = label}); + } + return out; + }, + .selected = [&menu] { return std::optional{Key{std::string{matchLabel(menu.state().match)}}}; }, + .onSelect = + [&menu](Key const& key) { + std::string const* const label = std::get_if(&key); + for (GroupMatch const choice : {GroupMatch::AnyColumn, GroupMatch::EveryColumn, + GroupMatch::AtLeast, GroupMatch::Exactly, GroupMatch::Together}) { + if (label != nullptr && matchLabel(choice) == *label) { + menu.setMatch(choice); + } + } + }}; + match.label = std::string{"Match"}; + match.common.testId = "table_filter_match"; + parts.push_back(select(std::move(match))); + TextInput count{.value = [&menu] { return menu.state().count; }, + .onChange = [&menu](std::string text) { menu.setCount(std::move(text)); }}; + count.label = std::string{"N"}; + count.common.testId = "table_filter_count"; + count.common.visible = [&menu] { + GroupMatch const line = menu.state().match; + return line == GroupMatch::AtLeast || line == GroupMatch::Exactly; + }; + parts.push_back(textInput(std::move(count))); + } + Button apply{ + .label = std::string{"Apply"}, .emphasis = ButtonEmphasis::Primary, .onClick = [&menu] { menu.apply(); }}; + apply.common.testId = "table_filter_apply"; + apply.common.enabled = [&menu] { return menu.canApply(); }; + Button clear{.label = std::string{"Clear filter"}, .onClick = [&menu] { menu.clearFilter(); }}; + clear.common.testId = "table_filter_clear"; + parts.push_back(ui::row(Row{.children = {button(std::move(apply)), button(std::move(clear))}, .gap = 1})); + return ui::column(Column{.children = std::move(parts), .gap = 1}); +} + +} // namespace morph::ui::detail::filtermenu + +namespace morph::ui { + +Node filterMenuDialog(FilterMenu& menu) { + Node const content = forEach( + [&menu] { + FilterMenuState const& state = menu.state(); + return state.open ? std::vector{state.opening} : std::vector{}; + }, + [](std::uint64_t const& opening) -> Key { return Key{static_cast(opening)}; }, + [&menu](reactive::Signal const& opening) { + static_cast(opening); + FilterTarget const target = menu.state().target; + return detail::filtermenu::menuContent(menu, target); + }, + Axis::Vertical, 0); + Dialog dialog{.open = [&menu] { return menu.state().open; }, + .title = [&menu] { return menu.state().target.label; }, + .child = content, + .onDismiss = [&menu] { menu.close(); }}; + dialog.common.testId = "table_filter"; + return ui::dialog(std::move(dialog)); +} + +} // namespace morph::ui diff --git a/src/ui/table_rows_1.cpp b/src/ui/table_rows_1.cpp new file mode 100644 index 000000000..f53f1dd10 --- /dev/null +++ b/src/ui/table_rows_1.cpp @@ -0,0 +1,1490 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +std::string selectionJsonOf(TableSelection const& selection) { + return table::detail::selectionJson( + selection.keys, selection.view ? &selection.view->filters : nullptr, + selection.view ? std::span{selection.view->retained} : std::span{}, + selection.view ? std::string_view{selection.view->revision} : std::string_view{}, selection.except); +} + +std::string selectAllRefusalText(SelectAllRefusal const& refusal, FormatContext const& locale) { + if (refusal.undecided > 0) { + return "Select all is available once " + + render::formatCanonicalNumber(std::to_string(refusal.undecided), locale.numeric) + + (refusal.undecided == 1 ? " row is decided" : " rows are decided"); + } + if (refusal.levels.empty()) { + return "Select all is available once the rows have loaded"; + } + std::string levels; + for (std::string const& level : refusal.levels) { + levels += (levels.empty() ? "" : " and ") + level; + } + return "Select all is available once " + levels + " data has loaded"; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one walk down the reply along the catalog's path. +ChangedRowsValue changedRowsOf(Value const& reply, ActionInfo const& action, std::string_view record) { + ChangedRowsValue out; + auto const keyOf = [](Value const* key) -> std::optional { + if (key == nullptr) { + return std::nullopt; + } + if (auto const* const number = key->asInt()) { + return table::RowId{*number}; + } + if (auto const* const text = key->asString()) { + return table::RowId{*text}; + } + return std::nullopt; + }; + for (ActionRecordInfo const& info : action.records) { + if (info.record != record) { + continue; + } + for (std::string const& path : info.paths) { + std::string_view parent; + if (path == "rows") { + parent = {}; + } else if (path.ends_with(".rows")) { + parent = std::string_view{path}.substr(0, path.size() - std::string_view{".rows"}.size()); + } else { + continue; + } + Value const* node = &reply; + while (node != nullptr && !parent.empty()) { + auto const dot = parent.find('.'); + node = node->field(parent.substr(0, dot)); + parent = dot == std::string_view::npos ? std::string_view{} : parent.substr(dot + 1); + } + if (node == nullptr) { + continue; + } + if (Value const* const rows = node->field("rows"); rows != nullptr && rows->asList() != nullptr) { + for (Value const& row : *rows->asList()) { + if (auto key = keyOf(row.field("key"))) { + out.rows.push_back( + table::ChangedRow{.key = std::move(*key), .from = keyOf(row.field("from"))}); + } + } + } + if (Value const* const failed = node->field("failed"); failed != nullptr && failed->asList() != nullptr) { + for (Value const& row : *failed->asList()) { + if (auto key = keyOf(row.field("key"))) { + Value const* const message = row.field("message"); + out.failed.push_back(table::FailedRow{ + .key = std::move(*key), + .message = message != nullptr && message->asString() != nullptr ? *message->asString() + : std::string{}}); + } + } + } + } + } + return out; +} + +void RowStates::busyKeys(std::uint64_t run, std::vector keys) { + std::vector& held = _keyRuns[run]; + for (table::RowId& key : keys) { + if (!std::ranges::contains(held, key)) { + held.push_back(std::move(key)); + } + } +} + +void RowStates::busyView(std::uint64_t run, std::vector except, std::int64_t count) { + _viewRuns.insert_or_assign(run, ViewRun{.except = std::move(except), .count = std::max(count, 0)}); +} + +void RowStates::settle(std::uint64_t run) { + _keyRuns.erase(run); + _viewRuns.erase(run); +} + +void RowStates::fail(std::span rows) { + for (table::FailedRow const& row : rows) { + auto const found = std::ranges::find(_failed, row.key, &table::FailedRow::key); + if (found != _failed.end()) { + found->message = row.message; + } else { + _failed.push_back(row); + } + } +} + +void RowStates::move(table::RowId const& from, table::RowId const& target) { + if (from == target) { + return; + } + for (auto& [run, keys] : _keyRuns) { + auto const old = std::ranges::find(keys, from); + if (old == keys.end()) { + continue; + } + if (std::ranges::contains(keys, target)) { + keys.erase(old); + } else { + *old = target; + } + } + // A view run holds a row unless its `except` names it: a busy old key makes the new key busy, and is then + // left out itself. + for (auto& [run, view] : _viewRuns) { + if (!std::ranges::contains(view.except, from)) { + std::erase(view.except, target); + view.except.push_back(from); + } + } + auto const old = std::ranges::find(_failed, from, &table::FailedRow::key); + if (old == _failed.end()) { + return; + } + if (std::ranges::contains(_failed, target, &table::FailedRow::key)) { + _failed.erase(old); + } else { + old->key = target; + } +} + +bool RowStates::isBusy(table::RowId const& key) const { + auto const holds = [&key](auto const& run) { return std::ranges::contains(run.second, key); }; + auto const leavesIn = [&key](auto const& run) { return !std::ranges::contains(run.second.except, key); }; + return std::ranges::any_of(_keyRuns, holds) || std::ranges::any_of(_viewRuns, leavesIn); +} + +std::optional RowStates::failure(table::RowId const& key) const { + auto const found = std::ranges::find(_failed, key, &table::FailedRow::key); + return found == _failed.end() ? std::nullopt : std::optional{found->message}; +} + +std::int64_t RowStates::busyCount() const { + std::unordered_set keys; + for (auto const& [run, held] : _keyRuns) { + for (table::RowId const& key : held) { + auto const leavesOut = [&key](auto const& view) { return std::ranges::contains(view.second.except, key); }; + if (std::ranges::all_of(_viewRuns, leavesOut)) { + keys.insert(key); + } + } + } + std::int64_t largest = 0; + for (auto const& [run, view] : _viewRuns) { + largest = std::max(largest, view.count); + } + return largest + static_cast(keys.size()); +} + +std::vector RowStates::failedKeys() const { + std::vector out; + out.reserve(_failed.size()); + for (table::FailedRow const& row : _failed) { + out.push_back(row.key); + } + return out; +} + +bool TableRows::leftView(table::RowId const& key) const { + static_cast(key); + return false; +} + +RetainResult TableRows::retain(std::span keys) { + static_cast(keys); + return RetainResult::Retained; +} + +bool TableRows::unmatched(table::RowId const& key) const { + static_cast(key); + return false; +} + +async::Completion, table::TableError>> TableRows::rowsOf( + std::int64_t first, std::int64_t count, std::span columns) { + static_cast(first); + static_cast(count); + static_cast(columns); + return fetchRows({}, {}); +} + +std::optional lockText(TableRowRef const& row, table::TableDescription const& description) { + if (description.rowLock.empty()) { + return std::nullopt; + } + Value const* const cell = row.row.field(description.rowLock); + std::string const* const text = cell == nullptr ? nullptr : cell->asString(); + return text == nullptr || text->empty() ? std::nullopt : std::optional{*text}; +} + +bool refusesEdit(TableRows const& rows, std::int64_t index, table::TableDescription const& description) { + std::optional const row = rows.row(index); + return row && (rows.states().isBusy(row->key) || lockText(*row, description).has_value()); +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +Value doubleValue(double value) { + if (std::isfinite(value)) { + // The longest fixed text of a finite double: 309 integer digits, a sign, a point and 767 fraction digits. + std::array fixed{}; + auto const written = + std::to_chars(fixed.data(), std::to_address(fixed.end()), value, std::chars_format::fixed); + if (written.ec == std::errc{}) { + if (auto const parsed = table::parseDecimal(std::string_view{fixed.data(), written.ptr})) { + return Value{Decimal{*parsed}}; + } + } + } + std::array shortest{}; + auto const written = std::to_chars(shortest.data(), std::to_address(shortest.end()), value); + return Value{std::string{shortest.data(), written.ptr}}; +} + +Value dateValue(std::int64_t days) { + // Days of 0000-01-01 and 9999-12-31 from the epoch: the range a four-digit year spells. + constexpr std::int64_t kFirst = -719'528; + constexpr std::int64_t kLast = 2'932'896; + if (days < kFirst || days > kLast) { + return Value{std::to_string(days)}; + } + std::chrono::year_month_day const date{std::chrono::sys_days{std::chrono::days{static_cast(days)}}}; + return Value{std::format("{:04}-{:02}-{:02}", static_cast(date.year()), static_cast(date.month()), + static_cast(date.day()))}; +} + +Value dateTimeValue(std::int64_t seconds) { + constexpr std::int64_t kMillis = 1000; + if (seconds > std::numeric_limits::max() / kMillis || + seconds < std::numeric_limits::min() / kMillis) { + return Value{std::to_string(seconds)}; + } + return Value{time::DateTime{ + std::chrono::sys_time{std::chrono::milliseconds{seconds * kMillis}}}}; +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +Value cellValue(table::Cell const& cell, table::ColumnInfo const& column, table::UnitRegistry const* units) { + using table::ColumnKind; + return std::visit( + [&](T const& value) -> Value { + if constexpr (std::is_same_v || std::is_same_v) { + return Value{}; + } else if constexpr (std::is_same_v) { + if (column.kind == ColumnKind::Date) { + return detail::dateValue(value); + } + if (column.kind == ColumnKind::DateTime) { + return detail::dateTimeValue(value); + } + return Value{value}; + } else if constexpr (std::is_same_v) { + return Value{Decimal{value}}; + } else if constexpr (std::is_same_v) { + return detail::doubleValue(value); + } else if constexpr (std::is_same_v || std::is_same_v) { + return Value{value}; + } else if constexpr (std::is_same_v) { + if (units != nullptr && units->contains(value.unit)) { + return Value{Quantity{.value = value.amount, .unit = units->info(value.unit).id}}; + } + return Value{Decimal{value.amount}}; + } else { + static_assert(std::is_same_v); + // A product that does not fit is shown as the amount's own text, as the engine keys it invalid. + if (auto const canonical = math::checkedMul(value.amount, value.toCanonical)) { + return Value{Decimal{*canonical}}; + } + return Value{table::displayText(cell)}; + } + }, + cell); +} + +std::string countsText(TableCountsView const& counts, std::int64_t selected, FormatContext const& format) { + if (!counts.view.known) { + return {}; + } + auto const grouped = [&format](std::int64_t number) { + return render::formatCanonicalNumber(std::to_string(number), format.numeric); + }; + bool const lowerBound = counts.view.kind == table::TotalKind::AtLeast; + std::string view = grouped(counts.view.rows) + (lowerBound ? " or more" : ""); + if (counts.undecided > 0) { + return grouped(counts.view.rows) + " so far, " + grouped(counts.undecided) + " loading"; + } + if (selected > 0) { + return grouped(selected) + " of " + view + " selected"; + } + if (lowerBound) { + return view; + } + return counts.view.rows == 1 ? std::string{"1 row"} : view + " rows"; +} + +EngineRows::EngineRows(std::shared_ptr source, RecordOf recordOf, table::EngineOptions options) + : _source{checked(std::move(source), options)}, + _recordOf{std::move(recordOf)}, + _owner{options.owner}, + _engine{std::make_unique(_source, std::move(options))}, + _memoSnapshot{_engine->viewSnapshot()} { + _source->subscribe(*this); + _engine->onViewChange([this](table::ViewChange const& change) { + sync(); + if (_onChange) { + _onChange(change); + } + }); +} + +EngineRows::~EngineRows() { + _engine->onViewChange({}); + _source->unsubscribe(*this); +} + +void EngineRows::setRestoring(bool restoring) { + if (std::exchange(_restoring, restoring) == restoring) { + return; + } + if (_onChange) { + table::ViewChange change; + change.ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}); + _onChange(change); + } +} + +TableTotal EngineRows::total() const { + if (_restoring) { + return TableTotal{.rows = static_cast(_engine->viewRowCount()), + .kind = table::TotalKind::Exact, + .known = false}; + } + return TableTotal{ + .rows = static_cast(_engine->viewRowCount()), .kind = table::TotalKind::Exact, .known = true}; +} + +std::optional EngineRows::row(std::int64_t index) const { + if (_restoring) { + return std::nullopt; + } + auto const* const entry = entryAt(index); + if (entry == nullptr) { + return std::nullopt; + } + return TableRowRef{.key = entry->record.key, .row = entry->record.row}; +} + +table::UnloadedLevels EngineRows::unloadedLevels(std::int64_t index) const { + auto const* const entry = entryAt(index); + if (entry == nullptr) { + return {}; + } + return table::UnloadedLevels{.levels = entry->levels, .failed = {}}; +} + +void EngineRows::visible(std::int64_t first, std::int64_t count, std::span columns) { + static_cast(first); + static_cast(count); + static_cast(columns); +} + +async::Completion, table::TableError>> EngineRows::keysOf(std::int64_t first, + std::int64_t count) { + using Result = std::expected, table::TableError>; + auto [completion, promise] = async::Completion::makeSettleable(_owner); + auto const rows = static_cast(_engine->viewRowCount()); + if (first < 0 || count < 0 || count > rows - first) { + promise.resolve(Result{std::unexpected(table::TableError{ + .code = table::TableErrorCode::InvalidSpec, + .column = {}, + .message = std::format("{} rows from view row {} are not in a view of {}", count, first, rows)})}); + return std::move(completion); + } + std::vector keys; + keys.reserve(static_cast(count)); + for (std::int64_t at = first; at < first + count; ++at) { + keys.push_back(_engine->rowIdAt(static_cast(at))); + } + promise.resolve(Result{std::move(keys)}); + return std::move(completion); +} + +async::Completion, table::TableError>> EngineRows::fetchRows( + std::vector keys, std::vector columns) { + using Result = std::expected, table::TableError>; + auto [completion, promise] = async::Completion::makeSettleable(_owner); + auto const infos = _engine->columns(); + std::vector> places; + places.reserve(columns.size()); + for (std::string const& columnId : columns) { + auto const found = std::ranges::find(infos, columnId, &table::ColumnInfo::id); + places.push_back(found == infos.end() ? std::nullopt + : std::optional{static_cast(found - infos.begin())}); + } + auto const& snapshot = *_engine->viewSnapshot(); + std::vector rows; + for (table::RowId& key : keys) { + std::optional const viewRow = _engine->viewRowOfKey(key); + std::optional const sourceRow = viewRow ? _engine->sourceRowOf(*viewRow) : std::nullopt; + if (!sourceRow) { + continue; + } + FetchedRow row{.key = std::move(key), .viewRow = static_cast(*viewRow), .cells = {}}; + row.cells.reserve(places.size()); + for (std::optional const place : places) { + row.cells.push_back(place ? snapshot.cell(*sourceRow, *place) : table::Cell{}); + } + rows.push_back(std::move(row)); + } + promise.resolve(Result{std::move(rows)}); + return std::move(completion); +} + +std::expected EngineRows::selectView() const { + table::MembershipDigest digest; + for (std::size_t at = 0; at < _engine->viewRowCount(); ++at) { + digest.add(_engine->rowIdAt(at)); + } + auto const retained = _engine->retained(); + return ViewSelection{ + .filters = _engine->filter(), .retained = {retained.begin(), retained.end()}, .revision = digest.text()}; +} + +SelectedCount EngineRows::selectedCount(TableSelection const& selection) const { + if (!selection.view) { + return SelectedCount{.rows = static_cast(selection.keys.size()), .kind = CountKind::Exact}; + } + auto rows = static_cast(_engine->viewRowCount()); + for (table::RowId const& key : selection.except) { + if (_engine->viewRowOfKey(key)) { + --rows; + } + } + return SelectedCount{.rows = rows, .kind = CountKind::Exact}; +} + +async::Completion, table::TableError>> EngineRows::rowsOf( + std::int64_t first, std::int64_t count, std::span columns) { + auto const rows = static_cast(_engine->viewRowCount()); + std::vector keys; + for (std::int64_t at = std::max(first, 0); at < std::min(rows, first + count); ++at) { + keys.push_back(_engine->rowIdAt(static_cast(at))); + } + return fetchRows(std::move(keys), std::vector(columns.begin(), columns.end())); +} + +void EngineRows::locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) { + std::optional const viewRow = _engine->viewRowOfKey(key); + RowLocation const found{viewRow ? std::optional{static_cast(*viewRow)} : std::nullopt}; + _owner->post([stop = std::move(stop), done = std::move(done), found] { + if (!stop.stop_requested()) { + done(found); + } + }); +} + +async::Completion> EngineRows::distinctValues( + table::DistinctRequest request) { + using Result = std::expected; + auto [completion, promise] = async::Completion::makeSettleable(_owner); + auto const settle = std::make_shared::Promise>(std::move(promise)); + _owner->post(_scope.token().guard( + [this, settle, request = std::move(request)] { settle->resolve(_engine->distinctValues(request)); })); + return std::move(completion); +} + +TableCountsView EngineRows::counts() const { + std::int64_t retained = 0; + for (table::RowId const& key : _engine->retained()) { + if (auto const viewRow = _engine->viewRowOfKey(key); viewRow && _engine->isUnmatched(*viewRow)) { + ++retained; + } + } + return TableCountsView{.view = total(), + .source = static_cast(_engine->sourceRowCount()), + .undecided = static_cast(_engine->undecidedRowCount()), + .pending = _engine->pending(), + .awaiting = {}, + .failed = {}, + .retained = retained, + .busy = _states.busyCount()}; +} + +RetainResult EngineRows::retain(std::span keys) { + auto const held = _engine->retained(); + std::vector next(held.begin(), held.end()); + std::unordered_set seen(held.begin(), held.end()); + for (table::RowId const& key : keys) { + if (seen.insert(key).second) { + next.push_back(key); + } + } + if (next.size() > table::QueryLimits{}.maxRetained) { + return RetainResult::OverBound; + } + if (next.size() != held.size()) { + std::ignore = _engine->retain(std::move(next)); + } + return RetainResult::Retained; +} + +void EngineRows::clearRetained() { + if (!_engine->retained().empty()) { + std::ignore = _engine->retain({}); + } +} + +bool EngineRows::unmatched(table::RowId const& key) const { + auto const viewRow = _engine->viewRowOfKey(key); + return viewRow && _engine->isUnmatched(*viewRow); +} + +void EngineRows::moveKey(table::RowId const& from, table::RowId const& target) { + _states.move(from, target); + auto const held = _engine->retained(); + if (!std::ranges::contains(held, from)) { + return; + } + std::vector next; + next.reserve(held.size()); + bool const toHeld = std::ranges::contains(held, target); + for (table::RowId const& key : held) { + if (key == from) { + if (!toHeld) { + next.push_back(target); + } + } else { + next.push_back(key); + } + } + std::ignore = _engine->retain(std::move(next)); +} + +std::shared_ptr EngineRows::checked(std::shared_ptr source, + table::EngineOptions const& options) { + if (source == nullptr || options.owner == nullptr) { + throw std::invalid_argument{"morph::ui::EngineRows: the source and the engine's owner must not be null"}; + } + return source; +} + +void EngineRows::rowsChanged(table::RowChange const& change) { + _log.push_back(Logged{ + .snapshot = _source->snapshot(), .whole = change.kind != table::ChangeKind::Updated, .rows = change.rows}); +} + +void EngineRows::sync() const { + auto const& current = _engine->viewSnapshot(); + if (current == _memoSnapshot) { + return; + } + auto const made = std::ranges::find(_log, current, &Logged::snapshot); + auto const end = made == _log.end() ? _log.end() : std::next(made); + for (auto at = _log.begin(); at != end; ++at) { + if (at->whole) { + _memo.clear(); + } else { + for (auto const row : at->rows) { + _memo.erase(row); + } + } + } + _log.erase(_log.begin(), end); + _memoSnapshot = current; +} + +EngineRows::Entry const* EngineRows::entryAt(std::int64_t index) const { + if (index < 0) { + return nullptr; + } + auto const sourceRow = _engine->sourceRowOf(static_cast(index)); + if (!sourceRow) { + return nullptr; + } + sync(); + auto const found = _memo.find(*sourceRow); + if (found != _memo.end()) { + return &found->second; + } + auto const& snapshot = *_engine->viewSnapshot(); + Entry entry{.record = _recordOf(snapshot, *sourceRow), .levels = {}}; + ++_built; + auto const columns = _engine->columns(); + for (std::size_t column = 0; column < columns.size(); ++column) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): column < columns.size() by the loop + if (!columns[column].level.empty() && + std::holds_alternative(snapshot.cell(*sourceRow, column))) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): column < columns.size() by the loop + entry.levels.push_back(columns[column].level); + } + } + std::ranges::sort(entry.levels); + auto const [first, last] = std::ranges::unique(entry.levels); + entry.levels.erase(first, last); + return &_memo.insert_or_assign(*sourceRow, std::move(entry)).first->second; +} + +std::string ValueRowsCollator::sortKey(std::string_view text) const { + std::string key = folded(text); + key.push_back('\0'); + key.append(text); + return key; +} + +MORPH_PROCESS_UNIQUE std::string ValueRowsCollator::folded(std::string_view text) const { + struct Last { + std::string text; + std::string fold; + bool held = false; + }; + thread_local Last last; + if (!last.held || last.text != text) { + _folds.fetch_add(1, std::memory_order_relaxed); + last.fold = table::CodePointCollator{}.fold(text); + last.text.assign(text); + last.held = true; + } + return last.fold; +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +std::uint32_t exactPlacesOf(std::int64_t den) { + std::int64_t power = 1; + for (std::uint32_t places = 0; places < math::kMaxDecimalPlaces; ++places) { + if (power % den == 0) { + return places; + } + if (power > std::numeric_limits::max() / 10) { + break; + } + power *= 10; + } + return math::kMaxDecimalPlaces; +} + +std::optional measureOf(Value const& value) { + if (auto const* const quantity = value.asQuantity()) { + return MeasureParts{.amount = quantity->value, .unit = &quantity->unit}; + } + auto const* const record = value.asRecord(); + constexpr std::size_t kFields = 3; + if (record == nullptr || record->size() != kFields) { + return std::nullopt; + } + auto const* const num = value.field("num"); + auto const* const den = value.field("den"); + auto const* const unit = value.field("unit"); + if (num == nullptr || den == nullptr || unit == nullptr || num->asInt() == nullptr || den->asInt() == nullptr || + unit->asString() == nullptr || *den->asInt() == 0) { + return std::nullopt; + } + math::Rational const amount{math::Numerator{*num->asInt()}, math::Denominator{*den->asInt()}, + math::DecimalPlaces{0}}; + return MeasureParts{ + .amount = math::Rational{math::Numerator{amount.numerator}, math::Denominator{amount.denominator}, + math::DecimalPlaces{exactPlacesOf(amount.denominator)}}, + .unit = unit->asString()}; +} + +ValueVote voteOf(Value const& value) { + switch (value.kind()) { + case ValueKind::Bool: + return ValueVote::Bool; + case ValueKind::Int: + return ValueVote::Integer; + case ValueKind::Decimal: + return ValueVote::Decimal; + case ValueKind::String: + return ValueVote::Text; + case ValueKind::Timestamp: + return ValueVote::DateTime; + case ValueKind::Quantity: + return ValueVote::Measure; + case ValueKind::Record: + return measureOf(value) ? ValueVote::Measure : ValueVote::None; + case ValueKind::Null: + case ValueKind::List: + default: + return ValueVote::None; + } +} + +table::ColumnKind inferredKind(std::array const& counts, std::span votes) { + auto const count = [&counts](ValueVote vote) { return counts.at(static_cast(vote)); }; + std::size_t kinds = 0; + ValueVote only = ValueVote::None; + for (std::size_t at = 1; at < kValueVotes; ++at) { + if (counts.at(at) > 0) { + ++kinds; + only = static_cast(at); + } + } + if (kinds == 0) { + return table::ColumnKind::Text; + } + if (kinds == 1) { + return kindOfVote(only); + } + bool const decimals = count(ValueVote::Decimal) > 0; + if (kinds == 2 && decimals && count(ValueVote::Integer) > 0) { + return table::ColumnKind::Decimal; + } + auto const first = std::ranges::find_if(votes, [](ValueVote vote) { return vote != ValueVote::None; }); + auto const kind = first == votes.end() ? table::ColumnKind::Text : kindOfVote(*first); + return kind == table::ColumnKind::Integer && decimals ? table::ColumnKind::Decimal : kind; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one conversion per column kind, kept together. +ConvertedCell convertedCell(Value const& value, table::ColumnKind kind, table::UnitRegistry const* units) { + using table::ColumnKind; + if (value.isNull()) { + return {}; + } + auto const invalid = [kind] { + return kind == ColumnKind::Text + ? ConvertedCell{.cell = table::Cell{}, .invalid = true} + : ConvertedCell{.cell = table::Cell{table::Measure{.amount = {}, .unit = table::kUnknownUnit}}, + .invalid = true}; + }; + auto const floorDiv = [](std::int64_t count, std::int64_t per) { + std::int64_t const quotient = count / per; + return (count % per) < 0 ? quotient - 1 : quotient; + }; + constexpr std::int64_t kMillisPerSecond = 1000; + constexpr std::int64_t kMillisPerDay = 86'400'000; + switch (kind) { + case ColumnKind::Text: + case ColumnKind::Custom: + if (auto const* const text = value.asString()) { + return {.cell = table::Cell{*text}, .invalid = false}; + } + return invalid(); + case ColumnKind::Integer: + case ColumnKind::Key: + if (auto const* const integer = value.asInt()) { + return {.cell = table::Cell{*integer}, .invalid = false}; + } + return invalid(); + case ColumnKind::Decimal: + case ColumnKind::Quantity: + if (auto const* const integer = value.asInt()) { + return {.cell = table::Cell{math::Rational{*integer, math::DecimalPlaces{0}}}, .invalid = false}; + } + if (auto const* const decimal = value.asDecimal()) { + return {.cell = table::Cell{decimal->value}, .invalid = false}; + } + return invalid(); + case ColumnKind::Number: + if (auto const* const integer = value.asInt()) { + return {.cell = table::Cell{static_cast(*integer)}, .invalid = false}; + } + if (auto const* const decimal = value.asDecimal()) { + // One past the most places a decimal holds: the conversion is not rounded to any places. + return {.cell = table::Cell{decimal->value.toDouble(math::kMaxDecimalPlaces + 1)}, .invalid = false}; + } + return invalid(); + case ColumnKind::DateTime: + if (auto const* const instant = value.asTimestamp()) { + return {.cell = table::Cell{floorDiv(instant->value.time_since_epoch().count(), kMillisPerSecond)}, + .invalid = false}; + } + return invalid(); + case ColumnKind::Date: + if (auto const* const instant = value.asTimestamp()) { + return {.cell = table::Cell{floorDiv(instant->value.time_since_epoch().count(), kMillisPerDay)}, + .invalid = false}; + } + if (auto const* const text = value.asString()) { + if (auto const days = table::IsoDateParser{}.parseDate(*text, {})) { + return {.cell = table::Cell{*days}, .invalid = false}; + } + } + return invalid(); + case ColumnKind::Bool: + if (auto const* const flag = value.asBool()) { + return {.cell = table::Cell{*flag}, .invalid = false}; + } + return invalid(); + case ColumnKind::Measure: + if (auto const parts = measureOf(value)) { + if (auto const unit = units == nullptr ? std::nullopt : units->find(*parts->unit)) { + return {.cell = table::Cell{table::Measure{.amount = parts->amount, .unit = *unit}}, + .invalid = false}; + } + } + return invalid(); + default: + return invalid(); + } +} + +bool sameCell(table::Cell const& left, table::Cell const& right) { + auto const samePlaces = [](math::Rational const& lhs, math::Rational const& rhs) { + return lhs.decimalPlaces.value == rhs.decimalPlaces.value; + }; + if (left != right) { + return false; + } + if (auto const* const exact = std::get_if(&left)) { + return samePlaces(*exact, std::get(right)); + } + if (auto const* const measure = std::get_if(&left)) { + return samePlaces(measure->amount, std::get(right).amount); + } + return true; +} + +bool sameObject(Value const& left, Value const& right) { + if (left.kind() != right.kind()) { + return false; + } + if (auto const* const record = left.asRecord()) { + return record == right.asRecord(); + } + if (auto const* const list = left.asList()) { + return list == right.asList(); + } + return left == right; +} + +table::Cell ValueRowsSnapshot::cell(std::size_t row, std::size_t column) const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): column < _columns.size() by the condition above + if (column >= _columns.size() || _columns[column] == nullptr) { + return table::Cell{}; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): column < _columns.size() by the condition above + return _columns[column]->at(row); +} + +void ValueRowsSnapshot::readColumn(std::size_t column, table::ColumnSink& sink, std::size_t first, + std::size_t last) const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): column < _columns.size() by the condition above + if (column >= _columns.size() || _columns[column] == nullptr || first >= last) { + RowSnapshot::readColumn(column, sink, first, last); + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): column < _columns.size() by the condition above + sink.cells(first, std::span{*_columns[column]}.subspan(first, last - first)); +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +ValueRowsSource::ValueRowsSource(reactive::Runtime& runtime, std::vector columns, + std::function keyOf, + std::shared_ptr units) + : _runtime{&runtime}, + _columns{std::move(columns)}, + _keyOf{std::move(keyOf)}, + _units{std::move(units)}, + _held(_columns.size()) { + _infos.reserve(_columns.size() + 1); + for (auto const& column : _columns) { + _infos.push_back(table::ColumnInfo{.id = column.id, + .kind = column.kind.value_or(table::ColumnKind::Text), + .comparator = {}, + .format = {}, + .level = {}, + .dimensions = {}}); + } +} + +std::shared_ptr ValueRowsSource::snapshot() const { + if (_snapshot == nullptr) { + std::vector const>> cells; + cells.reserve(_infos.size()); + for (auto const& held : _held) { + cells.push_back(held.uses > 0 ? held.cells : nullptr); + } + if (_group) { + cells.push_back(_runCells); + } + _snapshot = std::make_shared(_rows, _keys, std::move(cells)); + } + return _snapshot; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one diff whose steps share their working vectors. +void ValueRowsSource::assign(ValueList rows) { + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): every vector here is sized to the row count and indexed below it; `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column + auto keys = std::make_shared>(); + auto kept = std::make_shared>(); + std::unordered_map index; + keys->reserve(rows.size()); + kept->reserve(rows.size()); + for (auto& row : rows) { + Key key = _keyOf(row); + if (!index.try_emplace(key, kept->size()).second) { + _runtime->core()->report(detail::site::kDuplicateKey); + continue; + } + keys->push_back(std::move(key)); + kept->push_back(std::move(row)); + } + std::size_t const count = kept->size(); + // Held, not referred to: the previous rows go when the new ones are taken, before the removed are counted. + auto const previousRows = _rows; + std::vector const& old = *previousRows; + constexpr std::size_t kNone = std::numeric_limits::max(); + std::vector was(count, kNone); + std::vector same(count, false); + std::size_t matched = 0; + bool inOrder = true; + std::size_t previous = 0; + for (std::size_t at = 0; at < count; ++at) { + auto const found = _index.find((*keys)[at]); + if (found == _index.end()) { + continue; + } + was[at] = found->second; + same[at] = detail::sameObject(old[found->second], (*kept)[at]); + inOrder = inOrder && (matched == 0 || found->second > previous); + previous = found->second; + ++matched; + } + bool const added = matched < count; + bool const dropped = matched < old.size(); + bool reset = std::exchange(_pending, Pending{}).any(); + std::vector updated(count, false); + for (std::size_t column = 0; column < _columns.size(); ++column) { + if (_held[column].uses == 0) { + continue; + } + reset = reassign(column, *kept, was, same, updated) || reset; + } + for (std::size_t at = 0; at < count; ++at) { + if (!same[at] && was[at] != kNone && !updated[at] && !(old[was[at]] == (*kept)[at])) { + updated[at] = true; + } + } + bool runsMoved = false; + if (_group) { + std::vector groupKeys(count); + for (std::size_t at = 0; at < count; ++at) { + groupKeys[at] = same[at] ? _byValues[was[at]] : readBy((*kept)[at]); + } + auto const before = _runs; + auto const recordsBefore = _runRecords; + _byValues = std::move(groupKeys); + buildRuns(*kept); + runsMoved = _runs != before; + if (!runsMoved) { + for (std::size_t run = 0; run < _runRecords.size(); ++run) { + if (!(_runRecords[run] == recordsBefore[run])) { + updated[_runFirst[run]] = true; + } + } + } + } + _rows = std::move(kept); + _keys = std::move(keys); + _index = std::move(index); + _snapshot.reset(); + bool const structural = added || dropped; + if (reset || (structural && (!inOrder || (added && dropped) || runsMoved)) || (!structural && runsMoved)) { + notify(table::RowChange{.kind = table::ChangeKind::Reset, .rows = {}}); + return; + } + if (dropped) { + std::vector stays(old.size(), false); + for (auto const heldIndex : was) { + if (heldIndex != kNone) { + stays[heldIndex] = true; + } + } + std::vector removed; + for (std::size_t at = 0; at < old.size(); ++at) { + if (!stays[at]) { + removed.push_back(at); + } + } + notify(table::RowChange{.kind = table::ChangeKind::Removed, .rows = std::move(removed)}); + } + if (added) { + std::vector inserted; + for (std::size_t at = 0; at < count; ++at) { + if (was[at] == kNone) { + inserted.push_back(at); + } + } + notify(table::RowChange{.kind = table::ChangeKind::Inserted, .rows = std::move(inserted)}); + } + std::vector changed; + for (std::size_t at = 0; at < count; ++at) { + if (updated[at]) { + changed.push_back(at); + } + } + if (!changed.empty()) { + notify(table::RowChange{.kind = table::ChangeKind::Updated, .rows = std::move(changed)}); + } + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) +} + +void ValueRowsSource::setGroup(std::function groupBy, UnitTable units) { + _group = std::move(groupBy); + _groupUnits = std::move(units); + bool const listed = _infos.size() > _columns.size(); + if (_group && !listed) { + _infos.push_back(table::ColumnInfo{.id = std::string{kGroupRunColumn}, + .kind = table::ColumnKind::Integer, + .comparator = {}, + .format = {}, + .level = {}, + .dimensions = {}}); + } else if (!_group && listed) { + _infos.pop_back(); + } + _byValues.clear(); + if (_group) { + _byValues.reserve(_rows->size()); + for (auto const& row : *_rows) { + _byValues.push_back(readBy(row)); + } + } + buildRuns(*_rows); + _snapshot.reset(); + notify(table::RowChange{.kind = table::ChangeKind::Reset, .rows = {}}); +} + +std::size_t ValueRowsSource::runOf(std::size_t sourceRow) const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): sourceRow < _runs.size() by the condition + return sourceRow < _runs.size() ? _runs[sourceRow] : 0; +} + +void ValueRowsSource::use(std::string_view column) { + auto const columnIndex = columnOf(column); + if (!columnIndex) { + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column (columnOf returns an index into `_columns`) + if (_held[*columnIndex].uses++ > 0) { + return; + } + rebuild(*columnIndex); + _snapshot.reset(); + notify(table::RowChange{.kind = table::ChangeKind::Reset, .rows = {}}); +} + +void ValueRowsSource::unuse(std::string_view column) { + auto const columnIndex = columnOf(column); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column (columnOf returns an index into `_columns`) + if (!columnIndex || _held[*columnIndex].uses == 0) { + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column (columnOf returns an index into `_columns`) + if (--_held[*columnIndex].uses > 0) { + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column (columnOf returns an index into `_columns`) + _held[*columnIndex] = Held{}; + _snapshot.reset(); +} + +RecordOf ValueRowsSource::recordOf() { + return [](table::RowSnapshot const& snapshot, std::size_t sourceRow) { + auto const* const rows = dynamic_cast(&snapshot); + return RowRecord{.key = snapshot.rowId(sourceRow), .row = rows == nullptr ? Value{} : rows->row(sourceRow)}; + }; +} + +std::size_t ValueRowsSource::cellsHeld() const noexcept { + std::size_t cells = 0; + for (auto const& held : _held) { + cells += held.cells == nullptr ? 0 : held.cells->size(); + } + return cells + (_runCells == nullptr ? 0 : _runCells->size()); +} + +std::size_t ValueRowsSource::invalidCells(std::string_view column) const { + auto const columnIndex = columnOf(column); + if (!columnIndex) { + return 0; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column (columnOf returns an index into `_columns`) + return static_cast(std::ranges::count(_held[*columnIndex].invalid, std::uint8_t{1})); +} + +std::optional ValueRowsSource::columnOf(std::string_view columnId) const { + auto const found = std::ranges::find(_columns, columnId, &ValueColumn::id); + if (found == _columns.end()) { + return std::nullopt; + } + return static_cast(found - _columns.begin()); +} + +Value ValueRowsSource::fieldOf(std::size_t column, Value const& row) const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column + auto const* const field = row.field(_columns[column].id); + return field == nullptr ? Value{} : *field; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): column index, then row index, in every call here. +Value ValueRowsSource::valueOf(std::size_t column, std::size_t row, Value const& input) const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column; row < trackers.size() by the condition + auto const& trackers = _held[column].trackers; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column; row < trackers.size() by the condition + if (row < trackers.size() && trackers[row] != nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column; row < trackers.size() by the condition + return trackers[row]->value; + } + return fieldOf(column, input); +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): column index, then row index, in every call here. +std::unique_ptr ValueRowsSource::track(std::size_t column, std::size_t row, + Value const& input) { + auto tracker = std::make_unique(); + tracker->column = column; + tracker->row = row; + tracker->input = input; + Tracker* const self = tracker.get(); + tracker->effect = std::make_unique(*_runtime, [this, self] { rerun(*self); }); + self->live = true; + return tracker; +} + +void ValueRowsSource::rerun(Tracker& tracker) { + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column; `row` is below the row count every per-row vector here is sized to + Value value; + try { + value = _columns[tracker.column].sortBy(tracker.input); + } catch (...) { + value = Value{}; + } + ++_derived; + tracker.value = std::move(value); + if (!tracker.live) { + return; + } + auto& held = _held[tracker.column]; + std::size_t const row = tracker.row; + auto const kind = vote(held, tracker.column, row, detail::voteOf(tracker.value)); + _pending.rerun.insert(row); + if (kind != _infos[tracker.column].kind) { + _infos[tracker.column].kind = kind; + reconvert(tracker.column); + _pending.reset = true; + } else { + auto converted = detail::convertedCell(tracker.value, kind, _units.get()); + held.invalid[row] = converted.invalid ? 1 : 0; + if (!detail::sameCell(converted.cell, (*held.cells)[row])) { + _snapshot.reset(); + writable(held)[row] = std::move(converted.cell); + _pending.rows.push_back(row); + } + } + if (!_posted) { + _posted = true; + _runtime->owner().post(_alive.guard([this] { flushTracked(); })); + } + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) +} + +void ValueRowsSource::flushTracked() { + _posted = false; + auto pending = std::exchange(_pending, Pending{}); + if (!pending.any()) { + return; + } + if (pending.reset || pending.rerun.size() == _rows->size()) { + notify(table::RowChange{.kind = table::ChangeKind::Reset, .rows = {}}); + return; + } + std::ranges::sort(pending.rows); + auto const [first, last] = std::ranges::unique(pending.rows); + pending.rows.erase(first, last); + notify(table::RowChange{.kind = table::ChangeKind::Updated, .rows = std::move(pending.rows)}); +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): column index, then row index, in every call here. +table::ColumnKind ValueRowsSource::vote(Held& held, std::size_t column, std::size_t row, detail::ValueVote next) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `row` is below the row count every per-row vector here is sized to + auto& current = held.votes[row]; + --held.counts.at(static_cast(current)); + ++held.counts.at(static_cast(next)); + current = next; + return kindOf(column, held); +} + +table::ColumnKind ValueRowsSource::kindOf(std::size_t column, Held const& held) const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column + if (auto const& declared = _columns[column].kind) { + return *declared; + } + return detail::inferredKind(held.counts, held.votes); +} + +std::vector& ValueRowsSource::writable(Held& held) { + if (held.cells.use_count() > 1) { + held.cells = std::make_shared>(*held.cells); + } + return *held.cells; +} + +void ValueRowsSource::reconvert(std::size_t column) { + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column; `row` is below the row count every per-row vector here is sized to + auto& held = _held[column]; + auto const kind = _infos[column].kind; + auto cells = std::make_shared>(_rows->size()); + for (std::size_t row = 0; row < _rows->size(); ++row) { + auto converted = detail::convertedCell(valueOf(column, row, (*_rows)[row]), kind, _units.get()); + (*cells)[row] = std::move(converted.cell); + held.invalid[row] = converted.invalid ? 1 : 0; + } + held.cells = std::move(cells); + _snapshot.reset(); + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) +} + +void ValueRowsSource::rebuild(std::size_t column) { + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column; `row` is below the row count every per-row vector here is sized to + auto& held = _held[column]; + std::size_t const count = _rows->size(); + held.votes.assign(count, detail::ValueVote::None); + held.invalid.assign(count, 0); + held.counts = {}; + held.counts[0] = count; + held.trackers.clear(); + if (_columns[column].sortBy) { + held.trackers.resize(count); + } + for (std::size_t row = 0; row < count; ++row) { + Value const& input = (*_rows)[row]; + if (_columns[column].sortBy) { + held.trackers[row] = track(column, row, input); + static_cast(vote(held, column, row, detail::voteOf(held.trackers[row]->value))); + } else { + ++_derived; + static_cast(vote(held, column, row, detail::voteOf(fieldOf(column, input)))); + } + } + _infos[column].kind = kindOf(column, held); + reconvert(column); + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) +} + +bool ValueRowsSource::reassign(std::size_t column, std::vector const& rows, std::vector const& was, + std::vector const& same, std::vector& updated) { + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): `column` indexes `_columns`, and `_held` and `_infos` hold one entry per column; `row` is below the row count every per-row vector here is sized to + auto& held = _held[column]; + bool const tracked = static_cast(_columns[column].sortBy); + std::size_t const count = rows.size(); + Held next; + next.uses = held.uses; + next.votes.assign(count, detail::ValueVote::None); + next.invalid.assign(count, 0); + if (tracked) { + next.trackers.resize(count); + } + auto cells = std::make_shared>(count); + std::vector fresh(count); + for (std::size_t row = 0; row < count; ++row) { + if (same[row]) { + next.votes[row] = held.votes[was[row]]; + next.invalid[row] = held.invalid[was[row]]; + (*cells)[row] = (*held.cells)[was[row]]; + if (tracked) { + next.trackers[row] = std::move(held.trackers[was[row]]); + next.trackers[row]->row = row; + } + } else if (tracked) { + next.trackers[row] = track(column, row, rows[row]); + fresh[row] = next.trackers[row]->value; + next.votes[row] = detail::voteOf(fresh[row]); + } else { + ++_derived; + fresh[row] = fieldOf(column, rows[row]); + next.votes[row] = detail::voteOf(fresh[row]); + } + ++next.counts.at(static_cast(next.votes[row])); + } + auto const kind = kindOf(column, next); + bool const changedKind = kind != _infos[column].kind; + for (std::size_t row = 0; row < count; ++row) { + if (same[row] && !changedKind) { + continue; + } + Value value; + if (same[row]) { + value = tracked ? next.trackers[row]->value : fieldOf(column, rows[row]); + } else { + value = std::move(fresh[row]); + } + auto converted = detail::convertedCell(value, kind, _units.get()); + next.invalid[row] = converted.invalid ? 1 : 0; + if (!changedKind && was[row] != std::numeric_limits::max() && + !detail::sameCell(converted.cell, (*held.cells)[was[row]])) { + updated[row] = true; + } + (*cells)[row] = std::move(converted.cell); + } + next.cells = std::move(cells); + _infos[column].kind = kind; + held = std::move(next); + return changedKind; + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) +} + +void ValueRowsSource::buildRuns(std::vector const& rows) { + _runs.clear(); + _runFirst.clear(); + _runRecords.clear(); + if (!_group) { + _runCells.reset(); + return; + } + auto cells = std::make_shared>(); + cells->reserve(rows.size()); + _runs.reserve(rows.size()); + // A heading's key is its run's key and its ordinal among the runs with an equal key, as the interpreter + // keys it: adjacent grouping can give two runs one key. + std::map> ordinals; + ValueList run; + std::size_t first = 0; + auto const close = [&] { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): first and row are below the row count _byValues is sized to + Value const& key = _byValues[first]; + std::string const json = ui::detail::canonicalJson(key); + Value const record = runRecord(key, std::exchange(run, {})); + ValueRecord entry = *record.asRecord(); + entry.insert_or_assign(std::string{detail::kGroupHeadingField}, + Value{"\x1Fgroup:" + json + ":" + std::to_string(ordinals[json]++)}); + _runRecords.emplace_back(std::move(entry)); + _runFirst.push_back(first); + }; + for (std::size_t row = 0; row < rows.size(); ++row) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): first and row are below the row count _byValues is sized to + if (!run.empty() && !detail::sameElement(_byValues[first], _byValues[row], _groupUnits)) { + close(); + } + if (run.empty()) { + first = row; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): first and row are below the row count _byValues is sized to + run.push_back(rows[row]); + _runs.push_back(_runRecords.size()); + cells->emplace_back(static_cast(_runRecords.size())); + } + if (!run.empty()) { + close(); + } + _runCells = std::move(cells); +} + +} // namespace morph::ui + +namespace morph::ui::detail { + +std::optional jsonInteger(glz::generic_u64 const& member) { + if (auto const* const value = member.get_if()) { + return *value; + } + if (auto const* const value = member.get_if(); + value != nullptr && *value <= static_cast(std::numeric_limits::max())) { + return static_cast(*value); + } + return std::nullopt; +} + +std::optional jsonDecimal(glz::generic_u64 const& member) { + auto const* const object = member.get_if(); + if (object == nullptr || (object->size() != 3 && object->size() != 4)) { + return std::nullopt; + } + auto const integer = [object](std::string_view name) -> std::optional { + auto const* const found = object->find(name); + return found == object->end() ? std::nullopt : jsonInteger(found->second); + }; + auto const num = integer("num"); + auto const den = integer("den"); + auto const places = integer("dp"); + if (!num || !den || !places || *den == 0 || *places < 0 || std::cmp_greater(*places, math::kMaxDecimalPlaces)) { + return std::nullopt; + } + std::string const* unit = nullptr; + if (object->size() == 4) { + auto const* const found = object->find("unit"); + unit = found == object->end() ? nullptr : found->second.get_if(); + if (unit == nullptr) { + return std::nullopt; + } + } + auto const amount = math::Rational::from(math::Numerator{*num}, math::Denominator{*den}, + math::DecimalPlaces{static_cast(*places)}); + if (!amount) { + return std::nullopt; + } + return JsonDecimal{.amount = *amount, .unit = unit}; +} + +} // namespace morph::ui::detail diff --git a/src/ui/table_rows_2.cpp b/src/ui/table_rows_2.cpp new file mode 100644 index 000000000..49dac95c6 --- /dev/null +++ b/src/ui/table_rows_2.cpp @@ -0,0 +1,1854 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui::detail { + +JsonVote jsonVoteOf(glz::generic_u64 const& member) { + if (member.is_boolean()) { + return JsonVote::Bool; + } + if (member.is_string()) { + return JsonVote::Text; + } + if (member.is_number()) { + return jsonInteger(member) ? JsonVote::Integer : JsonVote::Number; + } + if (auto const decimal = jsonDecimal(member)) { + return decimal->unit != nullptr ? JsonVote::Measure : JsonVote::Decimal; + } + return JsonVote::None; +} + +table::ColumnKind inferredJsonKind(std::span rows, std::string_view column) { + std::array counts{}; + JsonVote first = JsonVote::None; + for (auto const& row : rows) { + auto const* const object = row.get_if(); + if (object == nullptr) { + continue; + } + auto const* const found = object->find(column); + if (found == object->end()) { + continue; + } + JsonVote const vote = jsonVoteOf(found->second); + if (vote == JsonVote::None) { + continue; + } + ++counts.at(static_cast(vote)); + if (first == JsonVote::None) { + first = vote; + } + } + auto const count = [&counts](JsonVote vote) { return counts.at(static_cast(vote)); }; + std::size_t kinds = 0; + for (std::size_t at = 1; at < kJsonVotes; ++at) { + kinds += counts.at(at) > 0 ? 1U : 0U; + } + if (kinds == 0) { + return table::ColumnKind::Text; + } + if (kinds == 1) { + return kindOfJsonVote(first); + } + bool const integers = count(JsonVote::Integer) > 0; + bool const numbers = count(JsonVote::Number) > 0; + bool const decimals = count(JsonVote::Decimal) > 0; + std::size_t const numeric = (integers ? 1U : 0U) + (numbers ? 1U : 0U) + (decimals ? 1U : 0U); + if (numeric == kinds && integers && !numbers) { + return table::ColumnKind::Decimal; + } + if (numeric == kinds && integers && numbers) { + return table::ColumnKind::Number; + } + return kindOfJsonVote(first); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity): one case per column kind. +table::Cell typedCell(glz::generic_u64 const& member, table::ColumnKind kind, table::UnitRegistry const* units, + std::map& named) { + using table::ColumnKind; + if (member.is_null()) { + return table::Cell{}; + } + if (auto const* const flag = member.get_if()) { + return table::Cell{*flag}; + } + if (auto const integer = jsonInteger(member)) { + if (kind == ColumnKind::Decimal) { + return table::Cell{math::Rational{*integer, math::DecimalPlaces{0}}}; + } + if (kind == ColumnKind::Number) { + return table::Cell{static_cast(*integer)}; + } + return table::Cell{*integer}; + } + if (auto const* const real = member.get_if()) { + return table::Cell{*real}; + } + if (auto const* const large = member.get_if()) { + return table::Cell{static_cast(*large)}; + } + if (auto const* const text = member.get_if()) { + table::IsoDateParser const parser; + if (kind == ColumnKind::Date) { + if (auto const days = parser.parseDate(*text, {})) { + return table::Cell{*days}; + } + } else if (kind == ColumnKind::DateTime) { + if (auto const seconds = parser.parseDateTime(*text, {})) { + return table::Cell{*seconds}; + } + } + return table::Cell{*text}; + } + if (auto const decimal = jsonDecimal(member)) { + if (decimal->unit == nullptr) { + return table::Cell{decimal->amount}; + } + if (kind == ColumnKind::Measure) { + auto const unit = units == nullptr ? std::nullopt : units->find(*decimal->unit); + if (unit) { + named.try_emplace(*unit, *decimal->unit); + } + return table::Cell{table::Measure{.amount = decimal->amount, .unit = unit.value_or(table::kUnknownUnit)}}; + } + } + return table::Cell{glz::write_json(member).value_or(std::string{})}; +} + +std::optional typedKey(glz::generic_u64 const& member) { + if (auto const integer = jsonInteger(member)) { + return table::RowId{*integer}; + } + if (auto const* const text = member.get_if()) { + return table::RowId{*text}; + } + return std::nullopt; +} + +std::expected typedPageOf(TypedPageDom const& dom, + table::TableDescription const& description, + table::UnitRegistry const* units) { + auto const invalid = [](std::string message) { + return std::unexpected(table::TableError{ + .code = table::TableErrorCode::InvalidValue, .column = {}, .message = std::move(message)}); + }; + std::shared_ptr built; + bool const measures = std::ranges::any_of(description.columns, [](table::TableColumn const& column) { + return column.info.kind == table::ColumnKind::Measure; + }); + if (measures && units == nullptr) { + auto registry = table::registryOf(description); + if (!registry) { + return std::unexpected(std::move(registry.error())); + } + built = std::move(*registry); + units = built.get(); + } + auto const rowCount = static_cast(dom.rows.size()); + std::int64_t previous = -1; + for (auto const& unloaded : dom.unloadedRows) { + if (unloaded.index <= previous || unloaded.index >= rowCount) { + return invalid("an unloaded row at " + std::to_string(unloaded.index) + " in a page of " + + std::to_string(rowCount) + " rows, or out of order"); + } + previous = unloaded.index; + } + if (!dom.indices.empty() && dom.indices.size() != dom.rows.size()) { + return invalid("a page of " + std::to_string(dom.indices.size()) + " indices and " + + std::to_string(dom.rows.size()) + " rows"); + } + if (std::ranges::any_of(dom.indices, [](std::int64_t index) { return index < 0; })) { + return invalid("a negative view row in indices"); + } + table::GenericPage page; + page.columns.reserve(description.columns.size()); + for (auto const& column : description.columns) { + page.columns.push_back(column.info.id); + } + page.keys.reserve(dom.rows.size()); + page.rows.reserve(dom.rows.size()); + glz::generic_u64 const absent{}; + for (std::size_t at = 0; at < dom.rows.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < dom.rows.size() by the loop + auto const* const object = dom.rows[at].get_if(); + if (object == nullptr) { + return invalid("row " + std::to_string(at) + " is not an object"); + } + auto const* const keyMember = object->find(description.key); + auto key = keyMember == object->end() ? std::nullopt : typedKey(keyMember->second); + if (!key) { + return invalid("row " + std::to_string(at) + " has no key `" + description.key + "`"); + } + page.keys.push_back(std::move(*key)); + table::GenericRow cells; + cells.reserve(description.columns.size()); + for (auto const& column : description.columns) { + auto const* const found = object->find(column.info.id); + cells.push_back( + typedCell(found == object->end() ? absent : found->second, column.info.kind, units, page.units)); + } + page.rows.push_back(std::move(cells)); + } + page.total = dom.total; + page.totalKind = dom.totalKind; + page.offset = dom.offset; + page.unloadedRows = dom.unloadedRows; + page.undecided = dom.undecided; + page.awaiting = dom.awaiting; + page.failed = dom.failed; + page.indices = dom.indices; + page.distinct = dom.distinct; + return page; +} + +std::vector unlistedUnits(std::span rows, + table::TableDescription const& description, + table::UnitRegistry const* units, std::size_t room) { + std::vector out; + for (auto const& column : description.columns) { + if (column.info.kind != table::ColumnKind::Measure) { + continue; + } + for (auto const& row : rows) { + auto const* const object = row.get_if(); + auto const found = object == nullptr ? std::optional{} + : std::optional{object->find(column.info.id)}; + if (!found || *found == object->end()) { + continue; + } + auto const decimal = jsonDecimal((*found)->second); + if (out.size() >= room || !decimal || decimal->unit == nullptr || decimal->unit->empty() || + (units != nullptr && units->find(*decimal->unit)) || + std::ranges::contains(out, *decimal->unit, &table::UnitInfo::id)) { + continue; + } + out.push_back(table::UnitInfo{.id = *decimal->unit, + .symbol = *decimal->unit, + .dimension = *decimal->unit, + .toBase = math::Rational{1, math::DecimalPlaces{0}}, + .decimals = decimal->amount.decimalPlaces.value}); + } + } + return out; +} + +std::expected typedPageDom(std::string_view json) { + TypedPageDom dom; + if (auto const failed = + glz::read(dom, json)) { + return std::unexpected(table::TableError{.code = table::TableErrorCode::InvalidValue, + .column = {}, + .message = "not a page: " + glz::format_error(failed, json)}); + } + return dom; +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +std::expected readTypedPage(std::string_view json, + table::TableDescription const& description, + table::UnitRegistry const* units) { + auto dom = detail::typedPageDom(json); + if (!dom) { + return std::unexpected(std::move(dom.error())); + } + return detail::typedPageOf(*dom, description, units); +} + +WindowRows::WindowRows(Session& session, WindowRowsOptions options) + : _session{&session}, + _options{std::move(options)}, + _window{_options.pageSize, _options.maxPages, _options.maxKeys, _options.maxColumns}, + _restoring{_options.restoring}, + _watched{_options.records.empty()}, + _unanswered{_options.records.size()}, + _inferring{!_options.action.empty() && !_options.inferKinds.empty()} { + // A record watch hears a reconnect as a change of every row; a window that watches none hears it here. + if (_options.records.empty()) { + _reconnect = _session->onReconnected(_scope.token().guard([this] { + forgetDistinct(); + _window.invalidate(); + pump(); + })); + } + for (auto const& record : _options.records) { + auto watching = _session->watchRecord( + record, _scope.token().guard([this](effects::RecordChange const& change) { heard(change); })); + watching.then(_scope, [this](WatchHolder const& holder) { + _watches.push_back(holder); + answered(); + }); + watching.onError(_scope, [this](std::exception_ptr const&) { answered(); }); + } +} + +// NOLINTNEXTLINE(bugprone-exception-escape): only allocation can throw, and that ends the process either way. +WindowRows::~WindowRows() { + stopAll(); + for (auto& [flightId, stop] : _distinctFlights) { + static_cast(flightId); + stop.request_stop(); + } + for (auto const& held : _keyRequests) { + if (auto const request = held.lock()) { + for (auto& stop : request->stops) { + stop.request_stop(); + } + // Answered now, while the owner it delivers on is alive: the request may outlive it in a reply's + // handler. + if (request->waiting > 0) { + request->waiting = 0; + request->promise.resolve( + std::expected, table::TableError>{std::unexpected(table::TableError{ + .code = table::TableErrorCode::Unavailable, .column = {}, .message = "the rows are gone"})}); + } + } + } + for (auto const& held : _rowsRequests) { + if (auto const request = held.lock()) { + for (auto& stop : request->stops) { + stop.request_stop(); + } + if (request->waiting > 0) { + request->waiting = 0; + request->promise.resolve( + std::expected, table::TableError>{std::unexpected(table::TableError{ + .code = table::TableErrorCode::Unavailable, .column = {}, .message = "the rows are gone"})}); + } + } + } + _locateStop.request_stop(); +} + +void WindowRows::setDescription(table::TableDescription description) { + if (_descriptionError) { + _error.reset(); + } + _descriptionError = false; + bool const another = !_description || _description->revision != description.revision; + if (another) { + forgetDistinct(); + } + bool const replacing = _description.has_value() && another; + table::FitReport report; + auto fitted = table::fitState(table::StateDocument{.version = table::kStateVersion, + .layout = {}, + .sort = _sort, + .filters = _filter, + .view = {}, + .carried = {}}, + description, report); + _sort = fitted.sort.value_or(SortChain{}); + _filter = fitted.filters.value_or(table::FilterSpec{}); + _description = std::move(description); + // One registry for the description: a page's measure cells and the records made of them name units by its + // numbers. A description whose units do not build leaves it null, and its pages are refused as they read. + auto registry = table::registryOf(*_description); + _units = registry ? std::move(*registry) : nullptr; + _infos.clear(); + for (auto const& column : _description->columns) { + _infos.insert_or_assign(column.info.id, column.info); + } + std::erase_if(_columns, [this](std::string const& columnId) { return !_infos.contains(columnId); }); + ++_columnsStamp; + if (another) { + _error.reset(); + } + if (replacing) { + restart(); + } else { + pump(); + } +} + +void WindowRows::setDescription(Value const& described) { + table::TableDescription description; + auto const text = ui::detail::canonicalJson(described); + if (auto const failed = glz::read(description, text)) { + _descriptionError = true; + _error = + table::TableError{.code = table::TableErrorCode::InvalidValue, + .column = {}, + .message = "the table's description does not read: " + glz::format_error(failed, text)}; + status(); + return; + } + setDescription(std::move(description)); +} + +void WindowRows::release() { + if (!_restoring) { + return; + } + _restoring = false; + pump(); +} + +void WindowRows::retry() { + _error.reset(); + _retry = true; + _window.invalidate(); + pump(); +} + +TableTotal WindowRows::total() const { + auto const rows = _window.total(); + return TableTotal{.rows = rows.value_or(0), .kind = _window.totalKind(), .known = rows.has_value()}; +} + +std::optional WindowRows::row(std::int64_t index) const { + auto const* const key = _window.key(index); + if (key == nullptr) { + return std::nullopt; + } + auto [found, made] = _memo.try_emplace(*key, Entry{.key = *key, .record = {}, .stamp = 0}); + Entry& entry = found->second; + if (made || entry.stamp != _columnsStamp) { + ValueRecord fields; + auto const convert = [&](std::string const& columnId) { + auto const* const cell = _window.cell(index, columnId); + auto const info = _infos.find(columnId); + if (cell == nullptr || info == _infos.end()) { + return; + } + fields.insert_or_assign(columnId, cellValue(*cell, info->second, _units.get())); + ++_stats.cellsConverted; + }; + if (_columns.empty() && _description) { + for (auto const& column : _description->columns) { + convert(column.info.id); + } + } else { + for (auto const& columnId : _columns) { + convert(columnId); + } + } + entry.record = Value{std::move(fields)}; + entry.stamp = _columnsStamp; + } + return TableRowRef{.key = entry.key, .row = entry.record}; +} + +std::vector> WindowRows::heldRanges() const { + auto const size = std::max(_options.pageSize, 1); + std::vector> out; + for (std::int64_t const page : _heldPages) { + if (heldPage(page)) { + out.emplace_back(page * size, size); + } + } + return out; +} + +void WindowRows::visible(std::int64_t first, std::int64_t count, std::span columns) { + _first = std::max(first, 0); + _count = std::max(count, 0); + std::vector named(columns.begin(), columns.end()); + if (_description) { + std::erase_if(named, [this](std::string const& columnId) { return !_infos.contains(columnId); }); + } + if (named != _columns) { + _columns = std::move(named); + ++_columnsStamp; + } + _hasVisible = true; + auto const anchor = _first / std::max(_options.pageSize, 1); + if (anchor != _anchor) { + _anchor = anchor; + _anchorSince = now(); + } + pump(); +} + +async::Completion, table::TableError>> WindowRows::keysOf(std::int64_t first, + std::int64_t count) { + using Result = std::expected, table::TableError>; + auto [completion, promise] = async::Completion::makeSettleable(&_session->runtime().owner()); + if (first < 0 || count < 0 || count > std::numeric_limits::max() - first) { + promise.resolve(Result{std::unexpected( + table::TableError{.code = table::TableErrorCode::InvalidSpec, + .column = {}, + .message = std::format("{} rows from view row {} are not a range", count, first)})}); + return std::move(completion); + } + auto const size = std::max(_options.pageSize, 1); + auto state = std::make_shared(KeysRequest{.promise = std::move(promise), + .first = first, + .count = count, + .pages = {}, + .waiting = 0, + .failed = std::nullopt}); + std::vector missing; + for (std::int64_t page = first / size; count > 0 && page <= (first + count - 1) / size; ++page) { + std::int64_t const from = std::max(first, page * size); + std::int64_t const end = std::min(first + count, (page + 1) * size); + for (std::int64_t at = from; at < end; ++at) { + if (_window.key(at) == nullptr) { + missing.push_back(page); + break; + } + } + } + if (missing.empty() || !_description) { + finishKeys(*state); + return std::move(completion); + } + state->waiting = missing.size(); + std::erase_if(_keyRequests, [](std::weak_ptr const& held) { return held.expired(); }); + _keyRequests.push_back(state); + for (std::int64_t const page : missing) { + table::TableQuery query = queryOf(table::PageRequest{.offset = page * size, .limit = size}, {}); + query.columns = std::vector{}; + auto body = bodyOf(query); + if (!body) { + keysAnswered(*state, page, std::unexpected(body.error())); + continue; + } + ::core::async::StopSource stop; + auto reply = _session->read(_options.channel, "Table." + _options.table, *body, stop.get_token()); + state->stops.push_back(std::move(stop)); + reply.then(_scope, [this, state, page](std::string const& text) { + auto read = table::readGenericPage(text, *_description, _units.get()); + if (!read) { + keysAnswered(*state, page, std::unexpected(read.error())); + return; + } + keysAnswered(*state, page, std::move(read->keys)); + }); + reply.onError(_scope, [this, state, page](std::exception_ptr const& error) { + // A stopped fetch is the window going: the range is never answered. + if (!wasCancelled(error)) { + keysAnswered(*state, page, std::unexpected(failureOf(error))); + } + }); + } + return std::move(completion); +} + +void WindowRows::locateRow(table::RowId key, ::core::async::StopToken stop, + std::function done) { + table::TableQuery query = queryOf(table::PageRequest{}, {}); + query.columns = std::vector{}; + query.keys = std::vector{std::move(key)}; + auto body = _description ? bodyOf(query) : std::expected{std::unexpected(unavailable())}; + if (!body) { + _session->runtime().owner().post( + _scope.guard([stop = std::move(stop), done = std::move(done), error = std::move(body.error())] { + if (!stop.stop_requested()) { + done(std::unexpected(error)); + } + })); + return; + } + auto reply = _session->read(_options.channel, actionName(), *body, stop); + reply.then(_scope, [this, done, stop](std::string const& text) { + if (stop.stop_requested()) { + return; + } + if (!_description) { + done(std::unexpected(unavailable())); + return; + } + // Only the indices are read: a typed reply here fixes no inferred kind, which a page's first rows do. + auto read = _options.action.empty() ? table::readGenericPage(text, *_description, _units.get()) + : readTypedPage(text, *_description, _units.get()); + if (!read) { + done(std::unexpected(read.error())); + return; + } + // No row: the view lacks the key. A row without its index leaves where it is unknown, which is not + // its absence. + if (read->rows.empty()) { + done(std::nullopt); + } else if (read->indices.empty()) { + done(std::unexpected(table::TableError{.code = table::TableErrorCode::InvalidValue, + .column = {}, + .message = "the keyed reply gives its row no index"})); + } else { + done(std::optional{read->indices.front()}); + } + }); + reply.onError(_scope, [done, stop](std::exception_ptr const& error) { + if (!stop.stop_requested() && !wasCancelled(error)) { + done(std::unexpected(failureOf(error))); + } + }); +} + +async::Completion, table::TableError>> WindowRows::fetchRows( + std::vector keys, std::vector columns) { + using Result = std::expected, table::TableError>; + auto [completion, promise] = async::Completion::makeSettleable(&_session->runtime().owner()); + auto state = std::make_shared( + RowsRequest{.promise = std::move(promise), .rows = {}, .waiting = 0, .failed = std::nullopt, .stops = {}}); + if (keys.empty() || !_description) { + if (!_description) { + state->failed = unavailable(); + } + finishRows(*state); + return std::move(completion); + } + std::size_t const chunk = std::max(_options.maxKeys, 1); + state->waiting = (keys.size() + chunk - 1) / chunk; + std::erase_if(_rowsRequests, [](std::weak_ptr const& held) { return held.expired(); }); + _rowsRequests.push_back(state); + auto const named = std::make_shared const>(std::move(columns)); + for (std::size_t from = 0; from < keys.size(); from += chunk) { + table::TableQuery query = queryOf(table::PageRequest{}, {}); + query.columns = *named; + query.keys = + std::vector(keys.begin() + static_cast(from), + keys.begin() + static_cast(std::min(from + chunk, keys.size()))); + auto body = bodyOf(query); + if (!body) { + rowsAnswered(*state, std::unexpected(std::move(body.error()))); + continue; + } + ::core::async::StopSource stop; + auto reply = _session->read(_options.channel, actionName(), *body, stop.get_token()); + state->stops.push_back(std::move(stop)); + reply.then(_scope, [this, state, named](std::string const& text) { + if (!_description) { + rowsAnswered(*state, std::unexpected(unavailable())); + return; + } + auto read = _options.action.empty() ? table::readGenericPage(text, *_description, _units.get()) + : readTypedPage(text, *_description, _units.get()); + if (!read) { + rowsAnswered(*state, std::unexpected(std::move(read.error()))); + return; + } + rowsAnswered(*state, fetchedOf(*read, *named)); + }); + reply.onError(_scope, [state](std::exception_ptr const& error) { + // A stopped fetch is the window going: the rows are never answered. + if (!wasCancelled(error)) { + rowsAnswered(*state, std::unexpected(failureOf(error))); + } + }); + } + return std::move(completion); +} + +void WindowRows::locate(table::RowId key, std::function)> done) { + stopLocating(); + locateRow(std::move(key), _locateStop.get_token(), + [done = std::move(done)](RowLocation const& found) { done(found ? *found : std::nullopt); }); +} + +void WindowRows::stopLocating() { + _locateStop.request_stop(); + _locateStop = ::core::async::StopSource{}; +} + +std::expected WindowRows::setSort(SortChain sort) { + if (_description) { + if (auto error = sortError(sort)) { + return std::unexpected(std::move(*error)); + } + } + if (sort == _sort) { + return {}; + } + _sort = std::move(sort); + restart(); + return {}; +} + +std::expected WindowRows::setFilter(table::FilterSpec filter) { + if (_description) { + auto const infos = table::columnInfos(*_description); + // A measure's operand is read with the description's units. + table::Services services; + services.units = _units; + auto compiled = table::compileFilterGuarded(filter, infos, services, _description->groups); + if (!compiled) { + return std::unexpected(std::move(compiled.error())); + } + } + if (filter == _filter) { + return {}; + } + _filter = std::move(filter); + // The revision held is of the old filter's view: a selection taken before the new one answers would name it. + _viewRevision.clear(); + _outOfView.clear(); + // The retained rows are of the filter they no longer matched. + _retained.clear(); + _retainedSet.clear(); + ++_retainStamp; + restart(); + return {}; +} + +async::Completion> WindowRows::distinctValues( + table::DistinctRequest request) { + using Result = std::expected; + auto [completion, promise] = async::Completion::makeSettleable(&_session->runtime().owner()); + if (!_description || !_description->capabilities.distinct || !_options.action.empty()) { + promise.resolve(Result{std::unexpected(table::TableError{ + .code = table::TableErrorCode::Unavailable, .column = {}, .message = "the table lists no values"})}); + return std::move(completion); + } + table::TableQuery query; + query.filters = _filter; + query.distinct = std::move(request); + auto body = bodyOf(query); + if (!body) { + promise.resolve(Result{std::unexpected(std::move(body.error()))}); + return std::move(completion); + } + std::string key = ui::detail::canonicalJson(*body); + if (auto const held = _distinct.find(key); held != _distinct.end()) { + promise.resolve(Result{held->second}); + return std::move(completion); + } + ::core::async::StopSource stop; + ++_stats.distinctFetches; + auto reply = _session->read(_options.channel, actionName(), *body, stop.get_token()); + // The oldest values list still in flight is stopped past the bound: its menu has asked for others since. + std::uint64_t const flight = ++_distinctFlight; + _distinctFlights.emplace(flight, std::move(stop)); + if (_distinctFlights.size() > kMaxDistinctFlights) { + _distinctFlights.begin()->second.request_stop(); + _distinctFlights.erase(_distinctFlights.begin()); + } + auto const settle = std::make_shared::Promise>(std::move(promise)); + reply.then(_scope, [this, settle, flight, epoch = _distinctEpoch, key = std::move(key)](std::string const& text) { + _distinctFlights.erase(flight); + auto read = table::readGenericPage(text, *_description, _units.get()); + if (!read) { + settle->resolve(Result{std::unexpected(std::move(read.error()))}); + return; + } + if (!read->distinct) { + settle->resolve(Result{std::unexpected(table::TableError{ + .code = table::TableErrorCode::InvalidValue, .column = {}, .message = "the reply holds no values"})}); + return; + } + // A reply asked for before the record changed, the session reconnected or the revision moved answers + // its menu, and is not kept: it may count rows as they were. + if (epoch == _distinctEpoch) { + keepDistinct(key, *read->distinct); + } + settle->resolve(Result{std::move(*read->distinct)}); + }); + reply.onError(_scope, [this, settle, flight](std::exception_ptr const& error) { + _distinctFlights.erase(flight); + settle->resolve(Result{std::unexpected(failureOf(error))}); + }); + return std::move(completion); +} + +TableCountsView WindowRows::counts() const { + auto const awaiting = _window.awaiting(); + auto const failed = _window.failed(); + return TableCountsView{.view = total(), + .source = std::nullopt, + .undecided = _window.undecided(), + .pending = _window.pending() || !_rowsFlights.empty(), + .awaiting = {awaiting.begin(), awaiting.end()}, + .failed = {failed.begin(), failed.end()}, + .retained = static_cast(_unmatchedHeld.size()), + .busy = _states.busyCount()}; +} + +void WindowRows::moveKey(table::RowId const& from, table::RowId const& target) { + _states.move(from, target); + if (from == target || !_retainedSet.contains(from)) { + return; + } + _retainedSet.erase(from); + if (_retainedSet.insert(target).second) { + std::ranges::replace(_retained, from, target); + } else { + std::erase(_retained, from); + } + _unmatched.erase(from); + _unmatchedHeld.erase(from); + // The revision held is of the view with the old key retained. + ++_retainStamp; + _viewRevision.clear(); +} + +RetainResult WindowRows::retain(std::span keys) { + std::vector added; + std::unordered_set seen; + for (table::RowId const& key : keys) { + if (!_retainedSet.contains(key) && seen.insert(key).second) { + added.push_back(key); + } + } + if (_retained.size() + added.size() > table::QueryLimits{}.maxRetained) { + return RetainResult::OverBound; + } + if (added.empty()) { + return RetainResult::Retained; + } + _retainedSet.insert(added.begin(), added.end()); + _retained.insert(_retained.end(), added.begin(), added.end()); + // The revision held is of the view without them: a selection taken before the next reply would name it. + ++_retainStamp; + _viewRevision.clear(); + refetch(added); + return RetainResult::Retained; +} + +void WindowRows::clearRetained() { + if (_retained.empty()) { + return; + } + _retained.clear(); + _retainedSet.clear(); + _unmatched.clear(); + _unmatchedHeld.clear(); + ++_retainStamp; + _viewRevision.clear(); + _window.invalidate(); + pump(); + status(); +} + +void WindowRows::holdRefetches(std::uint64_t run) { + auto* const scheduler = _session->options().scheduler; + if (scheduler == nullptr) { + return; + } + if (_holding.empty()) { + _holdTimer = scheduler->after(_session->options().retainHold, _scope.token().guard([this] { + _holdTimer = {}; + _holding.clear(); + flushMarked(); + })); + } + _holding.insert(run); +} + +void WindowRows::releaseRefetches(std::uint64_t run) { + if (_holding.erase(run) == 0 || !_holding.empty()) { + return; + } + _holdTimer = {}; + flushMarked(); +} + +std::expected WindowRows::selectView() const { + auto const shown = counts(); + std::vector levels; + if (_description) { + std::vector filtered; + for (auto const& [column, entry] : _filter.columns) { + static_cast(entry); + filtered.push_back(column); + } + for (table::GroupFilter const& group : _filter.groups) { + filtered.insert(filtered.end(), group.columns.begin(), group.columns.end()); + for (table::ColumnGroupInfo const& declared : _description->groups) { + if (!group.group.empty() && declared.id == group.group) { + filtered.insert(filtered.end(), declared.columns.begin(), declared.columns.end()); + } + } + } + for (table::TableColumn const& column : _description->columns) { + if (!column.info.level.empty() && std::ranges::contains(filtered, column.info.id) && + std::ranges::contains(shown.awaiting, column.info.level) && + !std::ranges::contains(levels, column.info.level)) { + levels.push_back(column.info.level); + } + } + } + if (shown.undecided > 0 || !levels.empty() || _viewRevision.empty()) { + return std::unexpected(SelectAllRefusal{.undecided = shown.undecided, .levels = std::move(levels)}); + } + return ViewSelection{.filters = _filter, .retained = _retained, .revision = _viewRevision}; +} + +SelectedCount WindowRows::selectedCount(TableSelection const& selection) const { + if (!selection.view) { + return SelectedCount{.rows = static_cast(selection.keys.size()), .kind = CountKind::Exact}; + } + auto const view = total(); + std::unordered_set held; + for (auto const& [first, count] : heldRanges()) { + for (std::int64_t at = first; at < first + count; ++at) { + if (auto const* const key = _window.key(at)) { + held.insert(*key); + } + } + } + std::unordered_set owed; + for (RowsFlight const& flight : _rowsFlights) { + owed.insert(flight.fetch.keys.begin(), flight.fetch.keys.end()); + } + bool exact = view.known && view.kind == table::TotalKind::Exact; + std::int64_t rows = view.rows; + for (table::RowId const& key : selection.except) { + if (held.contains(key)) { + --rows; + exact = exact && !owed.contains(key); + } else { + exact = exact && _outOfView.contains(key); + } + } + return SelectedCount{.rows = std::max(rows, 0), + .kind = exact ? CountKind::Exact : CountKind::Approximate}; +} + +async::Completion, table::TableError>> WindowRows::rowsOf( + std::int64_t first, std::int64_t count, std::span columns) { + using Result = std::expected, table::TableError>; + auto [completion, promise] = async::Completion::makeSettleable(&_session->runtime().owner()); + auto state = std::make_shared( + RowsRequest{.promise = std::move(promise), .rows = {}, .waiting = 0, .failed = std::nullopt, .stops = {}}); + if (!_description || first < 0 || count <= 0) { + if (!_description) { + state->failed = unavailable(); + } + finishRows(*state); + return std::move(completion); + } + auto const size = std::max(_options.pageSize, 1); + auto const named = std::make_shared const>(columns.begin(), columns.end()); + std::vector offsets; + for (std::int64_t offset = first; offset < first + count; offset += size) { + offsets.push_back(offset); + } + state->waiting = offsets.size(); + std::erase_if(_rowsRequests, [](std::weak_ptr const& held) { return held.expired(); }); + _rowsRequests.push_back(state); + for (std::int64_t const offset : offsets) { + table::TableQuery query = + queryOf(table::PageRequest{.offset = offset, .limit = std::min(size, first + count - offset)}, {}); + query.columns = *named; + auto body = bodyOf(query); + if (!body) { + rowsAnswered(*state, std::unexpected(std::move(body.error()))); + continue; + } + ::core::async::StopSource stop; + auto reply = _session->read(_options.channel, actionName(), *body, stop.get_token()); + state->stops.push_back(std::move(stop)); + reply.then(_scope, [this, state, named](std::string const& text) { + if (!_description) { + rowsAnswered(*state, std::unexpected(unavailable())); + return; + } + auto read = _options.action.empty() ? table::readGenericPage(text, *_description, _units.get()) + : readTypedPage(text, *_description, _units.get()); + if (!read) { + rowsAnswered(*state, std::unexpected(std::move(read.error()))); + return; + } + // A page's rows are at its offset onward. + read->indices.clear(); + for (std::size_t at = 0; at < read->rows.size(); ++at) { + read->indices.push_back(read->offset + static_cast(at)); + } + rowsAnswered(*state, fetchedOf(*read, *named)); + }); + reply.onError(_scope, [state](std::exception_ptr const& error) { + if (!wasCancelled(error)) { + rowsAnswered(*state, std::unexpected(failureOf(error))); + } + }); + } + return std::move(completion); +} + +void WindowRows::keysAnswered(KeysRequest& request, std::int64_t page, + std::expected, table::TableError> keys) { + if (keys) { + request.pages.insert_or_assign(page, std::move(*keys)); + } else if (!request.failed) { + request.failed = std::move(keys.error()); + } + if (request.waiting > 0) { + --request.waiting; + if (request.waiting == 0) { + finishKeys(request); + } + } +} + +void WindowRows::finishKeys(KeysRequest& request) { + using Result = std::expected, table::TableError>; + if (request.failed) { + request.promise.resolve(Result{std::unexpected(*request.failed)}); + return; + } + auto const size = std::max(_options.pageSize, 1); + std::vector keys; + keys.reserve(static_cast(request.count)); + for (std::int64_t at = request.first; at < request.first + request.count; ++at) { + if (auto const page = request.pages.find(at / size); page != request.pages.end()) { + auto const place = static_cast(at - ((at / size) * size)); + if (place < page->second.size()) { + keys.push_back(page->second.at(place)); + continue; + } + } else if (auto const* const key = _window.key(at)) { + keys.push_back(*key); + continue; + } + request.promise.resolve( + Result{std::unexpected(table::TableError{.code = table::TableErrorCode::Unavailable, + .column = {}, + .message = std::format("view row {} is in no page", at)})}); + return; + } + request.promise.resolve(Result{std::move(keys)}); +} + +void WindowRows::rowsAnswered(RowsRequest& request, std::expected, table::TableError> rows) { + if (rows) { + request.rows.insert(request.rows.end(), std::make_move_iterator(rows->begin()), + std::make_move_iterator(rows->end())); + } else if (!request.failed) { + request.failed = std::move(rows.error()); + } + if (request.waiting > 0) { + --request.waiting; + if (request.waiting == 0) { + finishRows(request); + } + } +} + +void WindowRows::finishRows(RowsRequest& request) { + using Result = std::expected, table::TableError>; + if (request.failed) { + request.promise.resolve(Result{std::unexpected(*request.failed)}); + return; + } + request.promise.resolve(Result{std::move(request.rows)}); +} + +std::expected, table::TableError> WindowRows::fetchedOf( + table::GenericPage& page, std::vector const& columns) const { + if (!page.rows.empty() && page.indices.size() != page.rows.size()) { + return std::unexpected(table::TableError{.code = table::TableErrorCode::InvalidValue, + .column = {}, + .message = "the keyed reply gives its rows no index"}); + } + std::vector> places; + places.reserve(columns.size()); + for (std::string const& columnId : columns) { + auto const found = std::ranges::find(page.columns, columnId); + places.push_back(found == page.columns.end() + ? std::nullopt + : std::optional{static_cast(found - page.columns.begin())}); + } + std::vector out; + out.reserve(page.rows.size()); + for (std::size_t at = 0; at < page.rows.size() && at < page.keys.size(); ++at) { + auto const unloaded = + std::ranges::find(page.unloadedRows, static_cast(at), &table::UnloadedRow::index); + FetchedRow row{.key = std::move(page.keys.at(at)), .viewRow = page.indices.at(at), .cells = {}}; + row.cells.reserve(columns.size()); + for (std::size_t column = 0; column < columns.size(); ++column) { + std::optional const place = places.at(column); + table::GenericRow& cells = page.rows.at(at); + if (!place || *place >= cells.size()) { + row.cells.emplace_back(); + continue; + } + auto const info = _infos.find(columns.at(column)); + bool const missing = unloaded != page.unloadedRows.end() && info != _infos.end() && + !info->second.level.empty() && + std::ranges::contains(unloaded->levels, info->second.level); + row.cells.push_back(missing ? table::Cell{table::Unloaded{}} : std::move(cells.at(*place))); + } + out.push_back(std::move(row)); + } + return out; +} + +std::chrono::milliseconds WindowRows::now() const { + auto const& clock = _session->options().clock; + if (clock) { + return clock(); + } + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()); +} + +std::optional WindowRows::sortError(SortChain const& sort) const { + if (!_description) { + return unavailable(); + } + auto const error = [](table::TableErrorCode code, std::string column, std::string message) { + return table::TableError{.code = code, .column = std::move(column), .message = std::move(message)}; + }; + if (sort.size() > _description->capabilities.maxSortKeys) { + return error( + table::TableErrorCode::LimitExceeded, {}, + std::format("{} sort keys; the table takes {}", sort.size(), _description->capabilities.maxSortKeys)); + } + for (std::size_t at = 0; at < sort.size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < sort.size() by the loop + auto const& columnId = sort[at].column; + auto const column = + std::ranges::find(_description->columns, columnId, + [](table::TableColumn const& candidate) -> auto const& { return candidate.info.id; }); + if (column == _description->columns.end()) { + return error(table::TableErrorCode::UnknownColumn, columnId, "no column " + columnId); + } + if (!column->sortable) { + return error(table::TableErrorCode::InvalidSpec, columnId, "the column " + columnId + " is not sortable"); + } + if (std::ranges::contains(sort.begin(), sort.begin() + static_cast(at), columnId, + &table::SortKey::column)) { + return error(table::TableErrorCode::InvalidSpec, columnId, "the column " + columnId + " is sorted twice"); + } + } + return std::nullopt; +} + +void WindowRows::restart() { + stopAll(); + _window.reset(); + _memo.clear(); + _heldPages.clear(); + _unmatched.clear(); + _unmatchedHeld.clear(); + _retry = false; + _awaitedLast.reset(); + _awaitedTimer = {}; + announce(table::ViewChange{ + .ops = {table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}}}); + pump(); +} + +void WindowRows::stopAll() { + for (auto& flight : _pageFlights) { + flight.stop.request_stop(); + } + for (auto& flight : _rowsFlights) { + flight.stop.request_stop(); + } + _pageFlights.clear(); + _rowsFlights.clear(); +} + +bool WindowRows::heldPage(std::int64_t page) const { + auto const size = std::max(_options.pageSize, 1); + return page >= 0 && _window.key(page * size) != nullptr; +} + +bool WindowRows::due(table::PageFetch const& fetch, std::chrono::milliseconds instant) const { + if (_session->options().scheduler == nullptr) { + return true; + } + auto const page = fetch.request.offset / std::max(_options.pageSize, 1); + if (heldPage(page) || heldPage(page - 1) || heldPage(page + 1)) { + return true; + } + if (_window.pagesHeld() == 0 && page == _anchor) { + return true; + } + return instant - _anchorSince >= _session->options().tableSettle; +} + +bool WindowRows::spaced(std::chrono::milliseconds instant) const { + return !_window.awaiting().empty() && _session->options().scheduler != nullptr && _awaitedLast && + instant - *_awaitedLast < _session->options().tableAwaitedRefetch; +} + +void WindowRows::pump() { + if (!ready()) { + return; + } + auto fetches = _window.visible(_first, _count, _columns); + for (auto const& superseded : _window.superseded()) { + auto const flight = std::ranges::find(_pageFlights, superseded, &PageFlight::fetch); + if (flight != _pageFlights.end()) { + flight->stop.request_stop(); + _pageFlights.erase(flight); + } + _window.cancelled(superseded); + ++_stats.cancelled; + } + auto const instant = now(); + auto const size = std::max(_options.pageSize, 1); + bool settling = false; + bool spacing = false; + bool refetched = false; + for (auto const& fetch : fetches) { + bool const refetch = heldPage(fetch.request.offset / size); + if (refetch && spaced(instant)) { + _window.cancelled(fetch); + spacing = true; + } else if (due(fetch, instant)) { + refetched = refetched || refetch; + send(fetch); + } else { + _window.cancelled(fetch); + settling = true; + } + } + if (refetched && !_window.awaiting().empty()) { + _awaitedLast = instant; + } + // A retry's fetches carry the flag until the last of them, held back or not, has gone. + if (!settling && !spacing) { + _retry = false; + } + auto* const scheduler = _session->options().scheduler; + if (settling) { + auto const wait = _anchorSince + _session->options().tableSettle - instant; + _settleTimer = scheduler->after(std::max(wait, std::chrono::milliseconds{1}), _scope.token().guard([this] { + _settleTimer = {}; + pump(); + })); + } + if (spacing && _awaitedLast && !_awaitedTimer.active()) { + auto const wait = *_awaitedLast + _session->options().tableAwaitedRefetch - instant; + _awaitedTimer = scheduler->after(std::max(wait, std::chrono::milliseconds{1}), _scope.token().guard([this] { + _awaitedTimer = {}; + pump(); + })); + } +} + +std::expected WindowRows::bodyOf(table::TableQuery const& query) const { + auto const invalid = [](std::string message) { + return std::unexpected(table::TableError{ + .code = table::TableErrorCode::InvalidValue, .column = {}, .message = std::move(message)}); + }; + auto const text = glz::write_json(query); + if (!text) { + return invalid("the query does not write"); + } + auto const json = parseJson(*text); + if (!json) { + return invalid(json.error()); + } + auto const value = valueFromJson(*json); + if (!value || value->asRecord() == nullptr) { + return invalid(value ? std::string{"the query is not a record"} : value.error()); + } + ValueRecord body; + if (auto const* const fixed = _options.body.asRecord()) { + body = *fixed; + } + std::string const member = _options.action.empty() ? std::string{"query"} : _options.queryMember; + ValueRecord members; + if (auto const found = body.find(member); found != body.end() && found->second.asRecord() != nullptr) { + members = *found->second.asRecord(); + } + for (auto const& [name, field] : *value->asRecord()) { + members.insert_or_assign(name, field); + } + body.insert_or_assign(member, Value{std::move(members)}); + return Value{std::move(body)}; +} + +table::TableQuery WindowRows::queryOf(table::PageRequest page, std::vector const& columns) const { + table::TableQuery query; + query.sort = _sort; + query.filters = _filter; + query.page = page; + if (!columns.empty()) { + query.columns = columns; + } + query.retry = _retry; + query.retain = _retained; + return query; +} + +void WindowRows::send(table::PageFetch const& fetch) { + auto body = bodyOf(queryOf(fetch.request, fetch.columns)); + if (!body) { + _window.fail(fetch, body.error()); + _error = std::move(body.error()); + return; + } + ::core::async::StopSource stop; + ++_stats.pageFetches; + auto reply = _session->read(_options.channel, actionName(), *body, stop.get_token()); + _pageFlights.push_back(PageFlight{.fetch = fetch, .stop = std::move(stop), .retained = _retainStamp}); + reply.then(_scope, [this, fetch](std::string const& text) { pageArrived(fetch, text); }); + reply.onError(_scope, [this, fetch](std::exception_ptr const& error) { pageFailed(fetch, error); }); + status(); +} + +void WindowRows::send(table::RowsFetch const& fetch) { + auto query = queryOf(table::PageRequest{}, fetch.columns); + query.keys = fetch.keys; + auto body = bodyOf(query); + if (!body) { + keyedFailed(std::move(body.error())); + return; + } + ::core::async::StopSource stop; + ++_stats.rowsFetches; + auto reply = _session->read(_options.channel, actionName(), *body, stop.get_token()); + _rowsFlights.push_back(RowsFlight{.fetch = fetch, .stop = std::move(stop), .retained = _retainStamp}); + reply.then(_scope, [this, fetch](std::string const& text) { rowsArrived(fetch, text); }); + reply.onError(_scope, [this, fetch](std::exception_ptr const& error) { rowsFailed(fetch, error); }); + status(); +} + +void WindowRows::answered() { + if (_unanswered > 0) { + --_unanswered; + if (_unanswered == 0) { + _watched = true; + pump(); + } + } +} + +std::expected WindowRows::decode(std::string const& text) { + if (!_description) { + return std::unexpected(unavailable()); + } + // Held by reference: the helpers below change the description in place and never replace it. + table::TableDescription& description = *_description; + if (_options.action.empty()) { + return table::readGenericPage(text, description, _units.get()); + } + auto dom = detail::typedPageDom(text); + if (!dom) { + return std::unexpected(std::move(dom.error())); + } + if (!_inferring || dom->rows.empty()) { + listUnits(dom->rows); + return detail::typedPageOf(*dom, description, _units.get()); + } + // The kinds are fixed only by a reply that reads: one that does not leaves them to the next. + auto const before = description.columns; + inferKinds(dom->rows); + listUnits(dom->rows); + auto page = detail::typedPageOf(*dom, description, _units.get()); + if (!page) { + description.columns = before; + for (auto const& column : before) { + _infos.insert_or_assign(column.info.id, column.info); + } + ++_columnsStamp; + return page; + } + _inferring = false; + if (_onInferred) { + _onInferred(); + } + return page; +} + +void WindowRows::listUnits(std::span rows) { + if (!_description) { + return; + } + auto const added = detail::unlistedUnits( + rows, *_description, _units.get(), detail::kMaxUnlistedUnits - std::min(_unlisted, detail::kMaxUnlistedUnits)); + if (added.empty()) { + return; + } + _unlisted += added.size(); + _description->units.insert(_description->units.end(), added.begin(), added.end()); + auto registry = table::registryOf(*_description); + _units = registry ? std::move(*registry) : nullptr; + _memo.clear(); + ++_columnsStamp; +} + +void WindowRows::inferKinds(std::span rows) { + if (!_description) { + return; + } + for (auto& column : _description->columns) { + if (std::ranges::contains(_options.inferKinds, column.info.id)) { + column.info.kind = detail::inferredJsonKind(rows, column.info.id); + _infos.insert_or_assign(column.info.id, column.info); + } + } + auto registry = table::registryOf(*_description); + _units = registry ? std::move(*registry) : nullptr; + _memo.clear(); + ++_columnsStamp; +} + +bool WindowRows::wasCancelled(std::exception_ptr const& error) { + try { + std::rethrow_exception(error); + } catch (::core::async::OperationCancelled const&) { + return true; + } catch (...) { + return false; + } +} + +table::TableError WindowRows::failureOf(std::exception_ptr const& error) { + return table::TableError{ + .code = table::TableErrorCode::Unavailable, .column = {}, .message = ui::detail::failureText(error)}; +} + +table::TableError WindowRows::unavailable() { + return table::TableError{.code = table::TableErrorCode::Unavailable, .column = {}, .message = "no description"}; +} + +void WindowRows::heardRevision(std::string const& revision) { + if (_description && revision != _description->revision && _staleRevisions.insert(revision).second && _onStale) { + _onStale(); + } +} + +std::vector> WindowRows::slotsOfPage(std::int64_t page) const { + auto const size = std::max(_options.pageSize, 1); + std::vector> out; + out.reserve(static_cast(size)); + for (std::int64_t at = page * size; at < (page + 1) * size; ++at) { + auto const* const key = _window.key(at); + out.push_back(key == nullptr ? std::nullopt : std::optional{*key}); + } + return out; +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity,bugprone-easily-swappable-parameters): page, count +table::ViewChange WindowRows::pageChange(std::int64_t page, std::int64_t rowsBefore, + std::vector> const& before, + std::set const& heldBefore) const { + using table::ViewOp; + auto const reset = [] { + return table::ViewChange{.ops = {ViewOp{.kind = ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}}}; + }; + auto const size = std::max(_options.pageSize, 1); + auto const rowsAfter = shownRows(); + auto const start = page * size; + auto const after = slotsOfPage(page); + table::ViewChange change; + if (rowsAfter < rowsBefore) { + change.ops.push_back(ViewOp{.kind = ViewOp::Kind::Removed, + .first = static_cast(rowsAfter), + .count = static_cast(rowsBefore - rowsAfter), + .to = 0}); + } + auto const places = + static_cast(std::clamp(std::min(rowsBefore, rowsAfter) - start, 0, size)); + std::unordered_map wasAt; + std::unordered_map nowAt; + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < places <= slots' size + for (std::size_t at = 0; at < places; ++at) { + auto const& previous = before[at]; + auto const& current = after[at]; + bool const unique = + (!previous || wasAt.emplace(*previous, at).second) && (!current || nowAt.emplace(*current, at).second); + if (!unique) { + return reset(); + } + } + // Identities: each key one number; each place's own empty slot one number after every key's. + std::unordered_map ids; + auto const idOf = [&ids](table::RowId const& key) { + return ids.try_emplace(key, static_cast(ids.size())).first->second; + }; + std::vector changed; + for (std::size_t at = 0; at < places; ++at) { + if (auto const& previous = before[at]) { + idOf(*previous); + } + if (auto const& current = after[at]) { + changed.push_back(idOf(*current)); + } + } + auto const emptyBase = static_cast(ids.size()); + auto const emptyAt = [emptyBase](std::size_t index) { return emptyBase + static_cast(index); }; + std::vector was(places); + std::vector now(places); + for (std::size_t at = 0; at < places; ++at) { + auto const& previous = before[at]; + auto const& current = after[at]; + if (previous) { + was[at] = ids.at(*previous); + } else if (current && !wasAt.contains(*current)) { + was[at] = ids.at(*current); + } else { + was[at] = emptyAt(at); + } + if (current) { + now[at] = ids.at(*current); + } else if (previous && !nowAt.contains(*previous)) { + now[at] = ids.at(*previous); + } else { + now[at] = emptyAt(at); + } + } + // NOLINTEND(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) + auto inPage = table::diffViews(was, now, changed, static_cast(emptyBase) + places, kResetThreshold); + if (inPage.isReset()) { + return inPage; + } + for (auto op : inPage.ops) { + op.first += static_cast(start); + if (op.kind == ViewOp::Kind::Moved) { + op.to += static_cast(start); + } + change.ops.push_back(op); + } + if (rowsAfter > rowsBefore) { + change.ops.push_back(ViewOp{.kind = ViewOp::Kind::Inserted, + .first = static_cast(rowsBefore), + .count = static_cast(rowsAfter - rowsBefore), + .to = 0}); + } + for (auto const held : heldBefore) { + if (held == page || heldPage(held)) { + continue; + } + auto const first = held * size; + auto const last = std::min(first + size, rowsAfter); + if (first < last) { + change.ops.push_back(ViewOp{.kind = ViewOp::Kind::Changed, + .first = static_cast(first), + .count = static_cast(last - first), + .to = 0}); + } + } + return change; +} + +void WindowRows::pageArrived(table::PageFetch const& fetch, std::string const& text) { + auto const flight = std::ranges::find(_pageFlights, fetch, &PageFlight::fetch); + std::uint64_t const stamp = flight == _pageFlights.end() ? 0 : flight->retained; + std::erase_if(_pageFlights, [&fetch](PageFlight const& other) { return other.fetch == fetch; }); + if (!_description) { + return; + } + auto page = decode(text); + if (!page) { + _window.fail(fetch, page.error()); + _error = std::move(page.error()); + status(); + return; + } + heardRevision(page->revision); + if (fetch.query == _window.query()) { + // A reply to a query of another retained set names that set's view, and its rows' marks are of that set. + if (stamp == _retainStamp) { + if (!page->viewRevision.empty()) { + _viewRevision = page->viewRevision; + } + heardUnmatched(*page); + } + for (table::RowId const& key : page->keys) { + _outOfView.erase(key); + } + } + auto const size = std::max(_options.pageSize, 1); + auto const index = fetch.request.offset / size; + auto const before = slotsOfPage(index); + auto const rowsBefore = shownRows(); + if (_window.accept(fetch, std::move(*page))) { + _error.reset(); + auto const change = pageChange(index, rowsBefore, before, _heldPages); + for (auto const& slot : before) { + if (slot) { + _memo.erase(*slot); + } + } + for (auto const& slot : slotsOfPage(index)) { + if (slot) { + _memo.erase(*slot); + } + } + std::erase_if(_heldPages, [this](std::int64_t held) { return !heldPage(held); }); + if (heldPage(index)) { + _heldPages.insert(index); + } + heldUnmatched(); + announce(change); + } + planned(_window.owed()); + pump(); + status(); +} + +void WindowRows::pageFailed(table::PageFetch const& fetch, std::exception_ptr const& error) { + std::erase_if(_pageFlights, [&fetch](PageFlight const& other) { return other.fetch == fetch; }); + if (wasCancelled(error)) { + return; + } + auto failure = failureOf(error); + _window.fail(fetch, failure); + _error = std::move(failure); + status(); +} + +void WindowRows::rowsArrived(table::RowsFetch const& fetch, std::string const& text) { + auto const flight = std::ranges::find(_rowsFlights, fetch, &RowsFlight::fetch); + std::uint64_t const stamp = flight == _rowsFlights.end() ? 0 : flight->retained; + std::erase_if(_rowsFlights, [&fetch](RowsFlight const& other) { return other.fetch == fetch; }); + if (!_description) { + return; + } + auto page = decode(text); + if (!page) { + keyedFailed(std::move(page.error())); + return; + } + heardRevision(page->revision); + // Only a reply under the query the window holds says a row left: under another, the key may be in the view. + std::vector absent; + if (fetch.query == _window.query()) { + if (stamp == _retainStamp) { + if (!page->viewRevision.empty()) { + _viewRevision = page->viewRevision; + } + heardUnmatched(*page); + } + std::unordered_set const answered(page->keys.begin(), page->keys.end()); + for (table::RowId const& key : fetch.keys) { + if (answered.contains(key)) { + _outOfView.erase(key); + } else { + _outOfView.insert(key); + absent.push_back(key); + } + } + } + auto const revision = _window.revision(); + auto const replaced = _window.patch(fetch, std::move(*page)); + heldUnmatched(); + table::ViewChange change; + for (auto const index : replaced) { + if (auto const* const key = _window.key(index)) { + _memo.erase(*key); + } + auto const row = static_cast(index); + if (!change.ops.empty() && change.ops.back().first + change.ops.back().count == row) { + ++change.ops.back().count; + } else { + change.ops.push_back( + table::ViewOp{.kind = table::ViewOp::Kind::Changed, .first = row, .count = 1, .to = 0}); + } + } + announce(change); + if (!absent.empty() && _onRowsAbsent) { + std::function)> const heard = _onRowsAbsent; + heard(absent); + } + if (_window.revision() != revision) { + pump(); + } + status(); +} + +void WindowRows::rowsFailed(table::RowsFetch const& fetch, std::exception_ptr const& error) { + std::erase_if(_rowsFlights, [&fetch](RowsFlight const& other) { return other.fetch == fetch; }); + if (wasCancelled(error)) { + return; + } + keyedFailed(failureOf(error)); +} + +void WindowRows::keyedFailed(table::TableError error) { + _error = std::move(error); + _window.invalidate(); + pump(); + status(); +} + +void WindowRows::planned(table::RefreshPlan const& plan) { + if (plan.kind == table::Refresh::Rows) { + send(plan.rows); + } else if (plan.kind == table::Refresh::Pages) { + pump(); + } +} + +void WindowRows::keepDistinct(std::string const& key, table::DistinctValues const& values) { + if (!_distinct.contains(key)) { + _distinctOrder.push_back(key); + } + _distinct.insert_or_assign(key, values); + while (_distinctOrder.size() > kMaxDistinctReplies) { + _distinct.erase(_distinctOrder.front()); + _distinctOrder.pop_front(); + } +} + +void WindowRows::forgetDistinct() { + _distinct.clear(); + _distinctOrder.clear(); + ++_distinctEpoch; +} + +void WindowRows::heard(effects::RecordChange const& change) { + // Any row may change a count: the values lists are asked again. + forgetDistinct(); + std::optional> keys; + if (change.keys) { + keys.emplace(); + keys->reserve(change.keys->size()); + for (auto const& raw : *change.keys) { + auto key = table::rowIdOf(raw); + if (!key) { + keys.reset(); + break; + } + keys->push_back(std::move(*key)); + } + } + // A change of a row ends its failed mark. An action's own event names the rows it changed and not those it + // could not, so it leaves their marks; an event without keys names no row and ends none. + if (keys && !_states.failedKeys().empty()) { + auto const marked = _states.failedKeys().size(); + _states.clearFailed(*keys); + if (_states.failedKeys().size() != marked) { + status(); + } + } + // While a run holds the refetches, the event only marks what it would fetch. + if (!_holding.empty()) { + if (keys) { + _marked.insert(_marked.end(), keys->begin(), keys->end()); + } else { + _markedAll = true; + } + return; + } + if (!keys) { + _window.invalidate(); + pump(); + return; + } + planned(_window.refresh(*keys)); +} + +void WindowRows::refetch(std::vector const& keys) { + if (!_holding.empty()) { + _marked.insert(_marked.end(), keys.begin(), keys.end()); + return; + } + auto plan = _window.refresh(keys); + // A window that holds no row has no keyed fetch to make: its pages are fetched again. + if (plan.kind == table::Refresh::Nothing) { + _window.invalidate(); + pump(); + return; + } + planned(plan); +} + +void WindowRows::flushMarked() { + bool const all = std::exchange(_markedAll, false); + auto keys = std::move(_marked); + _marked.clear(); + if (all) { + _window.invalidate(); + pump(); + } else if (!keys.empty()) { + std::ranges::sort(keys); + auto const [first, last] = std::ranges::unique(keys); + keys.erase(first, last); + refetch(keys); + } +} + +void WindowRows::heardUnmatched(table::GenericPage const& page) { + for (std::size_t at = 0; at < page.keys.size(); ++at) { + if (std::ranges::binary_search(page.unmatched, static_cast(at))) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < page.keys.size() by the loop + _unmatched.insert(page.keys[at]); + } else { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): at < page.keys.size() by the loop + _unmatched.erase(page.keys[at]); + } + } +} + +void WindowRows::heldUnmatched() { + _unmatchedHeld.clear(); + if (_unmatched.empty()) { + return; + } + for (auto const& [first, count] : heldRanges()) { + for (std::int64_t at = first; at < first + count; ++at) { + if (auto const* const key = _window.key(at); key != nullptr && _unmatched.contains(*key)) { + _unmatchedHeld.insert(*key); + } + } + } +} + +void WindowRows::status() const { + if (_onStatus) { + _onStatus(); + } +} + +void WindowRows::announce(table::ViewChange const& change) { + if (change.empty()) { + return; + } + // Records of rows no longer held are not looked up again; past the window's own bound they are dropped. + if (_memo.size() > _options.maxPages * static_cast(std::max(_options.pageSize, 1))) { + _memo.clear(); + } + if (_onChange) { + _onChange(change); + } +} + +} // namespace morph::ui diff --git a/src/ui/table_state.cpp b/src/ui/table_state.cpp new file mode 100644 index 000000000..74f0d2b72 --- /dev/null +++ b/src/ui/table_state.cpp @@ -0,0 +1,451 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +void PreferencesTableStateStore::retryOn(reactive::Scheduler& scheduler, std::chrono::milliseconds retryDelay) { + _scheduler = &scheduler; + _retryDelay = retryDelay; +} + +async::Completion> PreferencesTableStateStore::load( + table::TableStateKey const& key) { + auto [completion, promise] = async::Completion>::makeSettleable(_owner); + queue(std::make_shared(Reading{.key = key, .promise = std::move(promise)})); + return std::move(completion); +} + +async::Completion PreferencesTableStateStore::save(table::TableStateKey const& key, + std::string json, std::string expected) { + auto [completion, promise] = async::Completion::makeSettleable(_owner); + auto upload = std::make_shared(Upload{.key = key, + .expected = std::move(expected), + .id = {}, + .text = std::move(json), + .offset = 0, + .promise = std::move(promise), + .retries = 0}); + if (upload->text.size() > kPartBytes) { + upload->id = std::format("{:016x}", _random()); + } + sendPart(upload); + return std::move(completion); +} + +async::Completion PreferencesTableStateStore::remove(table::TableStateKey const& key) { + auto [completion, promise] = async::Completion::makeSettleable(_owner); + auto const settle = std::make_shared::Promise>(std::move(promise)); + channel() + ->execute("remove", model::ActionTraits::toJson(TableStateRemove{.key = key}), CallOptions{}) + .then(_scope, + [settle](std::string const& reply) { + try { + settle->resolve(model::ActionTraits::resultFromJson(reply).removed); + } catch (...) { + settle->reject(std::current_exception()); + } + }) + .onError(_scope, [settle](std::exception_ptr const& error) { settle->reject(error); }); + return std::move(completion); +} + +async::Completion PreferencesTableStateStore::publish(table::TableStateKey const& key, + table::ViewOperation const& operation, + std::string expected) { + auto [completion, promise] = async::Completion::makeSettleable(_owner); + auto const settle = std::make_shared::Promise>(std::move(promise)); + TableStatePublish const request{ + .key = key, .operation = table::writeViewOperation(operation), .expected = std::move(expected)}; + channel() + ->execute("publish", model::ActionTraits::toJson(request), CallOptions{}) + .then(_scope, + [settle](std::string const& reply) { + try { + settle->resolve(model::ActionTraits::resultFromJson(reply).result); + } catch (...) { + settle->reject(std::current_exception()); + } + }) + .onError(_scope, [settle](std::exception_ptr const& error) { settle->reject(error); }); + return std::move(completion); +} + +std::shared_ptr const& PreferencesTableStateStore::channel() { + if (_channel == nullptr) { + _channel = _dispatcher->bind(std::string{kTableStateModel}, bridge::BindSharing::Private, {}); + } + return _channel; +} + +void PreferencesTableStateStore::queue(std::shared_ptr reading) { + _batch.push_back(std::move(reading)); + if (_batch.size() == 1) { + _owner->post(_scope.token().guard([this] { flushLoads(); })); + } +} + +void PreferencesTableStateStore::flushLoads() { + std::vector> all = std::move(_batch); + _batch.clear(); + for (std::size_t first = 0; first < all.size(); first += kMaxTableStateKeys) { + auto const last = std::min(all.size(), first + kMaxTableStateKeys); + sendLoads(std::make_shared>>( + all.begin() + static_cast(first), all.begin() + static_cast(last))); + } +} + +void PreferencesTableStateStore::sendLoads(std::shared_ptr>> const& batch) { + TableStateLoad request; + for (auto const& reading : *batch) { + request.keys.push_back(reading->key); + } + channel() + ->execute("load", model::ActionTraits::toJson(request), CallOptions{}) + .then(_scope, + [this, batch](std::string const& reply) { + TableStateLoaded loaded; + try { + loaded = model::ActionTraits::resultFromJson(reply); + if (loaded.entries.size() != batch->size()) { + throw std::runtime_error{"a table-state load answered " + + std::to_string(loaded.entries.size()) + " entries for " + + std::to_string(batch->size()) + " keys"}; + } + } catch (...) { + for (auto const& reading : *batch) { + reading->promise.reject(std::current_exception()); + } + return; + } + for (std::size_t at = 0; at < batch->size(); ++at) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): loaded.entries.size() == batch->size(), checked above + start((*batch)[at], std::move(loaded.entries[at])); + } + }) + .onError(_scope, [batch](std::exception_ptr const& error) { + for (auto const& reading : *batch) { + reading->promise.reject(error); + } + }); +} + +void PreferencesTableStateStore::start(std::shared_ptr const& reading, TableStateHead head) { + if (head.deferred) { + queue(reading); // the reply was full: asked for again in the next call + return; + } + if (!head.error.empty()) { + reading->promise.reject(std::make_exception_ptr(std::runtime_error{head.error})); + return; + } + if (!head.found) { + reading->promise.resolve(std::nullopt); + return; + } + reading->revision = std::move(head.revision); + reading->size = head.size; + reading->text = std::move(head.text); + readMore(reading); +} + +void PreferencesTableStateStore::readMore(std::shared_ptr const& reading) { + if (reading->text.size() >= reading->size) { + reading->promise.resolve( + table::StoredTableState{.json = std::move(reading->text), .revision = std::move(reading->revision)}); + return; + } + TableStateRead const request{.key = reading->key, .revision = reading->revision, .offset = reading->text.size()}; + channel() + ->execute("read", model::ActionTraits::toJson(request), CallOptions{}) + .then(_scope, + [this, reading](std::string const& reply) { + TableStateChunk chunk; + try { + chunk = model::ActionTraits::resultFromJson(reply); + } catch (...) { + reading->promise.reject(std::current_exception()); + return; + } + if (chunk.revision != reading->revision) { + if (++reading->restarts > kMaxRestarts) { + reading->promise.reject(std::make_exception_ptr( + std::runtime_error{"a table's state kept changing while it was read"})); + return; + } + reading->text.clear(); + queue(reading); + return; + } + if (chunk.text.empty()) { + reading->promise.reject( + std::make_exception_ptr(std::runtime_error{"a table's state ended before its size"})); + return; + } + reading->text += chunk.text; + readMore(reading); + }) + .onError(_scope, [reading](std::exception_ptr const& error) { reading->promise.reject(error); }); +} // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the function object owns the callable it heap-allocates for the capture. + +void PreferencesTableStateStore::retryLater(std::shared_ptr const& upload) { + auto send = _scope.token().guard([this, upload] { sendPart(upload); }); + if (_scheduler == nullptr) { + _owner->post(std::move(send)); + return; + } + std::uint64_t const token = ++_lastRetry; + _retries.insert_or_assign(token, _scheduler->after(_retryDelay, _scope.token().guard([this, token, send] mutable { + _retries.erase(token); + send(); + }))); +} + +void PreferencesTableStateStore::sendPart(std::shared_ptr const& upload) { + std::string_view const rest = std::string_view{upload->text}.substr(upload->offset); + std::size_t const length = upload->id.empty() ? rest.size() : detail::utf8Prefix(rest, kPartBytes); + TableStateSave const request{.key = upload->key, + .expected = upload->expected, + .upload = upload->id, + .offset = upload->offset, + .text = std::string{rest.substr(0, length)}, + .last = length == rest.size()}; + channel() + ->execute("save", model::ActionTraits::toJson(request), CallOptions{}) + .then(_scope, + [this, upload, length, last = request.last](std::string const& reply) { + table::SaveResult result; + try { + result = model::ActionTraits::resultFromJson(reply).result; + } catch (...) { + upload->promise.reject(std::current_exception()); + return; + } + if (upload->offset == 0 && result.outcome == table::SaveOutcome::Refused && + result.reason == kTableStateUploadsBusy && upload->retries < kMaxUploadRetries) { + ++upload->retries; + retryLater(upload); + return; + } + if (last) { + upload->promise.resolve(std::move(result)); + return; + } + upload->offset += length; + sendPart(upload); + }) + .onError(_scope, [upload](std::exception_ptr const& error) { upload->promise.reject(error); }); +} // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the function object owns the callable it heap-allocates for the capture. + +TableStates::TableStates(std::shared_ptr store, exec::IExecutor& owner MORPH_LIFETIMEBOUND, + reactive::Scheduler* scheduler, std::chrono::milliseconds debounce) + : _store{std::move(store)}, _owner{&owner}, _scheduler{scheduler}, _debounce{debounce} { + if (_store == nullptr) { + throw std::invalid_argument{"TableStates: a null store"}; + } +} + +std::optional TableStates::kept(table::TableStateKey const& key) const { + auto const found = _entries.find(tie(key)); + return found == _entries.end() ? std::nullopt : found->second.kept; +} + +async::Completion> TableStates::load(table::TableStateKey const& key) { + auto [completion, promise] = async::Completion>::makeSettleable(_owner); + Entry& entry = _entries[tie(key)]; + if (entry.known) { + promise.resolve(entry.kept); + return std::move(completion); + } + entry.waiters.push_back(std::move(promise)); + if (!entry.loading) { + startLoad(key, entry); + } + return std::move(completion); +} + +void TableStates::changed(table::TableStateKey const& key, table::StateDocument const& document, StateParts parts) { + Entry& entry = _entries[tie(key)]; + if (entry.settled) { + take(entry.current, document, parts); + } else { + take(entry.held, document, parts); + entry.heldParts = entry.heldParts | parts; + if (entry.known && !entry.loading) { + settle(entry, entry.kept); + } else if (!entry.loading) { + startLoad(key, entry); + } + } + entry.dirty = true; + if (_scheduler == nullptr) { + trySave(key); + return; + } + entry.timer = _scheduler->after(_debounce, _scope.token().guard([this, key] { trySave(key); })); +} + +void TableStates::start(table::TableStateKey const& key, table::StateDocument document) { + auto const found = _entries.find(tie(key)); + if (found == _entries.end() || !found->second.settled || found->second.dirty) { + return; + } + found->second.current = std::move(document); +} + +void TableStates::flush(table::TableStateKey const& key) { + auto const found = _entries.find(tie(key)); + if (found == _entries.end()) { + return; + } + found->second.timer.cancel(); + trySave(key); +} + +void TableStates::keep(table::TableStateKey const& key, table::StoredTableState state) { + Entry& entry = _entries[tie(key)]; + entry.kept = std::move(state); + entry.known = true; + if (!entry.settled && !entry.loading) { + settle(entry, entry.kept); + } +} + +void TableStates::take(table::StateDocument& into, table::StateDocument const& from, StateParts parts) { + if (holds(parts, StateParts::Layout)) { + into.layout = from.layout; + into.carried.columns = from.carried.columns; + into.carried.groups = from.carried.groups; + } + if (holds(parts, StateParts::Sort)) { + into.sort = from.sort; + into.carried.sort = from.carried.sort; + } + if (holds(parts, StateParts::Filters)) { + into.filters = from.filters; + into.carried.filters = from.carried.filters; + into.carried.groupFilters = from.carried.groupFilters; + } + if (holds(parts, StateParts::View)) { + into.view = from.view; + } +} + +void TableStates::startLoad(table::TableStateKey const& key, Entry& entry) { + entry.loading = true; + _store->load(key) + .then(_scope, [this, key](std::optional const& stored) { loaded(key, stored); }) + .onError(_scope, [this, key](std::exception_ptr const& error) { loadFailed(key, error); }); +} // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the function object owns the callable it heap-allocates for the capture. + +void TableStates::loaded(table::TableStateKey const& key, std::optional const& stored) { + Entry& entry = _entries[tie(key)]; + entry.loading = false; + bool const wasKnown = entry.known; + if (!wasKnown) { + entry.kept = stored; + entry.known = true; + } + if (!entry.settled || (entry.fromFailure && !wasKnown && !entry.dirty && !entry.saving)) { + settle(entry, entry.kept); + } + for (auto& waiter : std::exchange(entry.waiters, {})) { + waiter.resolve(entry.kept); + } + if (entry.dirty) { + trySave(key); + } +} + +void TableStates::loadFailed(table::TableStateKey const& key, std::exception_ptr const& error) { + Entry& entry = _entries[tie(key)]; + entry.loading = false; + if (!entry.settled) { + settle(entry, std::nullopt); + entry.fromFailure = true; + } + for (auto& waiter : std::exchange(entry.waiters, {})) { + waiter.reject(error); + } + if (entry.dirty) { + trySave(key); + } +} + +void TableStates::settle(Entry& entry, std::optional const& stored) { + table::StateDocument base; + if (stored) { + if (auto read = table::readState(stored->json)) { + base = std::move(*read); + } + } + take(base, entry.held, entry.heldParts); + entry.current = std::move(base); + entry.held = {}; + entry.heldParts = {}; + entry.settled = true; + entry.fromFailure = false; +} + +void TableStates::trySave(table::TableStateKey const& key) { + auto const found = _entries.find(tie(key)); + if (found == _entries.end()) { + return; + } + Entry& entry = found->second; + if (!entry.settled || entry.saving || !entry.dirty || entry.timer.active()) { + return; + } + std::string const json = table::writeState(entry.current); + entry.dirty = false; + entry.saving = true; + _store->save(key, json) + .then(_scope, [this, key, json](table::SaveResult const& result) { saved(key, json, result); }) + .onError(_scope, [this, key](std::exception_ptr const& error) { + saved(key, {}, + table::SaveResult{ + .outcome = table::SaveOutcome::Refused, .revision = {}, .reason = detail::failureText(error)}); + }); +} // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks): the function object owns the callable it heap-allocates for the capture. + +void TableStates::saved(table::TableStateKey const& key, std::string const& json, table::SaveResult const& result) { + Entry& entry = _entries[tie(key)]; + entry.saving = false; + if (result.outcome == table::SaveOutcome::Saved) { + entry.kept = table::StoredTableState{.json = json, .revision = result.revision}; + entry.known = true; + } else if (_onSaveFailed) { + _onSaveFailed(key, result); + } + if (entry.dirty) { + trySave(key); + } +} + +} // namespace morph::ui diff --git a/src/ui/table_state_model.cpp b/src/ui/table_state_model.cpp new file mode 100644 index 000000000..2aa082bad --- /dev/null +++ b/src/ui/table_state_model.cpp @@ -0,0 +1,367 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui::detail { + +std::string sha256Hex(std::string_view text, std::size_t digits) { + std::string const digest = session::detail::sha256(text); + std::string out; + out.reserve(digits); + for (char const byte : digest) { + if (out.size() >= digits) { + break; + } + out += std::format("{:02x}", static_cast(byte)); + } + out.resize(std::min(out.size(), digits)); + return out; +} + +std::string tableStateScope(table::TableStateKey const& key) { + return std::string{kTableStateScopePrefix} + "." + + sha256Hex(key.model + "\x1F" + key.table + "\x1F" + key.qualifier, 32); +} + +std::string tableStateRevision(std::string const& previous, std::string_view document) { + std::string input = previous; + input += document; + return sha256Hex(input, 16); +} + +std::string quotedSegment(std::string_view text) { + std::string out; + out.reserve(text.size() + 2); + out += '"'; + for (char const each : text) { + auto const byte = static_cast(each); + switch (byte) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\b': + out += "\\b"; + break; + case '\f': + out += "\\f"; + break; + case '\n': + out += "\\n"; + break; + case '\r': + out += "\\r"; + break; + case '\t': + out += "\\t"; + break; + default: + if (byte < 0x20) { + out += std::format("\\u{:04x}", byte); + } else { + out += each; + } + } + } + out += '"'; + return out; +} + +std::size_t utf8Prefix(std::string_view text, std::size_t limit) noexcept { + if (text.size() <= limit) { + return text.size(); + } + std::size_t end = limit; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): end <= limit < text.size(), and the loop only lowers it + while (end > 0 && (static_cast(text[end]) & 0xC0U) == 0x80U && limit - end < 3) { + --end; + } + return end == 0 ? limit : end; +} + +std::uint64_t wireBytes(std::string_view text) noexcept { + std::uint64_t out = 0; + for (char const each : text) { + auto const byte = static_cast(each); + switch (escapedBytes(byte)) { + case 1: + out += 1; + break; + case 2: // a short escape: its backslash escaped again, and the escaped quote or backslash too + out += 2 + ((byte == '"' || byte == '\\') ? 2 : 1); + break; + default: // a six-byte unicode escape: its backslash escaped again + out += 7; + } + } + return out; +} + +TableStateLocks::Lease::~Lease() { + if (_locks != nullptr) { + _locks->release(_name); + } +} + +TableStateLocks::Acquire::~Acquire() { + bool handed = false; + { + std::scoped_lock const lock{_locks->_mutex}; + if (auto const held = _queued ? _locks->_held.find(_name) : _locks->_held.end(); held != _locks->_held.end()) { + std::erase(held->second, this); + } + handed = _handed; + } + if (handed) { + _locks->release(_name); + } +} + +bool TableStateLocks::Acquire::await_suspend(std::coroutine_handle<> awaiting) { + std::scoped_lock const lock{_locks->_mutex}; + // `find` then `emplace`, not `try_emplace`: the latter's already-present path, inlined here, makes GCC at + // -O3 report a `-Wstrict-overflow` inside the deque's destructor. + auto const held = _locks->_held.find(_name); + if (held == _locks->_held.end()) { + _locks->_held.emplace(_name, std::deque{}); + _handed = true; + return false; + } + _awaiting = awaiting; + _context = ::core::async::ResumeTarget::current(); + _queued = true; + held->second.push_back(this); + return true; +} + +TableStateLocks::Lease TableStateLocks::Acquire::await_resume() { + std::scoped_lock const lock{_locks->_mutex}; + _handed = false; // the lease owns the lock from here + return Lease{_locks, _name}; +} + +void TableStateLocks::release(std::string const& name) { + std::coroutine_handle<> next; + ::core::async::ResumeTarget context; + { + std::scoped_lock const lock{_mutex}; + auto const held = _held.find(name); + if (held == _held.end()) { + return; + } + if (held->second.empty()) { + _held.erase(held); + return; + } + Acquire* const waiter = held->second.front(); + held->second.pop_front(); + waiter->_queued = false; + waiter->_handed = true; + next = waiter->_awaiting; + context = waiter->_context; + } + if (context) { + context.submit(::core::async::ParkedWork{.resume = next, .abandon = {}}); + } else { + next.resume(); + } +} + +std::vector segmentText(std::string_view text, std::size_t segmentBytes) { + std::size_t const budget = segmentBytes - 2; // the quotes + std::vector out; + std::size_t start = 0; + std::size_t used = 0; + std::size_t cursor = 0; + while (cursor < text.size()) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): cursor < text.size() by the loop + auto const lead = static_cast(text[cursor]); + std::size_t const length = std::min(sequenceBytes(lead), text.size() - cursor); + std::size_t cost = 0; + for (std::size_t each = cursor; each < cursor + length; ++each) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): each < cursor + length <= text.size() + cost += escapedBytes(static_cast(text[each])); + } + if (used + cost > budget && cursor > start) { + out.push_back(quotedSegment(text.substr(start, cursor - start))); + start = cursor; + used = 0; + } + used += cost; + cursor += length; + } + if (start < text.size()) { + out.push_back(quotedSegment(text.substr(start))); + } + return out; +} + +} // namespace morph::ui::detail + +namespace morph::ui { + +TableStateModel::TableStateModel(std::shared_ptr store, TableStateOptions options, + std::shared_ptr shared) + : _store{std::move(store)}, + _options{std::move(options)}, + _shared{shared != nullptr ? std::move(shared) : std::make_shared()} { + if (_store == nullptr) { + throw std::invalid_argument{"TableStateModel: a null store"}; + } + if (_options.segmentBytes < 32 || _options.partBytes < 16 || _options.partBytes > kTableStatePartBytes) { + throw std::invalid_argument{"TableStateModel: segmentBytes is at least 32, and partBytes 16 to " + + std::to_string(kTableStatePartBytes)}; + } +} + +std::string TableStateModel::verifiedPerson() { + session::Context const* const session = session::current(); + return session == nullptr ? std::string{} : session->principal; +} + +std::string TableStateModel::signedInPerson() { + std::string person = verifiedPerson(); + if (person.empty()) { + throw std::runtime_error{"table state is stored for a signed-in person"}; + } + return person; +} + +std::optional TableStateModel::keyProblem(table::TableStateKey const& key) { + auto const check = [](std::string const& member, std::string_view name, + std::size_t least) -> std::optional { + if (member.size() < least || member.size() > kMaxTableStateNameBytes) { + return "a table-state key's `" + std::string{name} + "` is " + std::to_string(least) + " to " + + std::to_string(kMaxTableStateNameBytes) + " bytes"; + } + return std::nullopt; + }; + for (auto problem : + {check(key.application, "application", 1), check(key.model, "model", 0), check(key.table, "table", 1), + check(key.qualifier, "qualifier", 1), check(key.part, "part", 1)}) { + if (problem) { + return problem; + } + } + if (key.part.contains('.')) { + return std::string{"a table-state key's `part` holds no `.`"}; + } + return std::nullopt; +} + +void TableStateModel::checkKey(table::TableStateKey const& key) { + if (auto problem = keyProblem(key)) { + throw std::invalid_argument{*problem}; + } +} + +std::chrono::milliseconds TableStateModel::now() const { + if (_options.clock) { + return _options.clock(); + } + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()); +} + +std::optional TableStateModel::takePart(std::string const& person, TableStateSave& request) { + std::scoped_lock const lock{_shared->mutex}; + auto& uploads = _shared->uploads; + auto const instant = now(); + std::erase_if(uploads, [&](auto const& entry) { return instant - entry.second.touched > _options.uploadExpiry; }); + std::pair const uploadKey{person, request.upload}; + if (request.offset == 0) { + uploads.erase(uploadKey); + auto const open = + std::ranges::count_if(uploads, [&](auto const& entry) { return entry.first.first == person; }); + if (std::cmp_greater_equal(open, kMaxTableStateUploads)) { + throw detail::UploadsBusy{std::string{kTableStateUploadsBusy}}; + } + uploads.emplace(uploadKey, detail::TableStateShared::Upload{ + .key = request.key, .text = {}, .started = instant, .touched = instant}); + } + auto const found = uploads.find(uploadKey); + if (found == uploads.end() || !(found->second.key == request.key) || found->second.text.size() != request.offset) { + throw std::invalid_argument{"a table-state save part does not continue its upload"}; + } + if (_options.maxBytesPerPerson && request.offset + request.text.size() > *_options.maxBytesPerPerson) { + uploads.erase(found); + throw std::invalid_argument{"a table-state upload is over the table-state quota"}; + } + found->second.text += request.text; + found->second.touched = instant; + if (!request.last) { + return std::nullopt; + } + std::string text = std::move(found->second.text); + uploads.erase(found); + return text; +} + +PrefKey TableStateModel::pointKey(std::string const& person, table::TableStateKey const& key, std::string point) { + return PrefKey{ + .person = person, .app = key.application, .scope = detail::tableStateScope(key), .point = std::move(point)}; +} + +PrefKey TableStateModel::usageKey(std::string const& person) { + return PrefKey{.person = person, + .app = std::string{kTableStateModel}, + .scope = std::string{kTableStateScopePrefix}, + .point = "usage"}; +} + +bool TableStateModel::holds(std::string const& expected, Head const& head) { + if (expected.empty()) { + return true; + } + if (expected == table::kNoDocument) { + return !head.found; + } + return head.found && expected == head.revision; +} + +void registerTableState(std::shared_ptr store, model::detail::ActionDispatcher& dispatcher, + model::detail::ModelRegistryFactory& registry, TableStateOptions options) { + if (store == nullptr) { + throw std::invalid_argument{"registerTableState: a null store"}; + } + registry.registerModel(kTableStateModel, [store = std::move(store), options = std::move(options), + shared = std::make_shared()] { + return std::make_unique>(store, options, shared); + }); + dispatcher.registerAction(kTableStateModel, "load"); + dispatcher.registerAction(kTableStateModel, "read"); + dispatcher.registerAction(kTableStateModel, "save"); + dispatcher.registerAction(kTableStateModel, "remove"); + dispatcher.registerAction(kTableStateModel, "publish"); +} + +} // namespace morph::ui diff --git a/src/ui/table_views.cpp b/src/ui/table_views.cpp new file mode 100644 index 000000000..9b9fbcffa --- /dev/null +++ b/src/ui/table_views.cpp @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: Apache-2.0 + +// The non-template definitions of . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::ui { + +async::Completion TableViews::load() { + auto [completion, promise] = async::Completion::makeSettleable(_held->owner); + bool const shares = this->shares(); + auto const settle = + std::make_shared(Settle{.promise = std::move(promise), .waiting = shares ? 2 : 1, .failure = {}}); + loadPart(_held, &Held::own, settle); + if (shares) { + loadPart(_held, &Held::shared, settle); + } + return std::move(completion); +} + +table::SavedView const* TableViews::find(table::ViewsDocument const& document, std::string_view name) { + auto const found = std::ranges::find(document.views, name, &table::SavedView::name); + return found == document.views.end() ? nullptr : &*found; +} + +std::string TableViews::failed(table::ViewsPart part, std::string const& reason) { + if (part == table::ViewsPart::Shared) { + return reason.empty() ? std::string{"This view could not be published"} + : "This view could not be published: " + reason; + } + return reason.empty() ? std::string{"Views could not be saved"} : "Views could not be saved: " + reason; +} + +std::string TableViews::reasonOf(std::exception_ptr const& error) { + std::string reason; + try { + std::rethrow_exception(error); + } catch (std::exception const& failure) { + reason = failure.what(); + } catch (...) { + reason.clear(); + } + return reason; +} + +table::TableStateKey TableViews::partOf(table::TableStateKey key, std::string part) { + key.part = std::move(part); + return key; +} + +std::optional TableViews::take(Part& part, std::optional const& stored) { + if (!stored) { + part.document = {}; + part.revision.reset(); + return std::nullopt; + } + auto read = table::readViews(stored->json); + if (!read) { + return "The saved views could not be read: " + read.error().message; + } + part.document = std::move(*read); + part.revision = stored->revision; + return std::nullopt; +} + +void TableViews::loadPart(std::shared_ptr const& held, Part Held::* member, + std::shared_ptr const& settle) { + auto const done = [settle](std::string failure) { + if (settle->failure.empty()) { + settle->failure = std::move(failure); + } + if (--settle->waiting > 0) { + return; + } + if (settle->failure.empty()) { + settle->promise.resolve(Result{}); + } else { + settle->promise.resolve(Result{std::unexpected(settle->failure)}); + } + }; + held->states->load(((*held).*member).key) + .then([held, member, done](std::optional const& stored) { + done(take((*held).*member, stored).value_or(std::string{})); + }) + .onError([done](std::exception_ptr const& error) { + std::string text = "The saved views could not be loaded"; + if (auto const cause = reasonOf(error); !cause.empty()) { + text += ": " + cause; + } + done(std::move(text)); + }); +} + +async::Completion TableViews::start(table::ViewsPart part, table::ViewOperation operation, + std::optional upsert) { + auto [completion, promise] = async::Completion::makeSettleable(_held->owner); + auto const saving = std::make_shared(Saving{.held = _held, + .part = part, + .operation = std::move(operation), + .promise = std::move(promise), + .retried = false, + .upsert = std::move(upsert)}); + Part const& held = partIn(*_held, part); + attempt(saving, held.revision.value_or(std::string{table::kNoDocument})); + return std::move(completion); +} + +void TableViews::attempt(std::shared_ptr const& saving, std::string expected) { + Part const& part = partIn(*saving->held, saving->part); + // The document held is the one stored now after a reload, so a name another window took meanwhile is replaced + // rather than refused; a store that applies the operation itself does so under the same revision. + if (saving->upsert) { + saving->operation = find(part.document, saving->upsert->name) != nullptr + ? table::ViewOperation{table::ReplaceView{*saving->upsert}} + : table::ViewOperation{table::AddView{*saving->upsert}}; + } + auto applied = table::applyViewOperation(part.document, saving->operation, saving->part); + if (!applied) { + std::string text = table::viewErrorText(applied.error(), saving->operation); + saving->promise.resolve(Result{ + std::unexpected(saving->part == table::ViewsPart::Own ? std::move(text) : failed(saving->part, text))}); + return; + } + table::ITableStateStore& store = saving->held->states->store(); + std::string json = table::writeViews(*applied, saving->part); + auto sent = saving->part == table::ViewsPart::Own + ? store.save(part.key, json, std::move(expected)) + : store.publish(part.key, saving->operation, std::move(expected)); + sent.then([saving, document = std::move(*applied), json](table::SaveResult const& result) mutable { + answered(saving, std::move(document), std::move(json), result); + }) + .onError([saving](std::exception_ptr const& error) { + saving->promise.resolve(Result{std::unexpected(failed(saving->part, reasonOf(error)))}); + }); +} + +void TableViews::answered(std::shared_ptr const& saving, table::ViewsDocument document, std::string json, + table::SaveResult const& result) { + Part& part = partIn(*saving->held, saving->part); + switch (result.outcome) { + case table::SaveOutcome::Saved: + part.document = std::move(document); + part.revision = result.revision; + saving->held->states->keep(part.key, + table::StoredTableState{.json = std::move(json), .revision = result.revision}); + saving->promise.resolve(Result{}); + return; + case table::SaveOutcome::Conflict: + if (saving->retried) { + saving->promise.resolve( + Result{std::unexpected(failed(saving->part, "another window changed them at the same time"))}); + return; + } + saving->retried = true; + reload(saving); + return; + case table::SaveOutcome::Refused: + default: + saving->promise.resolve(Result{std::unexpected(failed(saving->part, result.reason))}); + return; + } +} + +void TableViews::reload(std::shared_ptr const& saving) { + Part const& part = partIn(*saving->held, saving->part); + saving->held->states->store() + .load(part.key) + .then([saving](std::optional const& stored) { + Part& reread = partIn(*saving->held, saving->part); + if (auto failure = take(reread, stored)) { + saving->promise.resolve(Result{std::unexpected( + saving->part == table::ViewsPart::Own ? std::move(*failure) : failed(saving->part, *failure))}); + return; + } + if (stored) { + saving->held->states->keep(reread.key, *stored); + } + attempt(saving, stored ? stored->revision : std::string{}); + }) + .onError([saving](std::exception_ptr const& error) { + saving->promise.resolve(Result{std::unexpected(failed(saving->part, reasonOf(error)))}); + }); +} + +std::optional stateAtMount(std::optional stored, + table::ViewsDocument const& own) { + if (!own.defaultView) { + return stored; + } + auto const view = std::ranges::find(own.views, *own.defaultView, &table::SavedView::name); + if (view == own.views.end()) { + return stored; + } + if (!stored) { + table::StateDocument document; + document.layout = view->layout; + document.sort = view->sort; + document.filters = view->filters; + document.view = view->name; + return document; + } + if (own.defaultOnMount) { + stored->sort = view->sort; + stored->filters = view->filters; + } + return stored; +} + +} // namespace morph::ui diff --git a/src/ui/theme.cpp b/src/ui/theme.cpp index 6d4500778..de7da8f6f 100644 --- a/src/ui/theme.cpp +++ b/src/ui/theme.cpp @@ -347,6 +347,9 @@ std::optional combinationProblem(ThemeIndex const& index, TokenFile if (auto problem = dimensionProblem(*resolved)) { return combinationLabel(variant, density, surface) + ": " + *problem; } + if (auto problem = opacityProblem(*resolved)) { + return combinationLabel(variant, density, surface) + ": " + *problem; + } return std::nullopt; } @@ -1072,6 +1075,20 @@ std::optional dimensionProblem(TokenSet const& resolved) { return std::nullopt; } +std::optional opacityProblem(TokenSet const& resolved) { + for (std::string_view const path : kOpacityPaths) { + auto const found = resolved.find(path); + if (found == resolved.end() || found->second.type != "number") { + continue; + } + auto const number = numberOf(found->second.value); + if (number && (*number < 0.0 || *number > 1.0)) { + return std::string{path} + ": must be between 0 and 1"; + } + } + return std::nullopt; +} + std::optional strokeProblem(TokenSet const& resolved) { for (std::string_view const path : kStrokePaths) { auto const found = resolved.find(path); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 70b804c76..6ff06123f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -20,6 +20,77 @@ morph_generate_pinned_facts_header( ${CMAKE_BINARY_DIR}/generated/pinned_facts_generated.hpp ) +# ── The wide-table fixture ─────────────────────────────────────────────────── +# The column-store source every table measurement runs against (docs/spec/table/table.md, "Performance"). Linked +# whole, so the registrations it carries are never dropped by a linker that finds nothing referencing them. +add_library(morph_wide_table_model STATIC table/wide_table_model.cpp) +target_link_libraries(morph_wide_table_model PUBLIC morph::morph) +target_include_directories(morph_wide_table_model PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +apply_warnings(morph_wide_table_model) + +# The table tests' sources, one list for the native executable and the WebAssembly one below. +set(MORPH_TABLE_TEST_SOURCES + table/test_table_source.cpp + table/test_table_sort.cpp + table/test_table_parse.cpp + table/test_table_filter.cpp + table/test_table_distinct.cpp + table/test_table_view_change.cpp + table/test_table_engine.cpp + table/test_table_changes.cpp + table/test_table_query.cpp + table/test_table_selection.cpp + table/test_table_columns.cpp + table/test_table_pending.cpp + table/test_table_reentrancy.cpp + table/test_table_server.cpp + table/test_table_description.cpp + table/test_table_unloaded_cells.cpp + table/test_table_level_cache.cpp + table/test_table_view_cache.cpp + table/test_table_cov_c_cells.cpp + table/test_table_cov_c_query.cpp + table/test_table_cov_c_filter.cpp + table/test_table_cov_c_views.cpp + table/test_table_cov_c_state.cpp + table/test_table_cov_c_edits.cpp + table/test_table_cov_c_cell_edits.cpp + table/test_table_cov_c_layout.cpp + table/test_table_cov_c_parse.cpp + table/test_table_cov_c_units.cpp + table/test_table_cov_c_selection.cpp + table/test_table_cov_c_levels.cpp + table/test_table_cov_c_answer.cpp + table/test_table_cov_c_view_cache.cpp + table/test_table_cov_c_fit.cpp + table/test_table_cov_c_pages.cpp + table/test_table_cov_f_window.cpp + table/test_table_cov_f_levels.cpp + table/test_table_cov_f_engine.cpp + table/test_table_cov_f_edits.cpp + table/test_table_cov_f_selection.cpp + table/test_table_cov_f_description.cpp + table/test_table_state.cpp + table/test_table_measure.cpp + table/test_wide_table.cpp + table/bench_table.cpp +) + +# ── WebAssembly: the table tests alone, run under Node ────────────────────── +# The table module builds without Qt, so its tests run in WebAssembly too and the count gates of +# the single-threaded path are checked there. Nothing else in this directory is built for that target, and Node runs +# the executable by hand, so no test is registered with ctest. +if(EMSCRIPTEN) + add_executable(morph_table_tests ${MORPH_TABLE_TEST_SOURCES}) + target_link_libraries(morph_table_tests PRIVATE morph::morph morph_test_main + "$") + target_include_directories(morph_table_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + # Emscripten's default heap is a fixed 16 MiB; the 100,000 x 300 column store the baselines sort needs it to grow. + target_link_options(morph_table_tests PRIVATE -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=4GB) + apply_warnings(morph_table_tests) + return() +endif() + add_executable(morph_tests oom_injector.cpp test_oom_injector.cpp @@ -29,11 +100,108 @@ add_executable(morph_tests test_example.cpp test_push_records.cpp test_push_effects.cpp + test_cov_c_effects.cpp + test_cov_c_forms_values.cpp + test_cov_h_forms_rules.cpp + test_cov_h_forms_values.cpp + test_cov_h_rational.cpp + test_cov_h_views_columns.cpp + test_cov_c_forms_session.cpp + test_cov_f_forms_session.cpp + test_cov_c_observability.cpp + test_cov_c_ui_document_mutations.cpp + test_cov_c_ui_document_grids.cpp + test_cov_c_ui_document_tables.cpp + test_cov_c_ui_interpreter_inputs.cpp test_push_watch_table.cpp test_push_catalog.cpp test_push_channel.cpp test_push_watch.cpp test_push_cache.cpp + test_ui_interpreter_cache.cpp + ui_table_model_support.cpp + test_ui_table_model_window_rows.cpp + test_ui_table_model_table_catalog.cpp + test_ui_table_model_model_table.cpp + test_ui_table_model_value_rows.cpp + test_ui_table_model_action_table.cpp + test_ui_table_model_filter_menu.cpp + test_ui_table_model_copy_collection.cpp + test_ui_table_model_view_selection.cpp + test_ui_table_model_row_changes.cpp + test_ui_table_model_model_cells.cpp + test_ui_table_model_cell_walk.cpp + test_ui_table_model_cell_reads.cpp + test_ui_table_model_cell_edits.cpp + test_ui_table_model_cell_errors.cpp + test_ui_grid.cpp + test_ui_cov_grid_form_rows.cpp + test_ui_cov_grid_keys.cpp + test_ui_cov_expression.cpp + test_ui_cov_h_expression.cpp + test_ui_cov_h_theme.cpp + test_ui_cov_h_page_layout.cpp + test_ui_cov_h_navigator.cpp + test_ui_cov_h_table_dialogs.cpp + test_ui_cov_h_table_state.cpp + test_ui_cov_h_interp_download.cpp + test_ui_cov_h_interp_lowering.cpp + test_ui_cov_interp_lowering.cpp + test_ui_cov_interp_elements.cpp + test_ui_cov_grid_unknown.cpp + test_ui_cov_j_grid_source.cpp + test_ui_cov_j_page_mount.cpp + test_ui_cov_j_mount_labels.cpp + test_ui_cov_j_filter_pages.cpp + test_ui_cov_j_explorer_search.cpp + test_ui_cov_j_custom_checks.cpp + test_ui_cov_j_workspace_head.cpp + test_ui_cov_j_filter_menu.cpp + test_ui_cov_j_controller.cpp + test_ui_cov_j_custom_source.cpp + test_ui_cov_j_mount_keys.cpp + test_ui_cov_j_explorer.cpp + test_ui_cov_grid_paste.cpp + test_ui_cov_grid_rows.cpp + test_ui_cov_interp_rows.cpp + test_ui_cov_grid_model.cpp + test_ui_cov_grid_fixed.cpp + test_ui_cov_interp_collections.cpp + test_ui_cov_interp_forms.cpp + test_ui_cov_mount_extents.cpp + test_ui_cov_interp_fixed_grid.cpp + test_ui_cov_d_form_grid.cpp + test_ui_cov_d_fixed_grid.cpp + test_ui_cov_d_custom_screen_checks.cpp + test_ui_cov_d_custom_screen_words.cpp + test_ui_cov_d_shell_parts.cpp + test_ui_cov_d_chat_tools.cpp + test_ui_cov_d_workspace.cpp + test_ui_cov_d_rows_bound.cpp + test_ui_cov_g_action_table_view.cpp + test_ui_cov_g_document_loader.cpp + test_ui_cov_g_table_points.cpp + test_ui_cov_g_menu_walk.cpp + test_ui_cov_g_rows_decorators.cpp + test_ui_cov_g_model_grid.cpp + test_ui_cov_g_element_values.cpp + test_ui_cov_g_model_table_binds.cpp + test_ui_cov_g_host_commands.cpp + test_ui_cov_g_typed_table.cpp + test_ui_cov_g_filter_menu.cpp + test_ui_cov_g_window_fetch.cpp + test_ui_cov_g_model_grid_values.cpp + test_ui_cov_g_grid_controller.cpp + test_ui_cov_g_form_grid_rows.cpp + test_ui_cov_g_fixed_grid_source.cpp + test_ui_cov_d_rows_state.cpp + test_ui_cov_d_chart.cpp + test_ui_cov_d_grid_groups.cpp + test_ui_cov_d_host.cpp + test_ui_cov_d_shell_frame.cpp + test_ui_cov_d_grid_bound.cpp + forms/test_forms_derive.cpp + test_ui_table_state.cpp test_push_agent.cpp test_mcp_transport.cpp test_chat_settle.cpp @@ -216,10 +384,41 @@ add_executable(morph_tests test_ui_structure.cpp test_ui_foreach.cpp test_ui_table.cpp + test_ui_cell_format.cpp + test_ui_cov_table_cell_format.cpp + test_ui_cov_table_config.cpp + test_ui_cov_table_filter_menu.cpp + test_ui_cov_table_state.cpp + test_ui_cov_table_engine_rows.cpp + test_ui_cov_table_window_rows.cpp + test_ui_cov_table_views_menu.cpp + test_ui_cov_table_filter_dialog.cpp + test_ui_cov_table_model_columns.cpp + test_ui_cov_table_rows_pure.cpp + test_ui_cov_table_window_state.cpp + test_ui_cov_table_runs.cpp + test_ui_cov_table_mount.cpp + test_ui_cov_table_state_model.cpp + test_ui_cov_h_table_state_model.cpp + test_ui_cov_i_views.cpp + test_ui_cov_i_cell_menu.cpp + test_ui_cov_i_rows_table.cpp + test_ui_cov_i_collection.cpp + test_ui_cov_i_rows_columns.cpp + test_ui_cov_i_stored_state.cpp + test_ui_cov_i_groups.cpp + test_ui_cov_i_table_gestures.cpp + test_ui_cov_i_views_menu.cpp + test_ui_cov_i_sort_dialog.cpp + test_ui_table_config.cpp bench_interpreter.cpp bench_mount.cpp test_ui_frontend.cpp test_ui_conformance.cpp + test_ui_cov_e_conformance_faults.cpp + test_ui_cov_e_recording_backend.cpp + test_ui_cov_e_interpreter.cpp + test_ui_cov_f_interpreter.cpp test_ui_spotlight_recording.cpp test_ui_common.cpp test_ui_custom.cpp @@ -252,6 +451,7 @@ add_executable(morph_tests test_ui_interpreter_table.cpp test_ui_interpreter_chart.cpp test_ui_chart_scale.cpp + test_ui_stretch_columns.cpp test_ui_document_rules.cpp test_ui_interpreter_gallery.cpp test_ui_interpreter_edges.cpp @@ -316,6 +516,7 @@ target_link_libraries(morph_tests PRIVATE morph::morph morph_test_main + "$" ) apply_warnings(morph_tests) @@ -991,24 +1192,9 @@ endif() # Its own executable so the threaded engine tests can run alone under a # sanitizer preset. The `[.benchmark]` cases are hidden: catch_discover_tests # does not list them, and they run only when asked for by tag. -add_executable(morph_table_tests - table/test_table_source.cpp - table/test_table_sort.cpp - table/test_table_parse.cpp - table/test_table_filter.cpp - table/test_table_view_change.cpp - table/test_table_engine.cpp - table/test_table_changes.cpp - table/test_table_query.cpp - table/test_table_database_pages.cpp - table/test_table_selection.cpp - table/test_table_columns.cpp - table/test_table_pending.cpp - table/test_table_reentrancy.cpp - table/test_table_server.cpp - table/bench_table.cpp -) -target_link_libraries(morph_table_tests PRIVATE morph::morph morph_test_main) +add_executable(morph_table_tests ${MORPH_TABLE_TEST_SOURCES}) +target_link_libraries(morph_table_tests PRIVATE morph::morph morph_test_main + "$") target_include_directories(morph_table_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_compile_options(morph_table_tests PRIVATE $<$:/bigobj>) apply_warnings(morph_table_tests) diff --git a/tests/bench_interpreter.cpp b/tests/bench_interpreter.cpp index 720542895..ae0d3bfdc 100644 --- a/tests/bench_interpreter.cpp +++ b/tests/bench_interpreter.cpp @@ -5,12 +5,37 @@ // // morph_tests "[.benchmark][interpreter]" +#include #include #include +#include +#include #include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include "forms_engine_support.hpp" +#include "qt_quick/wide_rows_document.hpp" +#include "table/wide_table_model.hpp" #include "ui_interpreter_support.hpp" namespace ui = morph::ui; @@ -64,3 +89,726 @@ TEST_CASE("interpreter bench: update state read by a mounted screen", "[.benchma return h.backend.all("Text").size(); }; } + +// ── Step 0 baselines: a `rows` table on the interpreter, and a collection ─── +// docs/spec/table/table.md, "Benchmarks: every surface". Each case first REQUIREs that the path it times was reached. +// Run on a Release build: +// +// morph_tests "[.benchmark][baseline]" + +namespace { + +using Clock = std::chrono::steady_clock; + +struct Spread { + double median = 0; + double p10 = 0; + double p90 = 0; +}; + +Spread spreadOf(std::vector samples) { + std::ranges::sort(samples); + auto const at = [&](double q) { + auto const index = static_cast(std::lround(q * static_cast(samples.size() - 1))); + return samples[std::min(index, samples.size() - 1)]; + }; + return Spread{.median = at(0.5), .p10 = at(0.1), .p90 = at(0.9)}; +} + +double millisSince(Clock::time_point began) { + return std::chrono::duration(Clock::now() - began).count(); +} + +void printRow(std::string_view scenario, std::size_t rows, Spread const& spread) { + std::println("| {} | {} | {:.2f} | {:.2f}-{:.2f} |", scenario, rows, spread.median, spread.p10, spread.p90); + static_cast(std::fflush(stdout)); +} + +std::string jsonText(std::string const& text) { + std::string out; + REQUIRE_FALSE(glz::write_json(text, out)); + return out; +} + +// The rows of a `rows` table over the fixture: `id`, `name` from `t001` and `qty` from `i001`. +std::string fixtureItems(bench::WideTableSource const& source) { + auto const snapshot = source.snapshot(); + auto const columns = source.columns(); + auto const index = [&](std::string_view id) { + return static_cast(std::ranges::find(columns, id, &morph::table::ColumnInfo::id) - + columns.begin()); + }; + auto const name = index("t001"); + auto const qty = index("i001"); + std::string items; + for (std::size_t row = 0; row < snapshot->rowCount(); ++row) { + auto const quantity = snapshot->cell(row, qty); + items += std::format(R"({}{{"id":{},"name":{},"qty":{}}})", row == 0 ? "" : ",", row + 1, + jsonText(morph::table::displayText(snapshot->cell(row, name))), + std::holds_alternative(quantity) ? std::string{"null"} + : morph::table::displayText(quantity)); + } + return items; +} + +// A table over state `items` whose sort is state `order`; "sort" sorts it by name, "rename" gives the row keyed +// @p renamed a name that sorts last. +std::string sortedDocument(std::string const& items, std::int64_t renamed) { + return std::format(R"({{ + "vocab": "ui/1", "id": "baselineRows", + "state": {{ "items": {{ "init": {{ "lit": [{}] }} }}, "order": {{ "init": {{ "lit": [] }} }} }}, + "view": {{ "kind": "column", "children": [ + {{ "kind": "button", "testId": "sort", "label": "sort", + "onClick": {{ "set": "order", "value": {{ "lit": [ {{ "column": "name", "direction": "asc" }} ] }} }} }}, + {{ "kind": "button", "testId": "rename", "label": "rename", + "onClick": {{ "set": "items", "value": {{ "map": {{ "ref": "items" }}, "as": "r", "to": {{ "if": [ + {{ "fn": "eq", "args": [ {{ "ref": "r.id" }}, {} ] }}, + {{ "obj": {{ "id": {{ "ref": "r.id" }}, "name": "ÿÿÿ", "qty": {{ "ref": "r.qty" }} }} }}, + {{ "ref": "r" }} ] }} }} }} }}, + {{ "kind": "table", "rows": {{ "ref": "items" }}, "sort": {{ "ref": "order" }}, + "columns": [ {{ "id": "id", "label": "Id" }}, {{ "id": "name", "label": "Name", "sortable": true }}, + {{ "id": "qty", "label": "Qty" }} ] }} ] }} }})", + items, renamed); +} + +// The texts of the first row the table shows, in column order. +std::vector firstRowTexts(Harness const& h) { + auto const tables = h.backend.all("Table"); + REQUIRE(tables.size() == 1); + auto const rows = h.backend.children(tables.front()); + REQUIRE_FALSE(rows.empty()); + std::vector texts; + std::vector pending{rows.front()}; + while (!pending.empty()) { + int const id = pending.front(); + pending.erase(pending.begin()); + if (h.backend.kindOf(id) == "Text") { + texts.push_back(h.backend.prop(id, "text")); + } + auto const children = h.backend.children(id); + pending.insert(pending.begin(), children.begin(), children.end()); + } + return texts; +} + +std::string realizedWindow(Harness const& h) { + return h.backend.prop(h.backend.all("Table").front(), "realizedWindow"); +} + +} // namespace + +TEST_CASE("interpreter baseline: U1 U2 a rows table of 100,000", "[.benchmark][baseline]") { + constexpr std::size_t kRows = 100'000; + bench::WideTableSource const source{{.rows = kRows, .columns = 300, .seed = 1}}; + std::string const items = fixtureItems(source); + // The row U2 renames is the one the sorted table shows first, read from one mount before the timed runs. + std::int64_t shownFirst = 0; + { + Harness probe; + auto const screen = probe.mount(sortedDocument(items, 0)); + probe.backend.click(probe.byTestId("Button", "sort")); + probe.settle(); + auto const texts = firstRowTexts(probe); + REQUIRE_FALSE(texts.empty()); + shownFirst = std::stoll(texts.front()); + } + std::string const document = sortedDocument(items, shownFirst); + std::println( + "\nU1, U2: a document rows table of 100,000 rows on the recording backend, click to settled\n\n" + "| scenario | rows | median ms | p10-p90 ms |\n|---|---:|---:|---:|"); + std::vector sorts; + std::vector renames; + for (int run = 0; run < 7; ++run) { + Harness h; + auto const screen = h.mount(document); + REQUIRE(realizedWindow(h).ends_with("/100000")); + auto const before = firstRowTexts(h); + auto began = Clock::now(); + h.backend.click(h.byTestId("Button", "sort")); + h.settle(); + sorts.push_back(millisSince(began)); + auto const sorted = firstRowTexts(h); + REQUIRE(sorted.size() >= 2); + REQUIRE(sorted != before); + began = Clock::now(); + h.backend.click(h.byTestId("Button", "rename")); + h.settle(); + renames.push_back(millisSince(began)); + auto const after = firstRowTexts(h); + REQUIRE(after.size() >= 2); + REQUIRE(after.front() != sorted.front()); // the renamed row moved from the top + } + printRow("U1: sort on name, click to settled", kRows, spreadOf(sorts)); + printRow("U2: one row renamed in the sorted table, click to settled", kRows, spreadOf(renames)); +} + +namespace { + +// The bytes a document value holds, as the cells' `approximateCellBytes` counts a cell: the `Value` itself, a string's +// heap buffer when it has one, a list's or a record's container and its elements, with each map node's pointers. +// A list or record shared between values is counted once; allocator overhead is not counted, as for the cells. +class ValueBytes { +public: + [[nodiscard]] std::size_t of(ui::Value const& value) { return sizeof(ui::Value) + held(value); } + +private: + // What @p value holds outside its own `sizeof`. + // NOLINTNEXTLINE(misc-no-recursion): `held` measures a value that may nest lists and records, recursing once per level of the document's own nesting + std::size_t held(ui::Value const& value) { + if (std::string const* const text = value.asString()) { + return heap(*text); + } + if (ui::Quantity const* const quantity = value.asQuantity()) { + return heap(quantity->unit); + } + if (ui::ValueList const* const list = value.asList()) { + if (!_seen.insert(list).second) { + return 0; + } + std::size_t bytes = kControlBlock + sizeof(ui::ValueList) + (list->capacity() * sizeof(ui::Value)); + for (ui::Value const& item : *list) { + bytes += held(item); + } + return bytes; + } + if (ui::ValueRecord const* const record = value.asRecord()) { + if (!_seen.insert(record).second) { + return 0; + } + std::size_t bytes = kControlBlock + sizeof(ui::ValueRecord) + kMapNode; // the map's sentinel node + for (auto const& [key, field] : *record) { + bytes += kMapNode + heap(key) + held(field); + } + return bytes; + } + return 0; + } + + [[nodiscard]] static std::size_t heap(std::string const& text) { + return text.capacity() > std::string{}.capacity() ? text.capacity() + 1 : 0; + } + + // A shared_ptr's control block: two counts and a vtable pointer. + static constexpr std::size_t kControlBlock = (2 * sizeof(long)) + sizeof(void*); + // A map node: its key and value, three links and its colour, padded. + static constexpr std::size_t kMapNode = sizeof(std::pair) + (4 * sizeof(void*)); + std::unordered_set _seen; +}; + +} // namespace + +TEST_CASE("interpreter baseline: U4 memory of a rows table", "[.benchmark][baseline]") { + constexpr std::size_t kRows = 10'000; + bench::WideTableSource const source{{.rows = kRows, .columns = 300, .seed = 1}}; + auto const snapshot = source.snapshot(); + std::size_t cellBytes = 0; + for (std::size_t row = 0; row < kRows; ++row) { + for (std::size_t column = 0; column < source.columns().size(); ++column) { + cellBytes += bench::approximateCellBytes(snapshot->cell(row, column)); + } + } + std::string const document = std::format( + R"({{ "vocab": "ui/1", "id": "baselineMemory", "state": {{ "items": {{ "init": {{ "lit": [{}] }} }} }}, + "view": {{ "kind": "table", "rows": {{ "ref": "items" }}, "sort": {{ "lit": [ {{ "column": "t001", "direction": "asc" }} ] }}, + "columns": [{}] }} }})", + bench::wideRowsJson(source), bench::wideColumnsJson(source)); + Harness h; + auto screen = h.mount(document); + REQUIRE(realizedWindow(h).ends_with("/10000")); + auto const reference = ui::parseJson(R"({"ref": "items"})"); + REQUIRE(reference.has_value()); + ui::Value const items = screen->read(*reference); + REQUIRE(items.asList() != nullptr); + REQUIRE(items.asList()->size() == kRows); + auto const valueBytes = ValueBytes{}.of(items); + std::println( + "\nU4: a rows table of 10,000 x 300 sorted on one column\n\n| held as | bytes | MiB | bytes per cell |\n" + "|---|---:|---:|---:|\n" + "| cells (approximateCellBytes) | {} | {:.1f} | {:.1f} |\n" + "| the state's document values | {} | {:.1f} | {:.1f} |", + cellBytes, static_cast(cellBytes) / (1024.0 * 1024.0), + static_cast(cellBytes) / (kRows * 300.0), valueBytes, + static_cast(valueBytes) / (1024.0 * 1024.0), static_cast(valueBytes) / (kRows * 300.0)); + static_cast(std::fflush(stdout)); +} + +namespace { + +constexpr std::string_view kCollectionView = R"({ + "v-kind": "collection", "v-title": "Rows", "v-query": "ListRows", "v-rowKey": "id", + "v-columns": [ + {"field": "id", "label": "ID", "kind": "integer", "v-hidden": true}, + {"field": "name", "label": "Name", "kind": "text"}, + {"field": "qty", "label": "Qty", "kind": "integer"}]})"; + +// A ListRows reply of the fixture's rows; @p renamed, when not 0, is the key of a row whose name is changed. +std::string listReply(bench::WideTableSource const& source, std::int64_t renamed) { + auto const snapshot = source.snapshot(); + auto const columns = source.columns(); + auto const index = [&](std::string_view id) { + return static_cast(std::ranges::find(columns, id, &morph::table::ColumnInfo::id) - + columns.begin()); + }; + auto const name = index("t001"); + auto const qty = index("i001"); + std::string out = R"({"rows":[)"; + for (std::size_t row = 0; row < snapshot->rowCount(); ++row) { + auto const key = static_cast(row) + 1; + auto const quantity = snapshot->cell(row, qty); + out += std::format( + R"({}{{"id":{},"name":{},"qty":{}}})", row == 0 ? "" : ",", key, + jsonText(key == renamed ? std::string{"renamed"} : morph::table::displayText(snapshot->cell(row, name))), + std::holds_alternative(quantity) ? std::string{"null"} + : morph::table::displayText(quantity)); + } + out += "]}"; + return out; +} + +} // namespace + +TEST_CASE("interpreter baseline: U5 a collection of 20,000", "[.benchmark][baseline]") { + constexpr std::size_t kRows = 20'000; + bench::WideTableSource const source{{.rows = kRows, .columns = 30, .seed = 1}}; + std::string const original = listReply(source, 0); + std::string const edited = listReply(source, 1); + auto const model = morph::forms::CollectionModel::fromSchema(kCollectionView); + REQUIRE(model.has_value()); + std::println( + "\nU5: a collection of 20,000 rows over a ListRows reply\n\n" + "| scenario | rows | median ms | p10-p90 ms |\n|---|---:|---:|---:|"); + std::vector mounts; + std::vector sorts; + std::vector edits; + for (int run = 0; run < 15; ++run) { + morph::test::formsengine::Harness harness; + std::string const* reply = &original; + harness.server.replyWith([&reply](morph::test::formsengine::Call const& call) -> std::optional { + if (call.action == "ListRows") { + return *reply; + } + return std::string{R"({"ok":true})"}; + }); + auto began = Clock::now(); + morph::forms::CollectionSession collection{harness.rt, *model, + [](std::string_view) { return std::optional{}; }, + harness.server.submitter(), harness.server.fetcher()}; + harness.settle(); + mounts.push_back(millisSince(began)); + REQUIRE(collection.rows().size() == kRows); + + morph::table::Engine engine{collection.source()}; + began = Clock::now(); + REQUIRE(engine.setSort({{.column = "name", .dir = morph::table::SortDirection::Ascending}}).has_value()); + engine.settleNow(); + sorts.push_back(millisSince(began)); + REQUIRE(engine.viewRowCount() == kRows); + + reply = &edited; + began = Clock::now(); + collection.refresh(); + harness.settle(); + engine.settleNow(); + edits.push_back(millisSince(began)); + REQUIRE(collection.rows().size() == kRows); + REQUIRE(collection.rows().front().cells.front() == "renamed"); + } + printRow("U5: mount (list reply decoded into the collection)", kRows, spreadOf(mounts)); + printRow("U5: sort on name through the table engine", kRows, spreadOf(sorts)); + printRow("U5: one row edited (the list reloaded) and the sorted view repaired", kRows, spreadOf(edits)); +} + +// U5 on a screen: a `collection` node over the corpus's sample list, its rows a table on the engine. Mount is the +// list's reply to settled; sort is a header click on Name to settled; an edit is a row's delete answered, then the +// reloaded list with one row renamed answered, to settled. docs/spec/table/table.md, "Performance". Run on a +// Release build: +// +// morph_tests "interpreter bench: a collection of 20\,000 rows*" (Catch2 reads an unescaped comma as a list) +TEST_CASE("interpreter bench: a collection of 20,000 rows: mount, sort, one row edited", "[.benchmark][interpreter]") { + constexpr std::size_t kRows = 20'000; + bench::WideTableSource const source{{.rows = kRows, .columns = 30, .seed = 1}}; + std::string const original = listReply(source, 0); + std::string const edited = listReply(source, 1); + constexpr std::string_view kDocument = R"({ + "vocab": "ui/1", "id": "bench", + "models": { "sample": { "type": "Lims_SampleModel" } }, + "view": { "kind": "collection", "model": "sample", "action": "Lims_ListSamples" } })"; + std::println( + "\nU5: a collection node of 20,000 rows on the table engine, call to settled\n\n" + "| scenario | rows | median ms | p10-p90 ms |\n|---|---:|---:|---:|"); + std::vector mounts; + std::vector sorts; + std::vector edits; + for (int run = 0; run < 7; ++run) { + Harness h; + auto const screen = h.mount(kDocument); + auto began = Clock::now(); + h.reply(h.dispatcher.last("Lims_ListSamples"), original); + mounts.push_back(millisSince(began)); + int const table = h.byTestId("Table", "collection_rows"); + REQUIRE_FALSE(h.backend.children(table).empty()); + + began = Clock::now(); + h.backend.clickHeader(table, 1, ui::HeaderClick::Plain); // Name + h.settle(); + sorts.push_back(millisSince(began)); + REQUIRE(h.backend.prop(table, "sort") == "1:Ascending"); + + std::string const key = h.backend.prop(h.backend.children(table).front(), "rowKey"); + h.backend.click(h.byTestId("Button", "rowAction_Lims_DeleteSample_" + key)); + h.settle(); + h.backend.click(h.byTestId("Button", "confirm_accept")); + h.settle(); + h.reply(h.dispatcher.last("Lims_DeleteSample"), "{}"); + began = Clock::now(); + h.reply(h.dispatcher.last("Lims_ListSamples"), edited); + edits.push_back(millisSince(began)); + REQUIRE(h.backend.prop(table, "sort") == "1:Ascending"); + } + printRow("U5: mount (the list's reply to settled)", kRows, spreadOf(mounts)); + printRow("U5: sort on Name from the header, click to settled", kRows, spreadOf(sorts)); + printRow("U5: one row edited (the list reloaded), reply to settled", kRows, spreadOf(edits)); +} + +namespace { + +// `T_Page` holds `T_Row` keyed by `code` at `rows`; `T_TablePage` holds it opaquely, as `Table.` does. +ui::Catalog k4Catalog() { + ui::Catalog catalog = ui::testing::corpusCatalog(); + auto const base = catalog.action; + catalog.action = [base](std::string_view action) -> std::optional { + auto info = base(action); + if (info && action == "T_Page") { + info->records = {ui::ActionRecordInfo{ + .record = "T_Row", .keyField = "code", .paths = {"rows"}, .open = {}, .partial = {}, .opaque = false}}; + } + if (info && action == "T_TablePage") { + info->records = {ui::ActionRecordInfo{ + .record = "T_Row", .keyField = "code", .paths = {}, .open = {}, .partial = {}, .opaque = true}}; + } + return info; + }; + return catalog; +} + +std::string k4Document(std::string_view action) { + return std::format(R"({{ + "vocab": "ui/1", "id": "k4", + "models": {{ "sample": {{ "type": "Lims_SampleModel" }} }}, + "queries": {{ "page": {{ "model": "sample", "action": "{}" }} }}, + "view": {{ "kind": "text", "text": "k4" }} }})", + action); +} + +} // namespace + +TEST_CASE("interpreter bench: K4 the query cache under an event and a wide page", "[.benchmark][interpreter]") { + std::string rows; + for (int row = 0; row < 200; ++row) { + rows += std::format(R"({}{{"code":{},"name":"row-{}"}})", row == 0 ? "" : ",", row, row); + } + morph::wire::ChangesBody event; + event.records.push_back(morph::effects::RecordChange{.record = "T_Row", .keys = std::vector{}}); + for (int key = 0; key < 4'096; ++key) { + event.records.back().keys->emplace_back(std::to_string(100'000 + key)); + } + std::vector events; + for (int run = 0; run < 15; ++run) { + Harness h{k4Catalog()}; + auto const screen = h.mount(k4Document("T_Page")); + h.reply(0, std::format(R"({{"rows":[{}]}})", rows)); + auto const began = std::chrono::steady_clock::now(); + h.session.applyChanges(event); + events.push_back(std::chrono::duration(std::chrono::steady_clock::now() - began).count()); + REQUIRE(h.dispatcher.calls.size() == 1); + } + + std::string page = R"({"revision":"r","columns":[)"; + for (int column = 0; column < 300; ++column) { + page += std::format(R"({}"c{:03}")", column == 0 ? "" : ",", column); + } + page += R"(],"keys":[)"; + for (int row = 0; row < 200; ++row) { + page += std::format("{}{}", row == 0 ? "" : ",", row); + } + page += R"(],"rows":[)"; + for (int row = 0; row < 200; ++row) { + page += row == 0 ? "[" : ",["; + for (int column = 0; column < 300; ++column) { + page += std::format("{}{}.5", column == 0 ? "" : ",", row + column); + } + page += ']'; + } + page += R"(],"total":200,"totalKind":"exact","offset":0})"; + std::vector stores; + for (int run = 0; run < 7; ++run) { + Harness h{k4Catalog()}; + auto const screen = h.mount(k4Document("T_TablePage")); + auto const began = std::chrono::steady_clock::now(); + h.reply(0, page); + stores.push_back(std::chrono::duration(std::chrono::steady_clock::now() - began).count()); + } + std::ranges::sort(events); + std::ranges::sort(stores); + std::println("\n| K4 | a 4,096-key event against an entry of 200 rows | {:.3f} ms median ({:.3f}-{:.3f}) |", + events[events.size() / 2], events.front(), events.back()); + std::println( + "| K4 | storing a decoded 200 x 300 page of fractional numbers in an opaque entry | {:.3f} ms median " + "({:.3f}-{:.3f}) |", + stores[stores.size() / 2], stores.front(), stores.back()); + static_cast(std::fflush(stdout)); +} + +// U1, U2 and U4 on the engine: a document's rows through `ValueRowsSource`. Timings only; their count gates are the +// "value rows source" cases of test_ui_table_model_value_rows.cpp. + +namespace { + +// A runtime of its own, a source over @p columns keyed by `id`, and an engine over it. +struct RowsOnEngine { + explicit RowsOnEngine(std::vector columns) + : source{std::make_shared( + runtime, std::move(columns), [](ui::Value const& row) { return ui::Key{*row.field("id")->asInt()}; })}, + engine{source, morph::table::EngineOptions{.owner = &owner}} {} + + morph::testing::StepExecutor owner; + morph::reactive::Runtime runtime{owner}; + std::shared_ptr source; + morph::table::Engine engine; +}; + +ui::ValueList listOf(std::string const& items) { + auto const json = ui::parseJson("[" + items + "]"); + REQUIRE(json.has_value()); + auto const value = ui::valueFromJson(*json); + REQUIRE(value.has_value()); + REQUIRE(value->asList() != nullptr); + return *value->asList(); +} + +// A copy of @p rows whose row @p at has the name "ÿÿÿ", which sorts last; the other rows share storage with @p rows. +ui::ValueList renamed(ui::ValueList rows, std::size_t at) { + ui::ValueRecord fields = *rows.at(at).asRecord(); + fields.insert_or_assign("name", ui::Value{std::string{"ÿÿÿ"}}); + rows.at(at) = ui::Value{std::move(fields)}; + return rows; +} + +std::vector plainColumns(std::initializer_list ids) { + std::vector columns; + for (auto const id : ids) { + columns.push_back(ui::ValueColumn{.id = std::string{id}, .kind = std::nullopt, .sortBy = {}}); + } + return columns; +} + +} // namespace + +TEST_CASE("interpreter bench: U1 U2 a rows table of 100,000 on the engine", "[.benchmark][interpreter]") { + constexpr std::size_t kRows = 100'000; + bench::WideTableSource const fixture{{.rows = kRows, .columns = 300, .seed = 1}}; + std::string const items = fixtureItems(fixture); + ui::ValueList const rows = listOf(items); + std::println( + "\nU1, U2: a document's rows of 100,000 through ValueRowsSource and the engine, call to settled\n\n" + "| scenario | rows | median ms | p10-p90 ms |\n|---|---:|---:|---:|"); + std::vector sorts; + std::vector shared; + std::vector fresh; + for (int run = 0; run < 7; ++run) { + RowsOnEngine h{plainColumns({"id", "name", "qty"})}; + h.source->assign(rows); + h.owner.runAll(); + auto began = Clock::now(); + h.source->use("name"); + REQUIRE(h.engine.setSort({{.column = "name", .dir = morph::table::SortDirection::Ascending}})); + h.owner.runAll(); + sorts.push_back(millisSince(began)); + auto const first = std::get(h.engine.rowIdAt(0)); + auto const firstRow = static_cast(first - 1); + began = Clock::now(); + h.source->assign(renamed(rows, firstRow)); + h.owner.runAll(); + shared.push_back(millisSince(began)); + REQUIRE(std::get(h.engine.rowIdAt(kRows - 1)) == first); // the renamed row moved to the end + // The held rows with one more renamed, written to JSON and read back: no row shares storage. + std::string const held = ui::detail::canonicalJson(ui::Value{renamed(renamed(rows, firstRow), firstRow + 1)}); + ui::ValueList const decoded = listOf(held.substr(1, held.size() - 2)); + began = Clock::now(); + h.source->assign(decoded); + h.owner.runAll(); + fresh.push_back(millisSince(began)); + REQUIRE(std::get(h.engine.rowIdAt(kRows - 1)) == first + 1); + } + printRow("U1: use and sort on name, call to settled", kRows, spreadOf(sorts)); + printRow("U2: one row renamed, other rows shared", kRows, spreadOf(shared)); + printRow("U2: one row renamed, a fresh decode of every row", kRows, spreadOf(fresh)); +} + +TEST_CASE("interpreter bench: U4 memory of a rows table on the engine", "[.benchmark][interpreter]") { + constexpr std::size_t kRows = 10'000; + bench::WideTableSource const fixture{{.rows = kRows, .columns = 300, .seed = 1}}; + std::vector columns; + for (auto const& column : fixture.columns()) { + columns.push_back(ui::ValueColumn{.id = column.id, .kind = std::nullopt, .sortBy = {}}); + } + RowsOnEngine h{std::move(columns)}; + h.source->assign(listOf(bench::wideRowsJson(fixture))); + h.source->use("t001"); + REQUIRE(h.engine.setSort({{.column = "t001", .dir = morph::table::SortDirection::Ascending}})); + h.owner.runAll(); + REQUIRE(h.engine.viewRowCount() == kRows); + auto const snapshot = h.source->snapshot(); + auto const sorted = static_cast( + std::ranges::find(h.source->columns(), std::string{"t001"}, &morph::table::ColumnInfo::id) - + h.source->columns().begin()); + std::size_t heldBytes = 0; + std::size_t allBytes = 0; + for (std::size_t row = 0; row < kRows; ++row) { + for (std::size_t column = 0; column < fixture.columns().size(); ++column) { + std::size_t const bytes = bench::approximateCellBytes(fixture.snapshot()->cell(row, column)); + allBytes += bytes; + } + heldBytes += bench::approximateCellBytes(snapshot->cell(row, sorted)); + } + std::println( + "\nU4: a rows table of 10,000 x 300 through ValueRowsSource, sorted on one column\n\n" + "| held as | cells | bytes | MiB |\n|---|---:|---:|---:|\n" + "| the source's cells (one column in use) | {} | {} | {:.2f} |\n" + "| every column as cells (approximateCellBytes) | {} | {} | {:.1f} |", + h.source->cellsHeld(), heldBytes, static_cast(heldBytes) / (1024.0 * 1024.0), + kRows * fixture.columns().size(), allBytes, static_cast(allBytes) / (1024.0 * 1024.0)); + static_cast(std::fflush(stdout)); +} + +// B1 as a `rows` table runs it: the engine with no worker, in owner steps of 4 ms, over `ValueRowsSource`, with the +// collator a rows table orders by. A timing: the bounds are table.md's, read off the printed rows. +TEST_CASE("interpreter bench: B1 a rows table's sort and filter in owner steps", "[.benchmark][interpreter]") { + std::println( + "\nB1: a three-key sort then a text filter on a rows table's engine, no worker, 4 ms steps\n\n" + "| scenario | rows | median ms | p10-p90 ms |\n|---|---:|---:|---:|"); + for (std::size_t const rows : {std::size_t{10'000}, std::size_t{20'000}, std::size_t{100'000}}) { + bench::WideTableSource const fixture{{.rows = static_cast(rows), .columns = 300, .seed = 1}}; + ui::ValueList const items = listOf(fixtureItems(fixture)); + std::vector results; + std::vector steps; + for (int run = 0; run < 7; ++run) { + morph::testing::StepExecutor owner; + morph::reactive::Runtime runtime{owner}; + auto const source = std::make_shared( + runtime, plainColumns({"id", "name", "qty"}), + [](ui::Value const& row) { return ui::Key{*row.field("id")->asInt()}; }); + morph::table::EngineOptions options; + options.owner = &owner; + options.frameBudget = std::chrono::milliseconds{4}; + options.services.collator = std::make_shared(); + morph::table::Engine engine{source, std::move(options)}; + source->assign(items); + for (auto const* const column : {"name", "qty", "id"}) { + source->use(column); + } + owner.runAll(); + morph::table::EngineStats const before = engine.stats(); + auto const began = Clock::now(); + REQUIRE(engine.setSort({{.column = "name", .dir = morph::table::SortDirection::Ascending}, + {.column = "qty", .dir = morph::table::SortDirection::Descending}, + {.column = "id", .dir = morph::table::SortDirection::Ascending}})); + morph::table::FilterSpec filter; + filter.columns["name"].include.push_back(morph::table::FilterEntry{.contains = "a"}); + auto const filtered = engine.setFilter(std::move(filter)); + REQUIRE(filtered); + owner.runAll(); + results.push_back(millisSince(began)); + REQUIRE(engine.stats().ownerSteps - before.ownerSteps > 1); // the work ran in steps, not in one call + steps.push_back(static_cast(engine.stats().maxOwnerStepMicros) / 1000.0); + } + printRow("B1: request to result", rows, spreadOf(results)); + printRow("B1: the longest owner step", rows, spreadOf(steps)); + } +} + +// Where U1's and U2's time goes on the engine: the source's part (putting a column in use, matching a new list) and +// the engine's (absorbing the change, sorting or repairing), each call to settled. Timings only. +TEST_CASE("interpreter bench: U1 U2 split between the source and the engine", "[.benchmark][interpreter]") { + constexpr std::size_t kRows = 100'000; + bench::WideTableSource const fixture{{.rows = kRows, .columns = 300, .seed = 1}}; + ui::ValueList const rows = listOf(fixtureItems(fixture)); + std::println( + "\nU1, U2 split: a document's rows of 100,000, the source's call and the engine's settling\n\n" + "| scenario | rows | median ms | p10-p90 ms |\n|---|---:|---:|---:|"); + std::vector use; + std::vector useSettled; + std::vector sort; + std::vector assign; + std::vector repair; + for (int run = 0; run < 7; ++run) { + RowsOnEngine h{plainColumns({"id", "name", "qty"})}; + h.source->assign(rows); + h.owner.runAll(); + auto began = Clock::now(); + h.source->use("name"); + use.push_back(millisSince(began)); + began = Clock::now(); + h.owner.runAll(); + useSettled.push_back(millisSince(began)); + began = Clock::now(); + REQUIRE(h.engine.setSort({{.column = "name", .dir = morph::table::SortDirection::Ascending}})); + h.owner.runAll(); + sort.push_back(millisSince(began)); + auto const first = std::get(h.engine.rowIdAt(0)); + ui::ValueList const next = renamed(rows, static_cast(first - 1)); + began = Clock::now(); + h.source->assign(next); + assign.push_back(millisSince(began)); + began = Clock::now(); + h.owner.runAll(); + repair.push_back(millisSince(began)); + REQUIRE(std::get(h.engine.rowIdAt(kRows - 1)) == first); + } + printRow("U1 split: use(name), the source deriving the column's cells", kRows, spreadOf(use)); + printRow("U1 split: the engine absorbing the new column (no sort yet)", kRows, spreadOf(useSettled)); + printRow("U1 split: setSort(name) to settled", kRows, spreadOf(sort)); + printRow("U2 split: assign of the list with one row renamed, the source matching it", kRows, spreadOf(assign)); + printRow("U2 split: the engine absorbing and repairing it", kRows, spreadOf(repair)); +} + +// D7: the Shift-click that adds a third key to a settled two-key sort of 100,000 document rows, click to settled. +// docs/spec/table/table.md, "Performance"; budget 50 ms. Run on a Release build: +// +// morph_tests "interpreter bench: a third sort key on 100,000 rows" +TEST_CASE("interpreter bench: a third sort key on 100,000 rows", "[.benchmark][interpreter]") { + constexpr std::size_t kRows = 100'000; + std::string items; + for (std::size_t i = 0; i < kRows; ++i) { + items += std::format(R"({}{{"id":{},"a":{},"b":{},"c":{}}})", i == 0 ? "" : ",", i, i % 7, i % 13, i % 101); + } + std::string const document = std::format(R"({{ + "vocab": "ui/1", "id": "chain", + "state": {{ "items": {{ "init": {{ "lit": [{}] }} }} }}, + "view": {{ "kind": "table", "id": "t", "rows": {{ "ref": "items" }}, + "columns": [ {{ "id": "a", "label": "A", "sortable": true }}, {{ "id": "b", "label": "B", "sortable": true }}, + {{ "id": "c", "label": "C", "sortable": true }} ] }} }})", + items); + Harness h; + auto const screen = h.mount(document); + int const table = h.backend.all("Table").front(); + h.backend.clickHeader(table, 0, ui::HeaderClick::Plain); + h.backend.clickHeader(table, 1, ui::HeaderClick::Shift); + h.settle(); + REQUIRE(h.backend.prop(table, "sort") == "0:Ascending,1:Ascending"); + std::println( + "\nD7: a third sort key added from the header to a two-key sort of 100,000 rows, click to settled\n\n" + "| scenario | rows | median ms | p10-p90 ms |\n|---|---:|---:|---:|"); + std::vector adds; + for (int run = 0; run < 7; ++run) { + auto const began = Clock::now(); + h.backend.clickHeader(table, 2, ui::HeaderClick::Shift); + h.settle(); + adds.push_back(millisSince(began)); + REQUIRE(h.backend.prop(table, "sort") == "0:Ascending,1:Ascending,2:Ascending"); + h.backend.chooseMenu(table, 2, {"Remove from sort"}); // untimed: back to two keys + h.settle(); + REQUIRE(h.backend.prop(table, "sort") == "0:Ascending,1:Ascending"); + } + printRow("D7: Shift-click a third key, click to settled", kRows, spreadOf(adds)); +} diff --git a/tests/forms/test_forms_derive.cpp b/tests/forms/test_forms_derive.cpp new file mode 100644 index 000000000..65e13eb9d --- /dev/null +++ b/tests/forms/test_forms_derive.cpp @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Derived values on the server: computed members of row types recomputed on every path, derived members cleared +// before the model runs, and both written into the schema (docs/spec/table/editing.md, "Derived values", delivery +// step 2). + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../test_support.hpp" + +struct DeriveBox { + std::int64_t count = 0; + std::int64_t perBox = 0; + std::int64_t total = 0; // computed: count * perBox + std::int64_t limit = 0; // derived: the model's + static constexpr auto computedFields = + morph::forms::computeList(morph::forms::computed<&DeriveBox::total, &DeriveBox::count, &DeriveBox::perBox>( + [](auto const& box) { return box.count * box.perBox; })); + static const std::array fieldMetadata; +}; +inline const std::array DeriveBox::fieldMetadata{ + morph::forms::derived<&DeriveBox::limit>()}; + +struct RecordBoxes { + std::vector boxes; + std::int64_t sum = 0; // computed: the boxes' totals + static constexpr auto computedFields = morph::forms::computeList( + morph::forms::computed<&RecordBoxes::sum, &RecordBoxes::boxes>([](auto const& record) { + std::int64_t s = 0; + for (auto const& b : record.boxes) { + s += b.total; + } + return s; + })); +}; +struct DeriveBoxModel { + static inline RecordBoxes last{}; + bool execute(RecordBoxes const& record) { + last = record; + return true; + } // sets no derived member +}; +BRIDGE_REGISTER_MODEL(DeriveBoxModel, "T_DeriveBoxes") +BRIDGE_REGISTER_ACTION(DeriveBoxModel, RecordBoxes, "T_RecordBoxes") + +// A nested struct, plain and optional, with its own computed and derived members. +struct DeriveLid { + std::int64_t width = 0; + std::int64_t area = 0; // computed: width * width + std::int64_t mark = 0; // derived: the model's + static constexpr auto computedFields = + morph::forms::computeList(morph::forms::computed<&DeriveLid::area, &DeriveLid::width>( + [](auto const& lid) { return lid.width * lid.width; })); + static const std::array fieldMetadata; +}; +inline const std::array DeriveLid::fieldMetadata{ + morph::forms::derived<&DeriveLid::mark>()}; + +struct RecordCrate { + DeriveLid lid; + std::optional spare; + std::optional> extras; + std::int64_t lidArea = 0; // computed: the lid's area, read recomputed + static constexpr auto computedFields = + morph::forms::computeList(morph::forms::computed<&RecordCrate::lidArea, &RecordCrate::lid>( + [](auto const& crate) { return crate.lid.area; })); +}; +struct DeriveCrateModel { + static inline RecordCrate last{}; + bool execute(RecordCrate const& crate) { + last = crate; + return true; + } +}; +BRIDGE_REGISTER_MODEL(DeriveCrateModel, "T_DeriveCrates") +BRIDGE_REGISTER_ACTION(DeriveCrateModel, RecordCrate, "T_RecordCrate") + +// A derived member with a floor, under a validator that checks declared bounds: the floor is the model's value's. +struct BoundedPick { + std::int64_t count = 0; + std::int64_t limit = 0; // derived, at least 1 once the model sets it + static const std::array fieldMetadata; + [[nodiscard]] bool validate() const { return morph::forms::allFieldBoundsSatisfied(*this); } +}; +inline const std::array BoundedPick::fieldMetadata{ + morph::forms::derived<&BoundedPick::limit>().withMinimum(morph::math::Rational{1, morph::math::DecimalPlaces{0}})}; +struct BoundedPickModel { + static inline BoundedPick last{}; + bool execute(BoundedPick const& pick) { + last = pick; + return true; + } +}; +BRIDGE_REGISTER_MODEL(BoundedPickModel, "T_BoundedPicks") +BRIDGE_REGISTER_ACTION(BoundedPickModel, BoundedPick, "T_BoundedPick") + +// A const member beside a derived one: clearing reaches only what can be assigned. +struct ConstTagged { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members): the case needs a const member beside a derived one, to show that clearing reaches only what can be assigned + std::int64_t const kind = 7; + std::int64_t limit = 0; // derived + static const std::array fieldMetadata; +}; +inline const std::array ConstTagged::fieldMetadata{ + morph::forms::derived<&ConstTagged::limit>()}; + +namespace { + +constexpr std::string_view kForged = R"({"boxes":[{"count":2,"perBox":3,"total":999,"limit":555}],"sum":999})"; + +// Mutation: recomputeAll skipping row members (total stays 999, sum 999); a second run with clearDerived removed +// from prepareAction (limit stays 555). +TEST_CASE("derive: the server keeps recomputeAll's values and the model's", "[forms][derive]") { + auto holder = morph::model::detail::defaultRegistry().create("T_DeriveBoxes"); + morph::model::detail::defaultDispatcher().dispatch("T_DeriveBoxes", "T_RecordBoxes", *holder, kForged); + RecordBoxes const& kept = DeriveBoxModel::last; + CHECK(kept.boxes.at(0).total == 6); + CHECK(kept.sum == 6); + CHECK(kept.boxes.at(0).limit == 0); // the client's 555 is cleared; the model set nothing + auto const evaluated = + morph::model::detail::defaultDispatcher().evaluate("T_DeriveBoxes", "T_RecordBoxes", kForged); + CHECK(evaluated.body == R"({"boxes":[{"count":2,"perBox":3,"total":6,"limit":0}],"sum":6})"); +} + +// Mutation: annotateNestedAggregate not writing x-computed for a row type. +TEST_CASE("derive: a row type's schema marks computed and derived members", "[forms][derive]") { + auto dom = glz::read_json(morph::forms::schemaJson()).value(); + auto& box = dom["properties"]["boxes"]["items"]; // DeriveBox is used once: glaze inlines it + CHECK(glz::write_json(box["properties"]["total"]["x-readonly"]).value() == "true"); + CHECK(glz::write_json(box["properties"]["total"]["x-computed"]["inputs"]).value() == R"(["count","perBox"])"); + CHECK(glz::write_json(box["properties"]["limit"]["x-derived"]).value() == "true"); + CHECK(glz::write_json(box["required"]).value() == R"(["count","perBox"])"); +} + +// Mutations: detail::forEachNested skipping a plain nested struct member (lid.area stays 999, lid.mark 555, lidArea +// 999); skipping the elements of an engaged `std::optional` (extras' area stays 999, mark 555). +TEST_CASE("derive: the server recomputes and clears a nested struct's members", "[forms][derive]") { + auto holder = morph::model::detail::defaultRegistry().create("T_DeriveCrates"); + morph::model::detail::defaultDispatcher().dispatch( + "T_DeriveCrates", "T_RecordCrate", *holder, + R"({"lid":{"width":3,"area":999,"mark":555},"spare":{"width":2,"area":999,"mark":555},)" + R"("extras":[{"width":5,"area":999,"mark":555}],"lidArea":999})"); + RecordCrate const& kept = DeriveCrateModel::last; + CHECK(kept.lid.area == 9); + CHECK(kept.lid.mark == 0); + CHECK(kept.lidArea == 9); + REQUIRE(kept.spare.has_value()); + CHECK(kept.spare->area == 4); + CHECK(kept.spare->mark == 0); + REQUIRE(kept.extras.has_value()); + CHECK(kept.extras->at(0).area == 25); + CHECK(kept.extras->at(0).mark == 0); +} + +// A derive action's input is `{"body": …}`, through the meta its deriving type inherits. +struct DeriveRecordBoxes : morph::forms::DeriveOf {}; + +TEST_CASE("derive: a derive action's input and reply read and write as specified", "[forms][derive]") { + DeriveRecordBoxes input; + REQUIRE_FALSE(glz::read_json(input, std::string_view{R"({"body":{"boxes":[{"count":4}],"sum":0}})"})); + CHECK(input.body.boxes.at(0).count == 4); + morph::forms::Derived reply{.values = {{.path = "boxes[0].limit", .value = glz::raw_json{"7"}}}}; + CHECK(glz::write_json(reply).value() == R"({"values":[{"path":"boxes[0].limit","value":7}]})"); + RecordBoxes record{.boxes = {DeriveBox{.count = 1, .perBox = 1, .total = 1, .limit = 9}}, .sum = 1}; + morph::forms::clearDerived(record); + CHECK(record.boxes.at(0).limit == 0); + CHECK(record.boxes.at(0).total == 1); +} + +/// A LocalBackend bridge, as tests/test_action_validation.cpp builds it. +struct LocalDeriveRig { + morph::exec::ThreadPoolExecutor pool{2}; + morph::exec::MainThreadExecutor owner; + morph::bridge::Bridge bridge{std::make_unique(pool), owner}; +}; + +// Mutations: clearDerived removed from localOp (limit stays 555 through execute); removed from the executeJson gate +// and from localOp both (limit stays 555 through executeJson). +TEST_CASE("derive: the in-process paths clear a derived member as the server does", "[forms][derive]") { + LocalDeriveRig rig; + morph::bridge::BridgeHandler boxes{rig.bridge, &rig.owner}; + DeriveBoxModel::last = {}; + RecordBoxes const forged{.boxes = {DeriveBox{.count = 2, .perBox = 3, .total = 999, .limit = 555}}, .sum = 999}; + static_cast(morph::testing::awaitValueOn(rig.owner, boxes.execute(forged))); + CHECK(DeriveBoxModel::last.boxes.at(0).total == 6); + CHECK(DeriveBoxModel::last.boxes.at(0).limit == 0); + DeriveBoxModel::last = {}; + static_cast(morph::testing::awaitValueOn(rig.owner, boxes.executeJson("T_RecordBoxes", kForged))); + CHECK(DeriveBoxModel::last.boxes.at(0).total == 6); + CHECK(DeriveBoxModel::last.boxes.at(0).limit == 0); +} + +// Mutations: the `meta->derived` skip removed from allFieldBoundsSatisfied (the dispatch is refused); removed from +// field_errors' outOfBounds (limit is reported out of bounds). +TEST_CASE("derive: a derived member's bound does not refuse the action before the model sets it", "[forms][derive]") { + BoundedPickModel::last = {}; + auto holder = morph::model::detail::defaultRegistry().create("T_BoundedPicks"); + morph::model::detail::defaultDispatcher().dispatch("T_BoundedPicks", "T_BoundedPick", *holder, + R"({"count":3,"limit":5})"); + CHECK(BoundedPickModel::last.count == 3); + CHECK(BoundedPickModel::last.limit == 0); + CHECK(morph::forms::fieldErrors(BoundedPick{.count = 3, .limit = 0}).empty()); +} + +// Compiles only while clearDerived tests the member reference's own assignability. +TEST_CASE("derive: clearing skips a const member and clears the derived one", "[forms][derive]") { + ConstTagged tagged{.kind = 7, .limit = 4}; + morph::forms::clearDerived(tagged); + CHECK(tagged.kind == 7); + CHECK(tagged.limit == 0); +} + +} // namespace diff --git a/tests/grid_test_support.hpp b/tests/grid_test_support.hpp new file mode 100644 index 000000000..1cb33cea3 --- /dev/null +++ b/tests/grid_test_support.hpp @@ -0,0 +1,626 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +/// @file grid_test_support.hpp +/// @brief The grids' fixtures: a form whose `specimens` rows are entered in a grid, helpers over a cell's menu, and a +/// model's table as a grid over rows the test holds. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "forms_engine_support.hpp" +#include "table/row_commits.hpp" + +namespace morph::test::grid { + +// A form whose `specimens` rows are entered in a grid. `density` is computed, `limit` derived and read-only. +// `reviewer` freezes the grid by rule. +inline constexpr std::string_view kSpecimens = R"({"type":"object","title":"Specimens","properties":{ + "sampleId":{"type":"integer","title":"Sample","x-order":0}, + "reviewer":{"type":["string","null"],"title":"Reviewer","x-order":1}, + "specimens":{"type":"array","title":"Specimens","x-order":2,"minItems":0,"maxItems":5, + "items":{"type":"object","properties":{ + "label":{"type":["string","null"],"title":"Label","x-order":0}, + "mass":{"type":["object","null"],"title":"Mass","x-decimalPlaces":2,"x-order":1}, + "volume":{"type":["object","null"],"title":"Volume","x-decimalPlaces":1,"x-order":2}, + "density":{"type":["object","null"],"title":"Density","x-decimalPlaces":3,"x-readonly":true, + "x-computed":{"inputs":["mass","volume"]},"x-order":3}, + "limit":{"type":["object","null"],"title":"Limit","x-decimalPlaces":2,"x-readonly":true,"x-derived":true, + "x-order":4}, + "note":{"type":["string","null"],"title":"Note","x-order":5}}}}}, + "required":["sampleId"], + "x-rules":[{"kind":"readonlyWhen","fields":["specimens"],"when":{"kind":"engaged","fields":["reviewer"]}}]})"; + +// A grid of any form: its schema, what it is prefilled with, its collection, its columns (empty: one per member of the +// row type, in schema order) and its options. +struct GridSpec { + std::string schema; + std::string body; + std::string array = "specimens"; + std::vector columns; + ui::GridOptions options; +}; + +struct GridFixture { + morph::test::formsengine::Harness h; + reactive::testing::ManualScheduler scheduler; + // The evaluation and the derive call `enableDerive` routes rounds to; every call stays pending until resolved. + morph::test::formsengine::FakeServer evaluate{h.owner}; + morph::test::formsengine::FakeServer derive{h.owner}; + std::unique_ptr form; + std::unique_ptr source; + std::unique_ptr grid; + // Loads `rows` blank rows (keys 1..rows) with sampleId 1, in a comma locale, columns in schema order. + explicit GridFixture(std::size_t rows, ui::GridOptions options = {}, std::string schema = std::string{kSpecimens}); + // Loads a grid of any form, in a comma locale. + explicit GridFixture(GridSpec spec); + [[nodiscard]] std::string json(std::string_view path) const; // the field's encoded JSON, "" when none + // Rounds of derived values over `evaluate` and `derive`, on `scheduler`, with the default debounce of 150 ms. + void enableDerive(); +}; +// `kSpecimens` with a Boolean member `checked` and an enumerated member `unit` (g or kg) after `note`. +inline std::string specimensWithChoices() { + std::string schema{kSpecimens}; + std::string_view const note = R"("note":{"type":["string","null"],"title":"Note","x-order":5})"; + schema.replace(schema.find(note), note.size(), + std::string{note} + R"(,"checked":{"type":"boolean","title":"Checked","x-order":6},)" + + R"("unit":{"enum":["g","kg",null],"title":"Unit","x-order":7})"); + return schema; +} + +// Rows whose `value` column edits `choice` or `amount` by the row's `isChoice`, and whose `mass` takes one place in +// row 1 and three in row 2 (`kindPerRowColumns`). +inline constexpr std::string_view kKindPerRow = R"({"type":"object","title":"Rows","properties":{ + "rows":{"type":"array","title":"Rows","x-order":0,"items":{"type":"object","properties":{ + "isChoice":{"type":"boolean","title":"Is choice","x-order":0}, + "choice":{"enum":["low","high",null],"title":"Choice","x-order":1}, + "amount":{"type":["object","null"],"title":"Amount","x-decimalPlaces":1,"x-order":2}, + "mass":{"type":["object","null"],"title":"Mass","x-decimalPlaces":2,"x-order":3}}}}}})"; + +// The columns over `kKindPerRow`: `value`, a member per row, and `mass`, with places per row. +inline std::vector kindPerRowColumns() { + std::vector columns; + columns.push_back(ui::GridColumn{ + .id = "value", .label = "Value", .field = {}, .value = {}, .fieldOf = [](forms::RowState const& row) { + return row.field("isChoice")->draft() == "true" ? std::string{"choice"} : std::string{"amount"}; + }}); + columns.push_back(ui::GridColumn{.id = "mass", + .label = "Mass", + .field = "mass", + .value = {}, + .fieldOf = {}, + .decimals = [](forms::RowState const& row) { + return std::optional{row.key() == 1 ? 1U : 3U}; + }}); + return columns; +} + +inline ui::CellRef at(std::int64_t key, std::string column) { + return ui::CellRef{.key = ui::Key{key}, .column = std::move(column)}; +} +// Every fetched key of the source's view, in view order. +inline std::vector keysOf(ui::GridSource const& source) { + std::vector keys; + for (std::size_t i = 0; i < source.rowCount(); ++i) { + if (auto key = source.keyAt(i)) { + keys.push_back(*key); + } + } + return keys; +} + +// Blank rows (keys 1..rows) with sampleId 1. +inline std::string blankSpecimens(std::size_t rows) { + std::string body = R"({"sampleId":1,"specimens":[)"; + for (std::size_t row = 0; row < rows; ++row) { + body += row == 0 ? "{}" : ",{}"; + } + return body + "]}"; +} + +inline GridFixture::GridFixture(std::size_t rows, ui::GridOptions options, std::string schema) + : GridFixture{GridSpec{.schema = std::move(schema), + .body = blankSpecimens(rows), + .array = "specimens", + .columns = {}, + .options = std::move(options)}} {} + +inline GridFixture::GridFixture(GridSpec spec) { + evaluate.replyWith([](morph::test::formsengine::Call const&) { return std::optional{}; }); + derive.replyWith([](morph::test::formsengine::Call const&) { return std::optional{}; }); + form = h.session("Lims_RecordSpecimens", spec.schema, + forms::FormSessionOptions{.locale = ui::localeFacts("de").numeric, .bcp47 = "de"}); + form->prefill(spec.body); + h.settle(); + std::vector columns = std::move(spec.columns); + if (columns.empty()) { + for (forms::FieldSpec const& member : form->field(spec.array).spec().children) { + columns.push_back( + ui::GridColumn{.id = member.name, .label = member.name, .field = member.name, .value = {}}); + } + } + source = std::make_unique( + *form, spec.array, std::move(columns), + ui::FormatContext{.locale = "de", .numeric = ui::withoutGrouping(ui::localeFacts("de").numeric)}); + if (spec.options.scheduler == nullptr) { + spec.options.scheduler = &scheduler; // the undo offer's hold + } + grid = std::make_unique(h.rt, *source, std::move(spec.options)); + source->onBeforeSubmit([controller = grid.get()] { controller->leave(); }); +} + +inline void GridFixture::enableDerive() { + form->deriveWith(forms::DeriveOptions{ + .evaluate = [this](std::string body) { return evaluate.submitter()("Lims_RecordSpecimens", std::move(body)); }, + .derive = [this](std::string body) { return derive.submitter()("Lims_DeriveSpecimens", std::move(body)); }, + .scheduler = &scheduler, + .debounce = std::chrono::milliseconds{150}, + .refused = {}}); +} + +inline std::string GridFixture::json(std::string_view path) const { + forms::Encoding const& encoding = form->field(path).encoded().get(); + return encoding.has_value() && encoding->has_value() ? (*encoding)->json : std::string{}; +} + +// A form of limits laid out as a fixed grid: `density` and `moisture` each a minimum and a maximum (three and one +// places), `method` a choice of A or B, `count` an integer, `weight` a quantity in kg or g, `limit` a derived quantity +// in kg or g, and `specimens` rows of a `mass` (two places). +inline constexpr std::string_view kSetLimits = R"({"type":"object","title":"Limits","properties":{ + "limits":{"type":"object","title":"Limits","x-order":0,"properties":{ + "density":{"type":"object","title":"Density","x-order":0,"properties":{ + "min":{"type":["object","null"],"title":"Min","x-decimalPlaces":3,"x-order":0}, + "max":{"type":["object","null"],"title":"Max","x-decimalPlaces":3,"x-order":1}}}, + "moisture":{"type":"object","title":"Moisture","x-order":1,"properties":{ + "min":{"type":["object","null"],"title":"Min","x-decimalPlaces":1,"x-order":0}, + "max":{"type":["object","null"],"title":"Max","x-decimalPlaces":1,"x-order":1}}}, + "method":{"enum":["A","B"],"title":"Method","x-order":2}, + "count":{"type":["integer","null"],"title":"Count","x-order":3}, + "weight":{"type":["object","null"],"title":"Weight","x-decimalPlaces":3, + "ExtUnits":{"unitAscii":"kg","unitUnicode":"kg"}, + "x-unitAlternatives":[{"id":"g","display":"g","decimals":1,"num":1,"den":1000}],"x-order":4}, + "limit":{"type":["object","null"],"title":"Limit","x-decimalPlaces":3,"x-readonly":true,"x-derived":true, + "ExtUnits":{"unitAscii":"kg","unitUnicode":"kg"}, + "x-unitAlternatives":[{"id":"g","display":"g","decimals":1,"num":1,"den":1000}],"x-order":5}}}, + "specimens":{"type":"array","title":"Specimens","x-order":1,"items":{"type":"object","properties":{ + "mass":{"type":["object","null"],"title":"Mass","x-decimalPlaces":2,"x-order":0}}}}}})"; + +// A fixed grid over the Lims_SetLimits form: columns `min`, `max` (and `v` for the block case), in a comma locale. +struct FixedGridFixture { + morph::test::formsengine::Harness h; + std::unique_ptr form; + std::unique_ptr source; + std::unique_ptr grid; + // Prefills `body`, builds the source over `rows` and `columns` and the controller with default options. + FixedGridFixture(std::string_view body, std::vector> rows, + std::vector columns); + [[nodiscard]] std::string json(std::string_view path) const; +}; + +inline FixedGridFixture::FixedGridFixture(std::string_view body, + std::vector> rows, + std::vector columns) { + form = h.session("Lims_SetLimits", kSetLimits, + forms::FormSessionOptions{.locale = ui::localeFacts("de").numeric, .bcp47 = "de"}); + form->prefill(body); + h.settle(); + source = std::make_unique( + h.rt, form.get(), std::move(rows), std::move(columns), + ui::FormatContext{.locale = "de", .numeric = ui::withoutGrouping(ui::localeFacts("de").numeric)}); + grid = std::make_unique(h.rt, *source, ui::GridOptions{}); +} + +inline std::string FixedGridFixture::json(std::string_view path) const { + forms::Encoding const& encoding = form->field(path).encoded().get(); + return encoding.has_value() && encoding->has_value() ? (*encoding)->json : std::string{}; +} + +// A fixed cell editing a field. +inline ui::FixedCell fieldCell(std::string path, std::size_t columns = 1) { + ui::FixedCell cell; + cell.field = std::move(path); + cell.columns = columns; + return cell; +} + +// A fixed cell showing a literal text. +inline ui::FixedCell textCell(std::string text) { + ui::FixedCell cell; + cell.text = std::move(text); + return cell; +} + +// One table column per member of the row type, in schema order, its id and label the member's name. +inline std::vector columnsOf(GridFixture const& f) { + std::vector columns; + for (forms::FieldSpec const& member : f.form->field("specimens").spec().children) { + columns.push_back(ui::TableColumn{.id = member.name, .label = member.name}); + } + return columns; +} + +// Each entry's label, as bound now. +inline std::vector labelsOf(std::vector const& items) { + std::vector labels; + for (ui::MenuItem const& item : items) { + // NOLINTNEXTLINE(performance-inefficient-vector-operation): `labels` is a fixture list built once; sizing it first would not change what the case checks + labels.push_back(item.label.evaluate()); + } + return labels; +} + +// The entry with a label; it must exist. +inline ui::MenuItem const& entry(std::vector const& items, std::string_view label) { + auto const found = + std::ranges::find_if(items, [label](ui::MenuItem const& item) { return item.label.evaluate() == label; }); + REQUIRE(found != items.end()); + return *found; +} + +// Whether an entry is enabled, as bound now. +inline bool enabledOf(ui::MenuItem const& item) { return item.enabled.evaluate(); } + +// An entry's description, as bound now. +inline std::string descriptionOf(ui::MenuItem const& item) { return item.description.evaluate(); } + +// ── Cells of a model's table ──────────────────────────────────────────────── + +// Rows of a model's table held by the test: a view of keys, some not fetched, with states, locks and unloaded levels. +class FakeRows final : public ui::TableRows { +public: + struct Row { + table::RowId key; + ui::Value record; + bool fetched = true; + std::set unloaded; // the levels the row has not loaded + }; + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes): the fake source's view, row states and recorded moves, which the cases arrange and read directly + std::vector view; // in view order + ui::RowStates rowStates; + std::vector> moved; // moveKey's calls + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes) + + // Marks the row fetched; reports it changed. + void deliver(std::size_t index) { + view.at(index).fetched = true; + announce({table::ViewOp{.kind = table::ViewOp::Kind::Changed, .first = index, .count = 1, .to = 0}}); + } + // The view in this order; reports the moves. + void reorder(std::vector const& keys) { + std::vector ops; + for (std::size_t to = 0; to < keys.size(); ++to) { + auto const at = std::ranges::find(view, keys.at(to), &Row::key); + auto const from = static_cast(at - view.begin()); + if (from == to) { + continue; + } + Row row = std::move(*at); + view.erase(at); + view.insert(view.begin() + static_cast(to), std::move(row)); + ops.push_back(table::ViewOp{.kind = table::ViewOp::Kind::Moved, .first = from, .count = 1, .to = to}); + } + announce(std::move(ops)); + } + // Out of the view; `restore` puts it back. + Row drop(table::RowId const& key) { + auto const at = std::ranges::find(view, key, &Row::key); + auto const index = static_cast(at - view.begin()); + Row row = std::move(*at); + view.erase(at); + announce({table::ViewOp{.kind = table::ViewOp::Kind::Removed, .first = index, .count = 1, .to = 0}}); + return row; + } + void restore(Row row, std::size_t index) { + view.insert(view.begin() + static_cast(index), std::move(row)); + announce({table::ViewOp{.kind = table::ViewOp::Kind::Inserted, .first = index, .count = 1, .to = 0}}); + } + // Replaces the record; reports it changed. + void refetch(table::RowId const& key, ui::Value record) { + auto const at = std::ranges::find(view, key, &Row::key); + at->record = std::move(record); + at->fetched = true; + auto const index = static_cast(at - view.begin()); + announce({table::ViewOp{.kind = table::ViewOp::Kind::Changed, .first = index, .count = 1, .to = 0}}); + } + [[nodiscard]] std::size_t handlers() const { return _handlerSets; } // how often onChange was set + // Gives a row a new key; reports it changed. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `rekey(from, to)` is a test helper whose arguments read differently at each call; a swap would fail the case's own assertion + void rekey(table::RowId const& from, table::RowId const& to) { + auto const at = std::ranges::find(view, from, &Row::key); + at->key = to; + ui::ValueRecord record = *at->record.asRecord(); + record.insert_or_assign("key", std::visit([](auto const& value) { return ui::Value{value}; }, to)); + at->record = ui::Value{std::move(record)}; + auto const index = static_cast(at - view.begin()); + announce({table::ViewOp{.kind = table::ViewOp::Kind::Changed, .first = index, .count = 1, .to = 0}}); + } + // Reports a change of several operations, as an engine's view change is. + void announceChange(std::vector ops) { announce(std::move(ops)); } + // Reports the whole view replaced, as a new query does. + void reset() { announce({table::ViewOp{.kind = table::ViewOp::Kind::Reset, .first = 0, .count = 0, .to = 0}}); } + // Answers every `locateRow` asked so far with the key's place in `view`, fetched or not. + void answerLocates() { + auto asked = std::exchange(_locates, {}); + for (auto& [key, done] : asked) { + auto const at = std::ranges::find(view, key, &Row::key); + // Assigned, not cast: the iterator difference is `std::ptrdiff_t`, which is `std::int64_t` only on some + // targets. + std::int64_t const index = at - view.begin(); + done(at == view.end() ? ui::RowLocation{std::nullopt} : ui::RowLocation{index}); + } + } + [[nodiscard]] std::size_t locatesAsked() const { return _locates.size(); } + // Rows past `view` the total counts and nothing holds: a large view's window. + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes): the fake source's unheld-row count and read counter, which the cases set and read directly + std::int64_t unheld = 0; + // How often `row` was read, and at which indices, in order. + mutable std::size_t rowReads = 0; + mutable std::vector readIndices; + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes) + + [[nodiscard]] ui::TableTotal total() const override { + return { + .rows = static_cast(view.size()) + unheld, .kind = table::TotalKind::Exact, .known = true}; + } + [[nodiscard]] std::vector> heldRanges() const override { + return {{0, static_cast(view.size())}}; + } + [[nodiscard]] std::optional row(std::int64_t index) const override { + ++rowReads; + readIndices.push_back(index); + if (index < 0 || static_cast(index) >= view.size()) { + return std::nullopt; + } + Row const& held = view.at(static_cast(index)); + if (!held.fetched) { + return std::nullopt; + } + return ui::TableRowRef{.key = held.key, .row = held.record}; + } + [[nodiscard]] table::UnloadedLevels unloadedLevels(std::int64_t index) const override { + if (index < 0 || static_cast(index) >= view.size()) { + return {}; + } + _levels.assign(view.at(static_cast(index)).unloaded.begin(), + view.at(static_cast(index)).unloaded.end()); + return table::UnloadedLevels{.levels = _levels, .failed = {}}; + } + void visible(std::int64_t, std::int64_t, std::span) override {} + async::Completion, table::TableError>> keysOf(std::int64_t, + std::int64_t) override { + return async::Completion, table::TableError>>::makeSettleable(nullptr) + .first; + } + void locateRow(table::RowId key, ::core::async::StopToken, + std::function done) override { + _locates.emplace_back(std::move(key), std::move(done)); + } + async::Completion, table::TableError>> fetchRows( + std::vector, std::vector) override { + return async::Completion, table::TableError>>::makeSettleable( + nullptr) + .first; + } + std::expected setSort(ui::SortChain) override { return {}; } + std::expected setFilter(table::FilterSpec) override { return {}; } + async::Completion> distinctValues( + table::DistinctRequest) override { + return async::Completion>::makeSettleable(nullptr) + .first; + } + [[nodiscard]] ui::TableCountsView counts() const override { return ui::TableCountsView{.view = total()}; } + [[nodiscard]] ui::RowStates& states() override { return rowStates; } + [[nodiscard]] ui::RowStates const& states() const override { return rowStates; } + void moveKey(table::RowId const& from, table::RowId const& to) override { moved.emplace_back(from, to); } + void onChange(std::function handler) override { + _handler = std::move(handler); + ++_handlerSets; + } + +private: + void announce(std::vector ops) { + if (_handler && !ops.empty()) { + _handler(table::ViewChange{.ops = std::move(ops)}); + } + } + std::function _handler; + std::size_t _handlerSets = 0; + mutable std::vector _levels; + std::vector>> _locates; +}; + +// The edit actions of the model table's cases: a count by `CellEdit`, a label and a remark by `RowEdit`. +inline constexpr std::string_view kEditSpecimenCount = + R"({"type":"object","x-cellEditOf":"Lims_SampleModel.samples","properties":{"key":{"type":"integer"},)" + R"("value":{"type":"integer","maximum":10}},"required":["key","value"]})"; +inline constexpr std::string_view kEditSpecimenRow = + R"({"type":"object","x-rowEditOf":"Lims_SampleModel.samples","properties":{"key":{"type":"integer"},)" + R"("values":{"type":"object","properties":{"label":{"type":["string","null"]},)" + R"("remarkText":{"type":["string","null"]},"sampled":{"type":["string","null"],"format":"date"},)" + R"("taken":{"type":["string","null"],"format":"date-time"},)" + R"("day":{"type":["integer","null"],"x-widget":"epochDays"},)" + R"("at":{"type":["integer","null"],"x-widget":"epochSeconds"},)" + R"("mass":{"type":["object","null"],"x-decimalPlaces":2},)" + R"("weight":{"type":["object","null"],"x-decimalPlaces":3,"ExtUnits":{"unitAscii":"kg","unitUnicode":"kg"},)" + R"("x-unitAlternatives":[{"id":"g","display":"g","decimals":1,"num":1,"den":1000}]}}}},"required":["key"]})"; + +// The description of the model table's cases: `key` (the key), `label` and `remark` (Text, `Lims_EditSpecimenRow`'s +// `label` and `remarkText`), `count` (Integer of level `counts`, `Lims_EditSpecimenCount`, frozen by `countFrozen`), +// `note` (Text, no edit), and the companions `countFrozen` and `lockedBy`, the row's lock. +inline table::TableDescription specimenTableDescription() { + table::TableDescription d; + d.id = "samples"; + d.label = "Samples"; + d.key = "key"; + auto const add = [&d](std::string id, table::ColumnKind kind, std::optional edit = {}, + std::string level = {}) { + table::TableColumn column; + column.info = table::ColumnInfo{.id = std::move(id), .kind = kind}; + column.info.level = std::move(level); + column.label = column.info.id; + column.edit = std::move(edit); + d.columns.push_back(std::move(column)); + }; + add("key", table::ColumnKind::Integer); + add("label", table::ColumnKind::Text, table::EditInfo{.action = "Lims_EditSpecimenRow", .member = "label"}); + add("remark", table::ColumnKind::Text, table::EditInfo{.action = "Lims_EditSpecimenRow", .member = "remarkText"}); + add("count", table::ColumnKind::Integer, + table::EditInfo{.action = "Lims_EditSpecimenCount", .member = {}, .readonly = "countFrozen"}, "counts"); + add("note", table::ColumnKind::Text); + add("countFrozen", table::ColumnKind::Bool); + add("lockedBy", table::ColumnKind::Text); + // One column per kind a row's member edits: a date and a date-time as the forms' own fields and as epoch counts, + // and a decimal. + add("sampled", table::ColumnKind::Date, table::EditInfo{.action = "Lims_EditSpecimenRow", .member = "sampled"}); + add("taken", table::ColumnKind::DateTime, table::EditInfo{.action = "Lims_EditSpecimenRow", .member = "taken"}); + add("day", table::ColumnKind::Date, table::EditInfo{.action = "Lims_EditSpecimenRow", .member = "day"}); + add("at", table::ColumnKind::DateTime, table::EditInfo{.action = "Lims_EditSpecimenRow", .member = "at"}); + add("mass", table::ColumnKind::Decimal, table::EditInfo{.action = "Lims_EditSpecimenRow", .member = "mass"}); + // A measure, each cell in its own unit of mass: the field's value is in kg. + add("weight", table::ColumnKind::Measure, table::EditInfo{.action = "Lims_EditSpecimenRow", .member = "weight"}); + d.units = { + table::UnitInfo{.id = "kg", + .symbol = "kg", + .dimension = "mass", + .toBase = morph::math::Rational{morph::math::Numerator{1}, morph::math::Denominator{1}, + morph::math::DecimalPlaces{0}}, + .decimals = 3}, + table::UnitInfo{.id = "g", + .symbol = "g", + .dimension = "mass", + .toBase = morph::math::Rational{morph::math::Numerator{1}, morph::math::Denominator{1000}, + morph::math::DecimalPlaces{3}}, + .decimals = 1}, + table::UnitInfo{.id = "percent", + .symbol = "%", + .dimension = "ratio", + .toBase = morph::math::Rational{morph::math::Numerator{1}, morph::math::Denominator{100}, + morph::math::DecimalPlaces{2}}, + .decimals = 1}}; + d.rowLock = "lockedBy"; + return table::describe(std::move(d)); +} + +// A row of the model table's cases: label `L`, remark `R`, count the key, note `n`, not frozen, not locked. +inline ui::Value specimenRecord(std::int64_t key, std::int64_t count = -1) { + ui::ValueRecord record; + record.insert_or_assign("key", ui::Value{key}); + record.insert_or_assign("label", ui::Value{"L" + std::to_string(key)}); + record.insert_or_assign("remark", ui::Value{"R" + std::to_string(key)}); + record.insert_or_assign("count", ui::Value{count < 0 ? key : count}); + record.insert_or_assign("note", ui::Value{std::string{"n"}}); + record.insert_or_assign("countFrozen", ui::Value{false}); + record.insert_or_assign("lockedBy", ui::Value{std::string{}}); + // As the window holds them: a `Date` cell as `YYYY-MM-DD`, a `DateTime` cell as a timestamp, a decimal exact. + ui::Value const instant{morph::time::DateTime::fromIso8601("2026-11-20T10:30:00Z").value()}; + record.insert_or_assign("sampled", ui::Value{std::string{"2026-11-20"}}); + record.insert_or_assign("taken", instant); + record.insert_or_assign("day", ui::Value{std::string{"2026-11-20"}}); + record.insert_or_assign("at", instant); + record.insert_or_assign("mass", ui::Value{ui::Decimal{table::parseDecimal("12.50").value()}}); + record.insert_or_assign("weight", + ui::Value{ui::Quantity{.value = table::parseDecimal("200").value(), .unit = "g"}}); + return ui::Value{std::move(record)}; +} + +// Sets a field of a held row's record. +inline void setField(FakeRows& rows, std::int64_t key, std::string const& field, ui::Value value) { + auto const at = std::ranges::find(rows.view, table::RowId{key}, &FakeRows::Row::key); + REQUIRE(at != rows.view.end()); + ui::ValueRecord record = *at->record.asRecord(); + record.insert_or_assign(field, std::move(value)); + at->record = ui::Value{std::move(record)}; +} + +// A model's table as a grid over `FakeRows`: its columns `label`, `remark`, `count` and `note`, its edits sent to +// `commits`, its actions permitted while `permitted` names them. +struct ModelGridFixture { + morph::test::formsengine::Harness h; + std::shared_ptr rows = std::make_shared(); + RowCommits commits; + table::CellEdits edits{commits.commit()}; + std::set> permitted{"Lims_EditSpecimenCount", "Lims_EditSpecimenRow"}; + std::unique_ptr source; + std::unique_ptr grid; + // One fetched row per key, in that order. In `EditMode::Row` Enter moves along the row, so a row's cells are + // entered with Enter as with Tab. + explicit ModelGridFixture(std::vector const& keys, ui::EditMode mode = ui::EditMode::Cell); + // The table columns the grid shows, for a mount: one per grid column. + [[nodiscard]] static std::vector tableColumns(); +}; + +inline ModelGridFixture::ModelGridFixture(std::vector const& keys, ui::EditMode mode) { + for (std::int64_t const key : keys) { + rows->view.push_back( + FakeRows::Row{.key = table::RowId{key}, .record = specimenRecord(key), .fetched = true, .unloaded = {}}); + } + auto const count = std::make_shared( + morph::test::formsengine::modelOf("Lims_EditSpecimenCount", kEditSpecimenCount)); + auto const row = std::make_shared( + morph::test::formsengine::modelOf("Lims_EditSpecimenRow", kEditSpecimenRow)); + table::TableDescription const description = specimenTableDescription(); + auto const editOf = [&description](std::string_view id) { + auto const found = std::ranges::find_if( + description.columns, [id](table::TableColumn const& column) { return column.info.id == id; }); + return found->edit; + }; + std::vector columns; + columns.push_back(ui::ModelColumn{.id = "label", .edit = editOf("label"), .model = row, .path = "values.label"}); + columns.push_back( + ui::ModelColumn{.id = "remark", .edit = editOf("remark"), .model = row, .path = "values.remarkText"}); + columns.push_back(ui::ModelColumn{.id = "count", .edit = editOf("count"), .model = count, .path = "value"}); + columns.push_back(ui::ModelColumn{.id = "note", .edit = std::nullopt, .model = nullptr, .path = {}}); + for (std::string const member : {"sampled", "taken", "day", "at", "mass", "weight"}) { + columns.push_back( + ui::ModelColumn{.id = member, .edit = editOf(member), .model = row, .path = "values." + member}); + } + source = std::make_unique( + rows, edits, std::move(columns), mode, + ui::ModelGridContext{.runtime = &h.rt, + .choices = h.server.fetcher(), + .session = {}, + .format = ui::FormatContext{}, + .may = [this](std::string_view action) { return permitted.contains(action); }}); + source->setDescription(description); + ui::GridOptions options; + if (mode == ui::EditMode::Row) { + options.enterMoves = ui::EnterMoves::Right; + } + grid = std::make_unique(h.rt, *source, std::move(options)); +} + +inline std::vector ModelGridFixture::tableColumns() { + return {ui::TableColumn{.id = "label", .label = "label"}, ui::TableColumn{.id = "remark", .label = "remark"}, + ui::TableColumn{.id = "count", .label = "count"}, ui::TableColumn{.id = "note", .label = "note"}, + ui::TableColumn{.id = "sampled", .label = "sampled"}, ui::TableColumn{.id = "taken", .label = "taken"}, + ui::TableColumn{.id = "day", .label = "day"}, ui::TableColumn{.id = "at", .label = "at"}, + ui::TableColumn{.id = "mass", .label = "mass"}, ui::TableColumn{.id = "weight", .label = "weight"}}; +} + +// The value of a settled success, and of a refusal naming fields. +inline std::expected> committedOk() { return {}; } +inline std::expected> refusedWith(std::vector errors) { + return std::unexpected(std::move(errors)); +} + +} // namespace morph::test::grid diff --git a/tests/net/CMakeLists.txt b/tests/net/CMakeLists.txt index 741709959..231efcb05 100644 --- a/tests/net/CMakeLists.txt +++ b/tests/net/CMakeLists.txt @@ -9,12 +9,15 @@ add_executable(morph_net_tests test_socket_backend.cpp test_push_net.cpp test_push_two_clients.cpp + test_push_tables.cpp + test_push_unloaded_rows.cpp ) target_link_libraries(morph_net_tests PRIVATE morph::net morph_test_main + "$" ) apply_warnings(morph_net_tests) diff --git a/tests/net/test_push_tables.cpp b/tests/net/test_push_tables.cpp new file mode 100644 index 000000000..f612fe808 --- /dev/null +++ b/tests/net/test_push_tables.cpp @@ -0,0 +1,1613 @@ +// SPDX-License-Identifier: Apache-2.0 + +// A model's tables over the `net` transport (docs/spec/table/table.md, "A model's tables"): one server, two clients, +// each table a record of its own. Admission to a table's record follows the actions holding it; an action's changed +// rows reach the watchers of their own table; a page's columns are the caller's; and the reply is built on the +// server's table executor. +// +// The end of each case names the mutation it is meant to catch. These cases need a POSIX build, and none of +// those mutations has been run yet. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "table/wide_table_model.hpp" + +// NOLINTBEGIN(misc-use-internal-linkage): registered types must have external linkage. +namespace push_tables { + +// The threads a recorded read ran on, shared by the source and the test. +struct ReadThreads { + std::mutex mutex; + std::set threads; + + void note() { + std::scoped_lock const lock{mutex}; + threads.insert(std::this_thread::get_id()); + } + + std::set taken() { + std::scoped_lock const lock{mutex}; + return threads; + } + + void clear() { + std::scoped_lock const lock{mutex}; + threads.clear(); + } +}; + +inline ReadThreads& reads() { + static ReadThreads shared; + return shared; +} + +// A snapshot that records the thread of every read of a cell. +class RecordingSnapshot final : public morph::table::RowSnapshot { +public: + explicit RecordingSnapshot(std::shared_ptr inner) : _inner{std::move(inner)} {} + + [[nodiscard]] std::size_t rowCount() const override { return _inner->rowCount(); } + [[nodiscard]] morph::table::RowId rowId(std::size_t row) const override { return _inner->rowId(row); } + [[nodiscard]] morph::table::Cell cell(std::size_t row, std::size_t column) const override { + reads().note(); + return _inner->cell(row, column); + } + void readColumn(std::size_t column, morph::table::ColumnSink& sink, std::size_t first, + std::size_t last) const override { + reads().note(); + _inner->readColumn(column, sink, first, last); + } + +private: + std::shared_ptr _inner; +}; + +// A source whose snapshots record their reads. +class RecordingSource final : public morph::table::DataSource { +public: + explicit RecordingSource(std::shared_ptr inner) : _inner{std::move(inner)} {} + + [[nodiscard]] std::span columns() const override { return _inner->columns(); } + [[nodiscard]] std::shared_ptr snapshot() const override { + return std::make_shared(_inner->snapshot()); + } + void subscribe(morph::table::ChangeListener& /*listener*/) override {} + void unsubscribe(morph::table::ChangeListener& /*listener*/) override {} + +private: + std::shared_ptr _inner; +}; + +// The thread `PtModel::first` last ran on. +inline std::atomic& firstThread() { + static std::atomic id{}; + return id; +} + +struct EditFirst { + std::int64_t key = 0; +}; +struct EditSecond { + std::int64_t key = 0; +}; +struct EditBoth { + std::int64_t first = 0; + std::int64_t second = 0; +}; + +class PtModel; +struct EditBothResult; + +class PtModel { +public: + morph::table::ServedTable first(morph::table::TableContext const& context); + morph::table::ServedTable second(morph::table::TableContext const& context); + morph::table::ChangedRows<&PtModel::first> execute(EditFirst const& action); + morph::table::ChangedRows<&PtModel::second> execute(EditSecond const& action); + EditBothResult execute(EditBoth const& action); +}; + +struct EditBothResult { + morph::table::ChangedRows<&PtModel::first> first; + morph::table::ChangedRows<&PtModel::second> second; +}; + +} // namespace push_tables +// NOLINTEND(misc-use-internal-linkage) + +BRIDGE_REGISTER_MODEL(push_tables::PtModel, "PtModel") +BRIDGE_REGISTER_TABLE(push_tables::PtModel, "first", &push_tables::PtModel::first) +BRIDGE_REGISTER_TABLE(push_tables::PtModel, "second", &push_tables::PtModel::second) +BRIDGE_REGISTER_ACTION(push_tables::PtModel, push_tables::EditFirst, "EditFirst") +BRIDGE_REGISTER_ACTION(push_tables::PtModel, push_tables::EditSecond, "EditSecond") +BRIDGE_REGISTER_ACTION(push_tables::PtModel, push_tables::EditBoth, "EditBoth") +BRIDGE_REGISTER_EFFECTS(push_tables::EditFirst, morph::effects::updatesTable<&push_tables::PtModel::first>) +BRIDGE_REGISTER_EFFECTS(push_tables::EditSecond, morph::effects::updatesTable<&push_tables::PtModel::second>) +BRIDGE_REGISTER_EFFECTS(push_tables::EditBoth, morph::effects::updatesTable<&push_tables::PtModel::first>, + morph::effects::updatesTable<&push_tables::PtModel::second>) + +namespace push_tables { + +namespace { + +// A one-column table of `rows` integer rows keyed 1..rows, read through a recording source. +morph::table::ServedTable smallTable(std::string id, std::int64_t rows) { + morph::table::ServedTable served; + served.description.id = std::move(id); + served.description.label = served.description.id; + served.description.key = "v"; + served.description.columns.push_back(morph::table::TableColumn{ + .info = {.id = "v", .kind = morph::table::ColumnKind::Integer, .comparator = {}, .format = {}, .level = {}}, + .label = "V", + .group = {}}); + auto source = std::make_shared(morph::table::columnInfos(served.description)); + std::vector keys; + std::vector> cells; + for (std::int64_t row = 1; row <= rows; ++row) { + keys.emplace_back(row); + cells.push_back({morph::table::Cell{row}}); + } + source->setRows(std::move(keys), std::move(cells)); + served.source = std::make_shared(std::move(source)); + return served; +} + +} // namespace + +morph::table::ServedTable PtModel::first(morph::table::TableContext const& /*context*/) { + firstThread() = std::this_thread::get_id(); + return smallTable("first", 8); +} + +morph::table::ServedTable PtModel::second(morph::table::TableContext const& /*context*/) { + return smallTable("second", 8); +} + +morph::table::ChangedRows<&PtModel::first> PtModel::execute(EditFirst const& action) { + return {.rows = {morph::table::ChangedRow{.key = morph::table::RowId{action.key}}}}; +} + +morph::table::ChangedRows<&PtModel::second> PtModel::execute(EditSecond const& action) { + return {.rows = {morph::table::ChangedRow{.key = morph::table::RowId{action.key}}}}; +} + +EditBothResult PtModel::execute(EditBoth const& action) { + return {.first = {.rows = {morph::table::ChangedRow{.key = morph::table::RowId{action.first}}}}, + .second = {.rows = {morph::table::ChangedRow{.key = morph::table::RowId{action.second}}}}}; +} + +} // namespace push_tables + +namespace { + +using namespace std::chrono_literals; +namespace ui = morph::ui; + +constexpr std::string_view kHello = "t-tables-hello"; +constexpr auto kCoalesce = 20ms; + +// Negotiates events for the connection its hello arrives on, as the UI service's `ui-hello` does. +class Hello final : public morph::backend::IEnvelopeService { +public: + using IEnvelopeService::handle; + + [[nodiscard]] bool serves(std::string_view kind) const override { return kind == kHello; } + + [[nodiscard]] std::string handle(morph::wire::Envelope const& request, + morph::session::IAuthorizer const& /*authorizer*/) override { + return morph::wire::encode(morph::wire::makeOk(request.callId)); + } + + [[nodiscard]] std::string handle(morph::wire::Envelope const& request, + morph::session::IAuthorizer const& authorizer, + morph::backend::ConnectionFacts& facts) override { + facts.events = true; + return handle(request, authorizer); + } +}; + +// Takes the principal a client names as verified, refuses `bob` every action holding `PtModel.second`, and refuses +// `viewer` the edit action of `editnet::Specimens`. +class TablesAuthorizer final : public morph::session::IAuthorizer { +public: + [[nodiscard]] bool authorize(morph::session::Context const& ctx, std::string_view /*modelType*/, + std::string_view actionType) const override { + if (ctx.principal == "viewer") { + return actionType != "Lims_EditSpecimenCount"; + } + if (ctx.principal != "bob") { + return true; + } + return actionType != "Table.second" && actionType != "EditSecond" && actionType != "EditBoth"; + } + + [[nodiscard]] std::optional authenticate(morph::session::Context const& ctx) const override { + return ctx.principal; + } +}; + +// A pool that records the threads its tasks run on. +class RecordingPool final : public morph::exec::IExecutor { +public: + explicit RecordingPool(std::size_t threads = 2) : _pool{threads} {} + + void post(std::function task) override { + _pool.post([this, task = std::move(task)] { + { + std::scoped_lock const lock{_mutex}; + _threads.insert(std::this_thread::get_id()); + } + task(); + }); + } + + [[nodiscard]] bool isSerial() const noexcept override { return false; } + + std::set threads() { + std::scoped_lock const lock{_mutex}; + return _threads; + } + +private: + std::mutex _mutex; + std::set _threads; + morph::exec::ThreadPoolExecutor _pool; +}; + +// One server on a socket, with the tables authorizer. +struct Server { + explicit Server(std::shared_ptr tableWork = nullptr) { + morph::backend::ServerConfig config; + config.services.push_back(std::make_shared()); + config.coalesceWindow = kCoalesce; + config.tableWork = std::move(tableWork); + server = std::make_shared(pool, std::make_shared(), + std::move(config)); + socket = std::make_unique(*server, 0); + REQUIRE(socket->listen()); + url = "ws://127.0.0.1:" + std::to_string(static_cast(socket->port())); + } + + morph::exec::ThreadPoolExecutor pool{2}; + std::shared_ptr server; + std::unique_ptr socket; + std::string url; +}; + +// One client as `principal`: raw envelopes over a socket, and the `changes` events it receives. +struct Client { + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `Client(url, principal)` is a test helper whose arguments read differently at each call; a swap would fail the case's own assertion + Client(std::string const& url, std::string principal) : _principal{std::move(principal)} { + socket = std::make_unique(url); + REQUIRE(socket->waitForConnected()); + exchange = ui::exchangeOver(*socket, owner); + socket->setEventHandler( + [this](morph::wire::EventBody const& event) { + if (event.topic != morph::wire::kChangesTopic) { + return; + } + auto body = morph::wire::readChangesBody(event.payload.str); + REQUIRE(body); + changes.push_back(std::move(*body)); + }, + &owner); + morph::wire::Envelope hello; + hello.kind = std::string{kHello}; + auto const sent = send(std::move(hello)); + REQUIRE(sent.kind == "ok"); + } + + // Sends @p request as this client's principal and waits for its reply. + morph::wire::Envelope send(morph::wire::Envelope request) { + request.session.principal = _principal; + std::optional reply; + exchange(std::move(request), [&reply](ui::ExchangeReply answer) { reply = std::move(answer); }); + REQUIRE(pumpUntil([&] { return reply.has_value(); })); + REQUIRE(reply->has_value()); + return **reply; + } + + // Watches @p records; returns the refused ones. + std::vector watch(std::vector records) { + morph::wire::Envelope env; + env.kind = std::string{morph::wire::kWatchKind}; + env.body = + glz::write_json(morph::wire::WatchBody{.records = std::move(records), .instances = {}, .replace = false}) + .value_or(std::string{}); + auto const reply = send(std::move(env)); + REQUIRE(reply.kind == "ok"); + auto const parsed = morph::wire::readWatchReply(reply.body); + REQUIRE(parsed); + return parsed->refusedRecords; + } + + // Registers a private PtModel or WideTableModel instance. + std::uint64_t create(std::string const& modelType) { + auto const reply = send(morph::wire::makeRegister(modelType)); + REQUIRE(reply.kind == "ok"); + return reply.modelId; + } + + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `execute(instance, modelType, action, body)` is a test helper whose arguments read differently at each call; a swap would fail the case's own assertion + morph::wire::Envelope execute(std::uint64_t instance, std::string const& modelType, std::string const& action, + std::string body) { + morph::wire::Envelope env; + env.kind = "execute"; + env.modelId = instance; + env.modelType = modelType; + env.actionType = action; + env.body = std::move(body); + return send(std::move(env)); + } + + template + bool pumpUntil(Done done, std::chrono::milliseconds budget = 5s) { + auto const deadline = std::chrono::steady_clock::now() + budget; + while (!done()) { + if (std::chrono::steady_clock::now() > deadline) { + return false; + } + if (!owner.runOnce()) { + std::this_thread::sleep_for(1ms); + } + } + return true; + } + + // Runs the owner's tasks for @p span, so an event that would arrive arrives. + void pumpFor(std::chrono::milliseconds span) { + static_cast(pumpUntil([] { return false; }, span)); + } + + // The keys of every change of @p record received so far, and whether one came without keys. + std::vector keysOf(std::string_view record, bool* whole = nullptr) const { + std::vector keys; + for (auto const& body : changes) { + for (auto const& change : body.records) { + if (change.record != record) { + continue; + } + if (!change.keys) { + if (whole != nullptr) { + *whole = true; + } + continue; + } + for (auto const& key : *change.keys) { + keys.push_back(key.str); + } + } + } + return keys; + } + + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes): the client's executor, socket, exchange and received changes, which the cases drive and read directly + morph::exec::MainThreadExecutor owner; + std::unique_ptr socket; + ui::Exchange exchange; + std::vector changes; + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes) + +private: + std::string _principal; +}; + +morph::table::GenericPage pageOf(morph::wire::Envelope const& reply) { + REQUIRE(reply.kind == "ok"); + morph::table::GenericPage page; + REQUIRE_FALSE(glz::read_json(page, reply.body)); + return page; +} + +} // namespace + +TEST_CASE("tables: a principal allowed one table's action is refused the other", "[net][tables]") { + Server const server; + Client bob{server.url, "bob"}; + Client alice{server.url, "alice"}; + CHECK(bob.watch({"PtModel.first"}).empty()); + CHECK(bob.watch({"PtModel.second"}) == std::vector{"PtModel.second"}); + auto const instance = bob.create("PtModel"); + CHECK(bob.execute(instance, "PtModel", "Table.second", "{}").kind == "err"); + CHECK(bob.execute(instance, "PtModel", "Table.first", "{}").kind == "ok"); + CHECK(alice.watch({"PtModel.first", "PtModel.second"}).empty()); + // bob is refused Table.second, EditSecond and EditBoth, the only actions holding PtModel.second. + // Mutation: one record for the model (bob is admitted to both or neither). +} + +TEST_CASE("tables: updatesTable on one table marks only its watchers", "[net][tables]") { + Server const server; + Client c1{server.url, "alice"}; + Client c2{server.url, "alice"}; + REQUIRE(c1.watch({"PtModel.first"}).empty()); + REQUIRE(c2.watch({"PtModel.second"}).empty()); + auto const instance = c1.create("PtModel"); + + REQUIRE(c1.execute(instance, "PtModel", "EditFirst", R"({"key":3})").kind == "ok"); + REQUIRE(c1.pumpUntil([&] { return !c1.keysOf("PtModel.first").empty(); })); + CHECK(c1.keysOf("PtModel.first") == std::vector{"3"}); + c2.pumpFor(3 * kCoalesce); + CHECK(c2.changes.empty()); + + REQUIRE(c1.execute(instance, "PtModel", "EditSecond", R"({"key":4})").kind == "ok"); + REQUIRE(c2.pumpUntil([&] { return !c2.keysOf("PtModel.second").empty(); })); + CHECK(c2.keysOf("PtModel.second") == std::vector{"4"}); + c1.pumpFor(3 * kCoalesce); + CHECK(c1.keysOf("PtModel.second").empty()); + CHECK(c1.keysOf("PtModel.first") == std::vector{"3"}); + // Mutation: ChangedRows::heldRecord naming the model's first registered table whatever F is (the registries + // refuse EditSecond's updatesTable, or c1 is told of key 4). +} + +TEST_CASE("tables: an action changing two tables sends each table its keys", "[net][tables]") { + Server const server; + Client c1{server.url, "alice"}; + Client c2{server.url, "alice"}; + REQUIRE(c1.watch({"PtModel.first"}).empty()); + REQUIRE(c2.watch({"PtModel.second"}).empty()); + auto const instance = c1.create("PtModel"); + + REQUIRE(c1.execute(instance, "PtModel", "EditBoth", R"({"first":1,"second":2})").kind == "ok"); + REQUIRE(c1.pumpUntil([&] { return !c1.changes.empty(); })); + REQUIRE(c2.pumpUntil([&] { return !c2.changes.empty(); })); + bool firstWhole = false; + bool secondWhole = false; + CHECK(c1.keysOf("PtModel.first", &firstWhole) == std::vector{"1"}); + CHECK(c2.keysOf("PtModel.second", &secondWhole) == std::vector{"2"}); + CHECK_FALSE(firstWhole); + CHECK_FALSE(secondWhole); + // Mutation: the walk reporting a holder's record at the holder's own path instead of at its `rows` member (no key + // is found at "first" or "second", so each watcher gets a change without keys). +} + +TEST_CASE("tables: a page's columns are the caller's", "[net][tables]") { + bench::WideTableModel::configure({.rows = 2'000, .columns = 300, .seed = 7, .loadDelay = {}}, + {.rows = 1'000, .columns = 30, .seed = 7, .loadDelay = {}}); + Server const server; + Client alice{server.url, "alice"}; + Client restricted{server.url, "restricted"}; + auto const aliceModel = alice.create(std::string{bench::kWideModelType}); + auto const restrictedModel = restricted.create(std::string{bench::kWideModelType}); + auto const describe = [](Client& client, std::uint64_t instance) { + auto const reply = client.execute(instance, std::string{bench::kWideModelType}, "Table.scoped.describe", "{}"); + REQUIRE(reply.kind == "ok"); + morph::table::TableDescription description; + REQUIRE_FALSE(glz::read_json(description, reply.body)); + return description; + }; + auto const aliceDescription = describe(alice, aliceModel); + auto const restrictedDescription = describe(restricted, restrictedModel); + CHECK(aliceDescription.columns.size() == 24); + CHECK(restrictedDescription.columns.size() == 17); + CHECK(aliceDescription.revision != restrictedDescription.revision); + + std::string const query = R"({"page":{"offset":0,"limit":5}})"; + auto const alicePage = + pageOf(alice.execute(aliceModel, std::string{bench::kWideModelType}, "Table.scoped", query)); + auto const restrictedPage = + pageOf(restricted.execute(restrictedModel, std::string{bench::kWideModelType}, "Table.scoped", query)); + CHECK(alicePage.columns.size() == 24); + CHECK(restrictedPage.columns.size() == 17); + CHECK(alicePage.revision == aliceDescription.revision); + CHECK(restrictedPage.revision == restrictedDescription.revision); + // Spec row "Columns by session", over the socket. + // Mutation: QueryTable::invoke building TableContext from an empty session instead of session::current() (both + // principals get the same 24 columns). +} + +TEST_CASE("tables: a table's reply is built on tableWork", "[net][tables]") { + auto const tableWork = std::make_shared(); + Server const server{tableWork}; + Client alice{server.url, "alice"}; + auto const instance = alice.create("PtModel"); + push_tables::reads().clear(); + + auto const page = pageOf(alice.execute(instance, "PtModel", "Table.first", + R"({"sort":[{"column":"v","dir":"desc"}],"page":{"offset":0,"limit":4}})")); + CHECK(page.keys.size() == 4); + auto const readThreads = push_tables::reads().taken(); + auto const workThreads = tableWork->threads(); + REQUIRE_FALSE(readThreads.empty()); + CHECK(std::ranges::all_of(readThreads, [&](std::thread::id id) { return workThreads.contains(id); })); + CHECK_FALSE(readThreads.contains(push_tables::firstThread().load())); + // Mutation: RemoteServer not installing the TableRuntimeScope (answerQuery runs inline on the strand). +} + +namespace { + +// A server whose `tableWork` and view cache a case configures, `WideTableModel`'s recipe cache attached. +struct ViewServer { + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `ViewServer(maxViewBytes)` is a test helper whose arguments read differently at each call; a swap would fail the case's own assertion + explicit ViewServer(std::size_t maxViewBytes = 64U << 20U, std::size_t tableThreads = 2) + : tableWork{std::make_shared(tableThreads)} { + morph::backend::ServerConfig config; + config.services.push_back(std::make_shared()); + config.coalesceWindow = kCoalesce; + config.tableWork = tableWork; + config.views.maxBytes = maxViewBytes; + config.views.onCompute = [this] { + { + std::scoped_lock const lock{mutex}; + computedOn.insert(std::this_thread::get_id()); + } + if (gate) { + gate(); + } + }; + server = std::make_shared(pool, std::make_shared(), + std::move(config)); + server->attach(bench::WideTableModel::recipeCache()); + socket = std::make_unique(*server, 0); + REQUIRE(socket->listen()); + url = "ws://127.0.0.1:" + std::to_string(static_cast(socket->port())); + } + + std::set computeThreads() { + std::scoped_lock const lock{mutex}; + return computedOn; + } + + morph::exec::ThreadPoolExecutor pool{4}; + std::shared_ptr tableWork; + std::mutex mutex; + std::set computedOn; + // Called where a view's computation starts, when set; set before any request. + std::function gate; + std::shared_ptr server; + std::unique_ptr socket; + std::string url; +}; + +bool waitUntil(std::function const& done, std::chrono::milliseconds budget = 10s) { + auto const deadline = std::chrono::steady_clock::now() + budget; + while (!done()) { + if (std::chrono::steady_clock::now() > deadline) { + return false; + } + std::this_thread::sleep_for(2ms); + } + return true; +} + +} // namespace + +TEST_CASE("table over the bridge: a level's layout is the cache's", "[net][tables][levels]") { + bench::WideTableModel::recipeGate().hold(); + bench::WideTableModel::configure( + {.rows = 2'000, .columns = 300, .seed = 7, .loadDelay = {}, .recipePreloaded = 0.0}, + {.rows = 1'000, .columns = 30, .seed = 7, .loadDelay = {}, .recipePreloaded = 0.0}); + ViewServer const server; + Client extended{server.url, "extended"}; + Client alice{server.url, "alice"}; + auto const extendedModel = extended.create(std::string{bench::kWideModelType}); + auto const aliceModel = alice.create(std::string{bench::kWideModelType}); + std::string const extendedQuery = + R"({"sort":[{"column":"id","dir":"asc"}],"columns":["id","d000","d001","d002","d003","d004","d005",)" + R"("t001","t002","t003","t004","t005","t006"],"page":{"offset":0,"limit":200}})"; + std::string const aliceQuery = + R"({"sort":[{"column":"id","dir":"asc"}],"columns":["id","t001","t002","t003","t004","t005","t006"],)" + R"("page":{"offset":0,"limit":200}})"; + auto const ask = [&](Client& client, std::uint64_t instance, std::string const& query) { + return pageOf(client.execute(instance, std::string{bench::kWideModelType}, "Table.scoped", query)); + }; + auto const firstExtended = ask(extended, extendedModel, extendedQuery); + auto const firstAlice = ask(alice, aliceModel, aliceQuery); + CHECK(firstExtended.unloadedRows.size() == 200); + CHECK(firstAlice.unloadedRows.size() == 200); + CHECK(std::holds_alternative(firstAlice.rows.at(0).at(1))); + // Both first replies are in, each wholly unloaded: the loads may run now. + bench::WideTableModel::recipeGate().release(); + REQUIRE(waitUntil([] { return bench::WideTableModel::recipeCache()->stats().loadedKeys >= 200; })); + auto const secondExtended = ask(extended, extendedModel, extendedQuery); + auto const secondAlice = ask(alice, aliceModel, aliceQuery); + CHECK(secondExtended.unloadedRows.empty()); + CHECK(secondAlice.unloadedRows.empty()); + // The generator's cells: the small source holds the same values in its own columns. + bench::WideTableSource const truth{{.rows = 1'000, .columns = 30, .seed = 7, .loadDelay = {}}}; + auto const snapshot = truth.snapshot(); + auto const columnOf = [&](std::string_view id) { + auto const& columns = truth.columns(); + return static_cast(std::ranges::find(columns, id, &morph::table::ColumnInfo::id) - + columns.begin()); + }; + for (std::size_t row = 0; row < 200; ++row) { + for (std::size_t at = 1; at < secondAlice.columns.size(); ++at) { + CHECK(secondAlice.rows[row][at] == snapshot->cell(row, columnOf(secondAlice.columns[at]))); + } + for (std::size_t at = 1; at < secondExtended.columns.size(); ++at) { + CHECK(secondExtended.rows[row][at] == snapshot->cell(row, columnOf(secondExtended.columns[at]))); + } + } + std::map counts; + for (auto const& call : bench::WideTableModel::loaderCalls()) { + for (auto const& key : call) { + ++counts[key]; + } + } + CHECK(counts.size() == 200); + CHECK(std::ranges::all_of(counts, [](auto const& entry) { return entry.second == 1; })); + // Mutation: reading the value by the caller's column order (alice's t001 then holds d000's value). +} + +TEST_CASE("table over the bridge: one sort for many watchers", "[net][tables][views]") { + bench::WideTableModel::recipeGate().release(); + bench::WideTableModel::configure( + {.rows = 2'000, .columns = 300, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}, + {.rows = 1'000, .columns = 30, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}); + // Enough table threads for every refetch to be in the cache at once: one computes, forty-nine wait. + ViewServer server{64U << 20U, 64}; + std::vector> clients; + std::vector instances; + std::string const query = R"({"sort":[{"column":"d000","dir":"asc"}],"columns":["id","d000"],)" + R"("page":{"offset":0,"limit":50}})"; + for (int i = 0; i < 50; ++i) { + clients.push_back(std::make_unique(server.url, "alice")); + REQUIRE(clients.back()->watch({"WideTableModel.wide"}).empty()); + instances.push_back(clients.back()->create(std::string{bench::kWideModelType})); + static_cast(pageOf( + clients.back()->execute(instances.back(), std::string{bench::kWideModelType}, "Table.wide", query))); + } + auto const before = server.server->viewStats().computations; + CHECK(before == 1); + // An arrival on the order level: one value stored again gives the level a new generation. + auto const cache = bench::WideTableModel::recipeCache(); + std::vector cells(20); + REQUIRE(cache->snapshot()->read(morph::table::RowId{std::int64_t{1}}, cells) == morph::table::LevelRead::Loaded); + morph::table::detail::LevelCacheAccess::store( + *cache, std::vector>>{ + {morph::table::RowId{std::int64_t{1}}, cells}}); + REQUIRE(server.server->announce("WideTableModel.wide", std::nullopt)); + for (auto const& held : clients) { + auto& client = *held; + REQUIRE(client.pumpUntil([&] { return !client.changes.empty(); })); + } + // The fifty refetches are sent before any reply is read, and the computation they share waits until the other + // forty-nine have joined it (or ten seconds, when they compute instead). + auto const waitsBefore = server.server->viewStats().waits; + server.gate = [&server, waitsBefore] { + auto const deadline = std::chrono::steady_clock::now() + 10s; + while (server.server->viewStats().waits < waitsBefore + 49 && std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + }; + std::vector> replies(clients.size()); + for (std::size_t i = 0; i < clients.size(); ++i) { + morph::wire::Envelope env; + env.kind = "execute"; + env.modelId = instances[i]; + env.modelType = std::string{bench::kWideModelType}; + env.actionType = "Table.wide"; + env.body = query; + env.session.principal = "alice"; + clients[i]->exchange(std::move(env), + [&replies, i](ui::ExchangeReply answer) { replies[i] = std::move(answer); }); + } + for (std::size_t i = 0; i < clients.size(); ++i) { + REQUIRE(clients[i]->pumpUntil([&] { return replies[i].has_value(); }, 30s)); + REQUIRE(replies[i]->has_value()); + CHECK((*replies[i])->kind == "ok"); + } + server.gate = {}; + CHECK(server.server->viewStats().computations == before + 1); + CHECK(server.server->viewStats().waits == waitsBefore + 49); + auto const work = server.tableWork->threads(); + auto const computed = server.computeThreads(); + REQUIRE_FALSE(computed.empty()); + CHECK(std::ranges::all_of(computed, [&](std::thread::id id) { return work.contains(id); })); + // Mutations: no single flight (a computation per refetch, each waiting out the gate); QueryTable::invoke + // running answerQuery inline (the computing thread is a strand's, not a tableWork thread). +} + +TEST_CASE("table over the bridge: fifty sorts stay inside the bound", "[net][tables][views]") { + bench::WideTableModel::recipeGate().release(); + bench::WideTableModel::configure( + {.rows = 2'000, .columns = 300, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}, + {.rows = 1'000, .columns = 30, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}); + std::size_t const viewBytes = 4UZ * 2'000; // a view of every row of `wide` + ViewServer const server{10 * viewBytes}; + Client client{server.url, "alice"}; + auto const instance = client.create(std::string{bench::kWideModelType}); + for (int i = 1; i <= 50; ++i) { + auto const query = std::format(R"({{"sort":[{{"column":"i{:03}","dir":"asc"}}],"columns":["id"],)" + R"("page":{{"offset":0,"limit":10}}}})", + i); + static_cast(pageOf(client.execute(instance, std::string{bench::kWideModelType}, "Table.wide", query))); + } + auto const stats = server.server->viewStats(); + CHECK(stats.computations == 50); + CHECK(stats.bytes <= 10 * viewBytes); + CHECK(stats.evictions > 0); + // Mutation: no bound (forty views over it are kept and nothing is evicted). +} + +TEST_CASE("table over the bridge: two scopes over one snapshot get two views", "[net][tables][views]") { + bench::WideTableModel::recipeGate().release(); + bench::WideTableModel::configure( + {.rows = 2'000, .columns = 300, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}, + {.rows = 1'000, .columns = 30, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}); + ViewServer const server; + Client alice{server.url, "alice"}; + Client carol{server.url, "carol"}; + auto const aliceModel = alice.create(std::string{bench::kWideModelType}); + auto const carolModel = carol.create(std::string{bench::kWideModelType}); + std::string const query = R"({"sort":[{"column":"i001","dir":"asc"}],"columns":["id","i001"],)" + R"("page":{"offset":0,"limit":10}})"; + // `scoped` serves one source to every principal, so both views are over one snapshot. + static_cast(pageOf(alice.execute(aliceModel, std::string{bench::kWideModelType}, "Table.scoped", query))); + static_cast(pageOf(carol.execute(carolModel, std::string{bench::kWideModelType}, "Table.scoped", query))); + static_cast(pageOf(alice.execute(aliceModel, std::string{bench::kWideModelType}, "Table.scoped", query))); + CHECK(server.server->viewStats().computations == 2); + CHECK(server.server->viewStats().hits == 1); + // Mutation: an empty scope in the view key (carol is answered alice's view: one computation). +} + +TEST_CASE("table benchmark: C1 C2 C3 many clients over the bridge", "[.benchmark][net]") { + bench::WideTableModel::recipeGate().release(); + bench::WideTableModel::configure( + {.rows = 100'000, .columns = 300, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}, + {.rows = 1'000, .columns = 30, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}); + ViewServer const server{10UZ * 4 * 100'000}; + std::vector> clients; + std::vector instances; + for (int i = 0; i < 50; ++i) { + clients.push_back(std::make_unique(server.url, "alice")); + instances.push_back(clients.back()->create(std::string{bench::kWideModelType})); + } + auto const ask = [&](std::size_t i, std::string const& body) { + morph::wire::Envelope env; + env.kind = "execute"; + env.modelId = instances[i]; + env.modelType = std::string{bench::kWideModelType}; + env.actionType = "Table.wide"; + env.body = body; + env.session.principal = "alice"; + return env; + }; + std::string const sorted = R"({"sort":[{"column":"d000","dir":"asc"}],"columns":["id","d000"],)" + R"("page":{"offset":0,"limit":50}})"; + // C1: fifty concurrent refetches of one sorted view after a new order-level generation. + auto const cache = bench::WideTableModel::recipeCache(); + std::vector cells(20); + REQUIRE(cache->snapshot()->read(morph::table::RowId{std::int64_t{1}}, cells) == morph::table::LevelRead::Loaded); + morph::table::detail::LevelCacheAccess::store( + *cache, std::vector>>{ + {morph::table::RowId{std::int64_t{1}}, cells}}); + std::vector> replies(clients.size()); + auto const began = std::chrono::steady_clock::now(); + for (std::size_t i = 0; i < clients.size(); ++i) { + clients[i]->exchange(ask(i, sorted), + [&replies, i](ui::ExchangeReply answer) { replies[i] = std::move(answer); }); + } + for (std::size_t i = 0; i < clients.size(); ++i) { + REQUIRE(clients[i]->pumpUntil([&] { return replies[i].has_value(); }, 60s)); + } + auto const c1 = std::chrono::duration(std::chrono::steady_clock::now() - began).count(); + std::println("| C1 | fifty concurrent refetches of one sorted view, 100,000 x 300: {:.1f} ms, {} computed |", c1, + server.server->viewStats().computations); + // C2: distinct sorts computed one after another. + auto const computed = server.server->viewStats().computations; + auto const c2Began = std::chrono::steady_clock::now(); + for (int column = 1; column <= 20; ++column) { + static_cast(pageOf(clients[0]->execute( + instances[0], std::string{bench::kWideModelType}, "Table.wide", + std::format( + R"({{"sort":[{{"column":"i{:03}","dir":"asc"}}],"columns":["id"],"page":{{"offset":0,"limit":10}}}})", + column)))); + } + auto const seconds = std::chrono::duration(std::chrono::steady_clock::now() - c2Began).count(); + std::println("| C2 | views computed per second: {:.1f} ({} views) |", + static_cast(server.server->viewStats().computations - computed) / seconds, + server.server->viewStats().computations - computed); + // C3: fifty sorts against a bound of ten views. + for (int column = 21; column <= 50; ++column) { + static_cast(pageOf(clients[0]->execute( + instances[0], std::string{bench::kWideModelType}, "Table.wide", + std::format( + R"({{"sort":[{{"column":"i{:03}","dir":"asc"}}],"columns":["id"],"page":{{"offset":0,"limit":10}}}})", + column)))); + } + auto const stats = server.server->viewStats(); + std::println("| C3 | after fifty sorts: {} bytes held of a {} bound, {} evictions |", stats.bytes, + 10 * 4 * 100'000, stats.evictions); +} + +namespace { + +// The wide fixture's 100,000 x 300 table, every level loaded: configured before a server attaches its recipe cache, +// as every case of this file does. +struct WideFixture { + WideFixture() { + bench::WideTableModel::recipeGate().release(); + bench::WideTableModel::configure( + {.rows = 100'000, .columns = 300, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}, + {.rows = 1'000, .columns = 30, .seed = 7, .loadDelay = {}, .recipePreloaded = 1.0}); + } +}; + +// A link with @p latency each way in front of a model's channel: a call leaves after the latency and its reply is +// handed on the latency after it lands, both slept on the client's owner, so the server's work in between is +// measured as it is. It counts the first-page fetches it carries: the round trips a change of the query costs. +class SlowLink final : public ui::ModelChannel { +public: + SlowLink(std::shared_ptr inner, morph::exec::IExecutor& owner, std::chrono::milliseconds latency) + : _inner{std::move(inner)}, _owner{&owner}, _latency{latency} {} + + [[nodiscard]] morph::async::Completion execute(std::string const& actionId, + std::string const& bodyJson, + ui::CallOptions options) override { + bool const page = !actionId.ends_with(".describe") && !bodyJson.contains(R"("keys")") && + !bodyJson.contains(R"("distinct")") && bodyJson.contains(R"("offset":0)"); + if (page) { + ++firstPages; + } + std::this_thread::sleep_for(_latency); + auto [completion, promise] = morph::async::Completion::makeSettleable(_owner); + auto const settle = std::make_shared::Promise>(std::move(promise)); + auto const latency = _latency; + auto sent = _inner->execute(actionId, bodyJson, std::move(options)); + sent.then([this, settle, latency, page](std::string const& reply) { + std::this_thread::sleep_for(latency); + if (page) { + ++answeredPages; + } + settle->resolve(reply); + }); + sent.onError([settle](std::exception_ptr const& error) { settle->reject(error); }); + return std::move(completion); + } + + [[nodiscard]] ui::ChannelFacts facts() const override { return _inner->facts(); } + + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes): the page counters the case reads after the run + int firstPages = 0; + int answeredPages = 0; + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes) + +private: + std::shared_ptr _inner; + morph::exec::IExecutor* _owner; + std::chrono::milliseconds _latency; +}; + +// One client as a UI session over the bridge, its model's calls through a `SlowLink`: what a model-backed table's +// `WindowRows` reads through. +struct SessionOverLink { + SessionOverLink(std::string const& url, std::chrono::milliseconds latency) { + auto made = std::make_unique(url); + socket = made.get(); + REQUIRE(socket->waitForConnected()); + exchange = ui::exchangeOver(*socket, owner); + bridge = std::make_unique(std::move(made), owner); + dispatcher = std::make_unique(*bridge, &owner); + ui::SessionOptions options; + options.watcher = ui::watcherOver(exchange, [] { return morph::session::Context{}; }, &owner); + session = std::make_unique(runtime, std::move(options)); + socket->setEventHandler([this](morph::wire::EventBody const& event) { session->deliverEvent(event); }, &owner); + bool negotiated = false; + morph::wire::Envelope hello; + hello.kind = std::string{kHello}; + exchange(std::move(hello), [&negotiated](ui::ExchangeReply const& reply) { + negotiated = reply.has_value() && reply->kind == "ok"; + }); + REQUIRE(pumpUntil([&] { return negotiated; })); + link = std::make_shared( + dispatcher->bind(std::string{bench::kWideModelType}, morph::bridge::BindSharing::Private, std::string{}), + owner, latency); + } + + template + bool pumpUntil(Done done, std::chrono::milliseconds budget = 10s) { + auto const deadline = std::chrono::steady_clock::now() + budget; + while (!done()) { + if (std::chrono::steady_clock::now() > deadline) { + return false; + } + if (!owner.runOnce()) { + std::this_thread::sleep_for(1ms); + } + } + return true; + } + + // The table's description, read as `Table.
.describe` through the session. + morph::table::TableDescription describe(std::string const& table) { + std::optional text; + bool failed = false; + auto completion = session->read(link, "Table." + table + ".describe", ui::Value{ui::ValueRecord{}}); + completion.then([&text](std::string const& reply) { text = reply; }) + .onError([&failed](std::exception_ptr const&) { failed = true; }); + REQUIRE(pumpUntil([&] { return text.has_value() || failed; })); + REQUIRE(text.has_value()); + morph::table::TableDescription description; + REQUIRE_FALSE(glz::read(description, *text)); + return description; + } + + morph::exec::MainThreadExecutor owner; + morph::reactive::Runtime runtime{owner}; + morph::net::SocketBackend* socket = nullptr; + ui::Exchange exchange; + std::unique_ptr bridge; + std::unique_ptr dispatcher; + std::unique_ptr session; + std::shared_ptr link; +}; + +// A table's rows over `wide` through the link, showing rows 0 to 30 of the columns @p columns names, and whether +// the rows took a first page that came after `expect` was called. +struct WideWindow { + WideWindow(SessionOverLink& client, std::vector columns) + : link{client.link}, + rows{std::make_shared( + *client.session, + ui::WindowRowsOptions{ + .channel = client.link, .table = "wide", .records = {}, .pageSize = 200, .maxPages = 8})}, + shown{std::move(columns)} { + rows->onChange([this](morph::table::ViewChange const& /*change*/) { + if (link->answeredPages > mark && rows->row(0).has_value()) { + accepted = true; + } + }); + rows->setDescription(client.describe("wide")); + rows->visible(0, 30, shown); + } + + // From now on, a first page answered after this call is the one awaited. + void expect() { + mark = link->answeredPages; + accepted = false; + } + + std::shared_ptr link; + std::shared_ptr rows; + std::vector shown; + int mark = 0; + bool accepted = false; +}; + +} // namespace + +// B3, recorded and not a gate. 50 ms each way, through the rows a model-backed table reads: a header sort's new +// chain to the accepted page (bound 150 ms), and the filter the last key of a text condition sends to the accepted +// page (bound 150 ms after the filter menu's 250 ms debounce, which "a condition applies once after typing pauses" +// gates in morph_tests). Each change costs one round trip: one first-page fetch. Unbuilt on the host that wrote it, +// and its mutation not run: WindowRows sending a query change twice (restart called a second time in `setSort` or +// `setFilter`) makes `firstPages` grow by two. +TEST_CASE("table benchmark: a sort change and a text filter over a socket with 50 ms each way", + "[.benchmark][table]") { + WideFixture const fixture; + ViewServer const server{}; + SessionOverLink client{server.url, 50ms}; + WideWindow window{client, {"id", "d000", "t011"}}; + REQUIRE(client.pumpUntil([&] { return window.accepted; }, 60s)); + + int const beforeSort = client.link->firstPages; + window.expect(); + auto const sortBegan = std::chrono::steady_clock::now(); + REQUIRE( + window.rows->setSort({morph::table::SortKey{.column = "d000", .dir = morph::table::SortDirection::Ascending}}) + .has_value()); + REQUIRE(client.pumpUntil([&] { return window.accepted; }, 10s)); + auto const sortMs = + std::chrono::duration(std::chrono::steady_clock::now() - sortBegan).count(); + CHECK(client.link->firstPages - beforeSort == 1); + + int const beforeFilter = client.link->firstPages; + window.expect(); + morph::table::FilterEntry contains; + contains.contains = "a"; + morph::table::FilterSpec filter; + filter.columns.insert_or_assign( + "t011", + morph::table::ColumnFilter{.combine = morph::table::Combine::Any, .include = {contains}, .exclude = {}}); + auto const keyBegan = std::chrono::steady_clock::now(); + REQUIRE(window.rows->setFilter(filter).has_value()); + REQUIRE(client.pumpUntil([&] { return window.accepted; }, 10s)); + auto const keyMs = std::chrono::duration(std::chrono::steady_clock::now() - keyBegan).count(); + CHECK(client.link->firstPages - beforeFilter == 1); + + std::println("| B3 | sort on d000, 100,000 x 300, 50 ms each way, to the accepted page: {:.1f} ms (bound 150) |", + sortMs); + std::println( + "| B3 | a text filter's query to the accepted page, 50 ms each way: {:.1f} ms (bound 150 after the " + "250 ms debounce) |", + keyMs); +} + +// D9, recorded and not a gate: the server side of a values list, a `distinct` query on `t011` to its reply (bound +// 150 ms from the menu's opening to the list shown, which this figure does not include the client's drawing in). +TEST_CASE("table benchmark: a server-mode values list from open to shown", "[.benchmark][table]") { + WideFixture const fixture; + ViewServer const server{}; + Client client{server.url, "alice"}; + auto const instance = client.create(std::string{bench::kWideModelType}); + auto const began = std::chrono::steady_clock::now(); + auto const listed = pageOf( + client.execute(instance, std::string{bench::kWideModelType}, "Table.wide", + R"({"distinct":{"column":"t011","search":"","bucket":"value","offset":0,"limit":200}})")); + auto const ms = std::chrono::duration(std::chrono::steady_clock::now() - began).count(); + REQUIRE(listed.distinct.has_value()); + CHECK_FALSE(listed.distinct->values.empty()); + std::println( + "| D9 | values list of t011, 100,000 rows, the server's reply: {:.1f} ms, {} values of {} (bound 150) |", ms, + listed.distinct->values.size(), listed.distinct->distinct); +} + +namespace { + +// One server on a socket offering `morph.tableState` over a memory preferences store, with the tables authorizer. +struct StateServer { + StateServer() { + ui::registerTableState(prefs, dispatcher, registry); + morph::backend::ServerConfig config; + config.services.push_back(std::make_shared()); + server = std::make_shared(pool, std::make_shared(), + std::move(config), dispatcher, registry); + socket = std::make_unique(*server, 0); + REQUIRE(socket->listen()); + url = "ws://127.0.0.1:" + std::to_string(static_cast(socket->port())); + } + + morph::exec::ThreadPoolExecutor pool{2}; + morph::model::detail::ActionDispatcher dispatcher; + morph::model::detail::ModelRegistryFactory registry; + std::shared_ptr prefs = std::make_shared(pool); + std::shared_ptr server; + std::unique_ptr socket; + std::string url; +}; + +} // namespace + +TEST_CASE("table state: the person is the store's", "[net][tables][state]") { + StateServer const server; + Client alice{server.url, "alice"}; + Client bob{server.url, "bob"}; + std::string const model{ui::kTableStateModel}; + auto const aliceState = alice.create(model); + auto const bobState = bob.create(model); + morph::table::TableStateKey const key{.application = "lims", + .model = "Lims_SampleModel", + .table = "samples", + .qualifier = "samples", + .part = "state"}; + auto const save = [&](Client& client, std::uint64_t instance, std::string text) { + auto const reply = client.execute( + instance, model, "save", + morph::model::ActionTraits::toJson(ui::TableStateSave{ + .key = key, .expected = {}, .upload = {}, .offset = 0, .text = std::move(text), .last = true})); + REQUIRE(reply.kind == "ok"); + }; + auto const loadedText = [&](Client& client, std::uint64_t instance, std::string const& body) { + auto const reply = client.execute(instance, model, "load", body); + REQUIRE(reply.kind == "ok"); + auto const loaded = morph::model::ActionTraits::resultFromJson(reply.body); + REQUIRE(loaded.entries.size() == 1); + return loaded.entries.front().text; + }; + save(alice, aliceState, R"({"version":1,"view":"alice's"})"); + save(bob, bobState, R"({"version":1,"view":"bob's"})"); + std::string const keys = morph::model::ActionTraits::toJson(ui::TableStateLoad{.keys = {key}}); + CHECK(loadedText(alice, aliceState, keys) == R"({"version":1,"view":"alice's"})"); + CHECK(loadedText(bob, bobState, keys) == R"({"version":1,"view":"bob's"})"); + // A body naming another person is read with that member ignored. + std::string const naming = keys.substr(0, keys.size() - 1) + R"(,"person":"bob"})"; + CHECK(loadedText(alice, aliceState, naming) == R"({"version":1,"view":"alice's"})"); + // Mutation: the model keying by a body member (alice's load naming bob reads bob's state). Not run: this case is + // in morph_net_tests, which builds only on POSIX, and has been neither built nor run; its in-process twin in + // tests/test_ui_table_state.cpp has, with this mutation. +} + +TEST_CASE("shared views: a view published over a socket is read by a second client", "[net][tables][state]") { + StateServer const server; + Client alice{server.url, "alice"}; + Client bob{server.url, "bob"}; + std::string const model{ui::kTableStateModel}; + auto const aliceState = alice.create(model); + auto const bobState = bob.create(model); + morph::table::TableStateKey const shared{.application = "lims", + .model = "Lims_SampleModel", + .table = "samples", + .qualifier = "samples", + .part = "shared"}; + // Mutation: publish written under the caller's person (bob does not see it). + auto const publish = + alice.execute(aliceState, model, "publish", + morph::model::ActionTraits::toJson(ui::TableStatePublish{ + .key = shared, + .operation = morph::table::writeViewOperation(morph::table::AddView{ + morph::table::SavedView{.name = "Mine", .layout = {}, .sort = {}, .filters = {}}}), + .expected = std::string{morph::table::kNoDocument}})); + REQUIRE(publish.kind == "ok"); + auto const published = morph::model::ActionTraits::resultFromJson(publish.body).result; + REQUIRE(published.outcome == morph::table::SaveOutcome::Saved); + auto const read = + bob.execute(bobState, model, "load", + morph::model::ActionTraits::toJson(ui::TableStateLoad{.keys = {shared}})); + REQUIRE(read.kind == "ok"); + auto const loaded = morph::model::ActionTraits::resultFromJson(read.body); + REQUIRE(loaded.entries.size() == 1); + CHECK(loaded.entries.front().revision == published.revision); + auto const views = morph::table::readViews(loaded.entries.front().text); + REQUIRE(views.has_value()); + REQUIRE(views->views.size() == 1); + CHECK(views->views.front().name == "Mine"); + + // Mutation: the model treating kNoDocument as an ordinary revision in `save` (the first save answers Conflict). + auto own = shared; + own.part = "views"; + auto const saveOnce = [&] { + auto const reply = alice.execute(aliceState, model, "save", + morph::model::ActionTraits::toJson( + ui::TableStateSave{.key = own, + .expected = std::string{morph::table::kNoDocument}, + .upload = {}, + .offset = 0, + .text = R"({"version":1,"views":[]})", + .last = true})); + REQUIRE(reply.kind == "ok"); + return morph::model::ActionTraits::resultFromJson(reply.body).result; + }; + auto const first = saveOnce(); + REQUIRE(first.outcome == morph::table::SaveOutcome::Saved); + auto const again = saveOnce(); + CHECK(again.outcome == morph::table::SaveOutcome::Conflict); + CHECK(again.revision == first.revision); +} + +// A view published under a new name and then replaced under that name over a socket is one view, which a second +// client reads with the replacing sort. Mutation: `applyViewOperation` answering a `ReplaceView` as `NameTaken` (the +// second publish is Refused). +TEST_CASE("shared views: a view published twice under one name over a socket is replaced", "[net][tables][state]") { + StateServer const server; + Client alice{server.url, "alice"}; + Client bob{server.url, "bob"}; + std::string const model{ui::kTableStateModel}; + auto const aliceState = alice.create(model); + auto const bobState = bob.create(model); + morph::table::TableStateKey const shared{.application = "lims", + .model = "Lims_SampleModel", + .table = "samples", + .qualifier = "samples", + .part = "shared"}; + auto const team = [](morph::table::SortDirection direction) { + return morph::table::SavedView{.name = "Team", + .layout = {}, + .sort = {morph::table::SortKey{.column = "name", .dir = direction}}, + .filters = {}}; + }; + auto const publish = [&](morph::table::ViewOperation const& operation, std::string expected) { + auto const reply = + alice.execute(aliceState, model, "publish", + morph::model::ActionTraits::toJson( + ui::TableStatePublish{.key = shared, + .operation = morph::table::writeViewOperation(operation), + .expected = std::move(expected)})); + REQUIRE(reply.kind == "ok"); + return morph::model::ActionTraits::resultFromJson(reply.body).result; + }; + auto const first = publish(morph::table::AddView{team(morph::table::SortDirection::Ascending)}, + std::string{morph::table::kNoDocument}); + REQUIRE(first.outcome == morph::table::SaveOutcome::Saved); + auto const second = + publish(morph::table::ReplaceView{team(morph::table::SortDirection::Descending)}, first.revision); + REQUIRE(second.outcome == morph::table::SaveOutcome::Saved); + auto const read = + bob.execute(bobState, model, "load", + morph::model::ActionTraits::toJson(ui::TableStateLoad{.keys = {shared}})); + REQUIRE(read.kind == "ok"); + auto const loaded = morph::model::ActionTraits::resultFromJson(read.body); + REQUIRE(loaded.entries.size() == 1); + CHECK(loaded.entries.front().revision == second.revision); + auto const views = morph::table::readViews(loaded.entries.front().text); + REQUIRE(views.has_value()); + REQUIRE(views->views.size() == 1); + CHECK(views->views.front().sort.front().dir == morph::table::SortDirection::Descending); +} + +// ── A selection of the view, resolved on the server ──────────────────────────────────────────────────────── +// Written by reading: morph_net_tests builds on POSIX only, and was not built or run for these cases. + +// NOLINTBEGIN(misc-use-internal-linkage) +namespace selnet { + +struct TagRows; +struct MoveRow; +struct SaveAs; +struct SavedAs; + +// Ten rows keyed 0..9: status "open" for 0..5, "closed" for 6..9. alice sees every row, bob rows 0..4. +class Rows { +public: + Rows(); + morph::table::ServedTable rows(morph::table::TableContext const& context); + core::async::Task> execute(TagRows action); + morph::table::ChangedRows<&Rows::rows> execute(MoveRow const& action); + SavedAs execute(SaveAs const& action); + + static inline std::int64_t maxSelectedRows = 1'000'000; + +private: + std::shared_ptr _source; +}; + +struct TagRows { + morph::table::RowSelection<&Rows::rows> rows; + morph::table::RowRef<&Rows::rows> focus; +}; + +struct MoveRow { + std::int64_t key = 0; + std::string status; +}; + +// Saves row 2 as the new row 10, and cannot save row 4. +struct SaveAs { + std::int64_t key = 0; +}; + +struct SavedAs { + morph::table::ChangedRows<&Rows::rows> rows; +}; + +} // namespace selnet + +BRIDGE_REGISTER_MODEL(selnet::Rows, "selnet::Rows") +BRIDGE_REGISTER_TABLE(selnet::Rows, "rows", &selnet::Rows::rows, morph::table::rowScoped) +BRIDGE_REGISTER_ACTION(selnet::Rows, selnet::TagRows, "TagRows") +BRIDGE_REGISTER_ACTION(selnet::Rows, selnet::MoveRow, "MoveRow") +BRIDGE_REGISTER_EFFECTS(selnet::MoveRow, morph::effects::updatesTable<&selnet::Rows::rows>) +BRIDGE_REGISTER_ACTION(selnet::Rows, selnet::SaveAs, "SaveAs") +BRIDGE_REGISTER_EFFECTS(selnet::SaveAs, morph::effects::updatesTable<&selnet::Rows::rows>) + +namespace selnet { + +namespace { + +std::vector rowColumns() { + return {morph::table::TableColumn{.info = {.id = "id", .kind = morph::table::ColumnKind::Integer}, .label = "Id"}, + morph::table::TableColumn{.info = {.id = "status", .kind = morph::table::ColumnKind::Text}, + .label = "Status"}}; +} + +} // namespace + +Rows::Rows() { + morph::table::TableDescription description; + description.columns = rowColumns(); + _source = std::make_shared(morph::table::columnInfos(description)); + std::vector keys; + std::vector> cells; + for (std::int64_t row = 0; row < 10; ++row) { + keys.emplace_back(row); + cells.push_back({morph::table::Cell{row}, morph::table::Cell{std::string{row < 6 ? "open" : "closed"}}}); + } + _source->setRows(std::move(keys), std::move(cells)); +} + +morph::table::ServedTable Rows::rows(morph::table::TableContext const& context) { + morph::table::ServedTable served; + served.description.id = "rows"; + served.description.key = "id"; + served.description.columns = rowColumns(); + served.scope = context.session.principal; + served.limits.maxSelectedRows = maxSelectedRows; + if (context.session.principal == "bob") { + std::vector mine; + for (std::int64_t row = 0; row < 5; ++row) { + // NOLINTNEXTLINE(performance-inefficient-vector-operation): `mine` is a fixture list of five keys built once; sizing it would not change what the case checks + mine.emplace_back(row); + } + served.source = morph::table::scoped(_source, std::move(mine)); + } else { + served.source = _source; + } + return served; +} + +core::async::Task> Rows::execute(TagRows action) { + auto const context = morph::table::detail::callerContext(); + auto completion = morph::table::resolve(*this, action.rows, context, morph::table::SelectionPolicy::Exact); + auto resolved = co_await std::move(completion); + if (!resolved) { + morph::table::refuse(resolved.error()); + } + morph::table::ChangedRows<&Rows::rows> out; + for (auto const& key : resolved->keys) { + out.rows.push_back(morph::table::ChangedRow{.key = key}); + } + co_return out; +} + +morph::table::ChangedRows<&Rows::rows> Rows::execute(MoveRow const& action) { + _source->patchRow(morph::table::RowId{action.key}, + {morph::table::Cell{action.key}, morph::table::Cell{action.status}}); + return {.rows = {morph::table::ChangedRow{.key = morph::table::RowId{action.key}}}}; +} + +SavedAs Rows::execute(SaveAs const& action) { + static_cast(action); + SavedAs out; + out.rows.rows.push_back(morph::table::ChangedRow{.key = morph::table::RowId{std::int64_t{10}}, + .from = morph::table::RowId{std::int64_t{2}}}); + out.rows.failed.push_back( + morph::table::FailedRow{.key = morph::table::RowId{std::int64_t{4}}, .message = "Locked"}); + return out; +} + +} // namespace selnet +// NOLINTEND(misc-use-internal-linkage) + +namespace { + +constexpr std::string_view kOpen = R"({"columns":{"status":{"include":[{"eq":"open"}]}}})"; + +// The keys of a ChangedRows reply (`rows`, objects with `key`) or a SelectedRows reply (`keys`). +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `keysOfReply(body, member)` is a test helper whose arguments read differently at each call; a swap would fail the case's own assertion +std::vector keysOfReply(std::string const& body, std::string const& member) { + glz::generic_u64 json; + REQUIRE_FALSE(glz::read_json(json, body)); + std::vector out; + for (auto const& item : json[member].get_array()) { + out.push_back(item.is_object() ? item.at("key").as() : item.as()); + } + return out; +} + +} // namespace + +TEST_CASE("tables: an action resolves a view selection on its own model", "[net][tables][selection]") { + Server const server; + Client alice{server.url, "alice"}; + auto const model = alice.create("selnet::Rows"); + auto const page = + pageOf(alice.execute(model, "selnet::Rows", "Table.rows", R"({"filters":)" + std::string{kOpen} + "}")); + std::string const revision = page.viewRevision; + REQUIRE(revision.size() == 48); + std::string const tag = R"({"rows":{"view":{"filters":)" + std::string{kOpen} + R"(,"retained":[],"revision":")" + + revision + R"("},"except":[3]},"focus":0})"; + auto const tagged = alice.execute(model, "selnet::Rows", "TagRows", tag); + REQUIRE(tagged.kind == "ok"); + CHECK(keysOfReply(tagged.body, "rows") == std::vector{0, 1, 2, 4, 5}); + REQUIRE(alice.execute(model, "selnet::Rows", "MoveRow", R"({"key":7,"status":"open"})").kind == "ok"); + auto const refused = alice.execute(model, "selnet::Rows", "TagRows", tag); + CHECK(refused.kind == "err"); + REQUIRE(refused.refusal.has_value()); + CHECK(refused.refusal->code == "morph.table.viewChanged"); +} +// Mutation: viewRevision that ignores the source snapshot, which tags rows under the old revision. + +TEST_CASE("tables: Table..resolve answers for the caller", "[net][tables][selection]") { + Server const server; + Client bob{server.url, "bob"}; + Client alice{server.url, "alice"}; + auto const bobModel = bob.create("selnet::Rows"); + auto const keys = bob.execute(bobModel, "selnet::Rows", "Table.rows.resolve", + R"({"selection":{"keys":[1,3,8]},"policy":"current"})"); + REQUIRE(keys.kind == "ok"); + CHECK(keysOfReply(keys.body, "keys") == std::vector{1, 3}); + CHECK(keys.body.contains(R"("dropped":1)")); + std::string const view = R"({"selection":{"view":{"filters":)" + std::string{kOpen} + + R"(,"retained":[],"revision":""},"except":[]},"policy":"current"})"; + auto const scoped = bob.execute(bobModel, "selnet::Rows", "Table.rows.resolve", view); + REQUIRE(scoped.kind == "ok"); + CHECK(keysOfReply(scoped.body, "keys") == std::vector{0, 1, 2, 3, 4}); // none outside the scope + selnet::Rows::maxSelectedRows = 5; + auto const aliceModel = alice.create("selnet::Rows"); + auto const over = alice.execute(aliceModel, "selnet::Rows", "Table.rows.resolve", view); + selnet::Rows::maxSelectedRows = 1'000'000; + CHECK(over.kind == "err"); + REQUIRE(over.refusal.has_value()); + CHECK(over.refusal->code == "table.limitExceeded"); +} +// Mutation: resolve run under the server principal, which returns rows outside the caller scope. + +TEST_CASE("tables: a selection's schema names its table", "[net][tables][selection]") { + glz::generic_u64 schema; + REQUIRE_FALSE(glz::read_json(schema, morph::forms::schemaJson())); + CHECK(schema["properties"]["rows"]["x-selectionOf"].get_string() == "selnet::Rows.rows"); + CHECK(schema["properties"]["focus"]["x-rowOf"].get_string() == "selnet::Rows.rows"); +} +// Mutation: schemaValue returning an empty name, which leaves the client unable to mark busy rows. + +TEST_CASE("tables: a changed key's event names both keys", "[net][tables][keys]") { + Server const server; + Client alice{server.url, "alice"}; + REQUIRE(alice.watch({"selnet::Rows.rows"}).empty()); + auto const model = alice.create("selnet::Rows"); + auto const saved = alice.execute(model, "selnet::Rows", "SaveAs", R"({"key":2})"); + REQUIRE(saved.kind == "ok"); + CHECK(saved.body.contains(R"("from":2)")); + CHECK(saved.body.contains(R"("message":"Locked")")); + REQUIRE(alice.pumpUntil([&] { return !alice.changes.empty(); })); + alice.pumpFor(3 * kCoalesce); + REQUIRE(alice.changes.size() == 1); + auto keys = alice.keysOf("selnet::Rows.rows"); + std::ranges::sort(keys); + CHECK(keys == std::vector{"10", "2"}); +} +// Mutation: the walk ignoring `from`, which leaves the old row's watchers untold (keys {10}). + +// ── Cells of a model's table over a socket ────────────────────────────────── + +// NOLINTBEGIN(misc-use-internal-linkage): registered types must have external linkage. +namespace editnet { + +struct EditSpecimenCount; + +// Three specimens keyed 1..3, each with a `count` equal to its key, which `Lims_EditSpecimenCount` changes. +class Specimens { +public: + Specimens(); + morph::table::ServedTable specimens(morph::table::TableContext const& context); + morph::table::ChangedRows<&Specimens::specimens> execute(EditSpecimenCount const& action); + +private: + std::shared_ptr _source; +}; + +struct EditSpecimenCount : morph::table::CellEdit<&Specimens::specimens, std::int64_t> {}; + +} // namespace editnet + +BRIDGE_REGISTER_MODEL(editnet::Specimens, "editnet::Specimens") +BRIDGE_REGISTER_TABLE(editnet::Specimens, "specimens", &editnet::Specimens::specimens) +BRIDGE_REGISTER_ACTION(editnet::Specimens, editnet::EditSpecimenCount, "Lims_EditSpecimenCount") +BRIDGE_REGISTER_EFFECTS(editnet::EditSpecimenCount, morph::effects::updatesTable<&editnet::Specimens::specimens>) + +namespace editnet { + +namespace { + +// `key` (the key) and `count`, edited by `Lims_EditSpecimenCount`. +std::vector specimenColumns() { + return { + morph::table::TableColumn{.info = {.id = "key", .kind = morph::table::ColumnKind::Integer}, .label = "Key"}, + morph::table::TableColumn{.info = {.id = "count", .kind = morph::table::ColumnKind::Integer}, + .label = "Count", + .edit = morph::table::EditInfo{.action = "Lims_EditSpecimenCount"}}}; +} + +} // namespace + +Specimens::Specimens() { + morph::table::TableDescription description; + description.columns = specimenColumns(); + _source = std::make_shared(morph::table::columnInfos(description)); + std::vector keys; + std::vector> cells; + for (std::int64_t row = 1; row <= 3; ++row) { + keys.emplace_back(row); + cells.push_back({morph::table::Cell{row}, morph::table::Cell{row}}); + } + _source->setRows(std::move(keys), std::move(cells)); +} + +morph::table::ServedTable Specimens::specimens(morph::table::TableContext const& /*context*/) { + morph::table::ServedTable served; + served.description.id = "specimens"; + served.description.key = "key"; + served.description.columns = specimenColumns(); + served.description.capabilities.keys = true; + served.source = _source; + return served; +} + +morph::table::ChangedRows<&Specimens::specimens> Specimens::execute(EditSpecimenCount const& action) { + auto const key = std::get(action.key); + _source->patchRow(action.key, {morph::table::Cell{key}, morph::table::Cell{action.value}}); + return {.rows = {morph::table::ChangedRow{.key = action.key}}}; +} + +} // namespace editnet +// NOLINTEND(misc-use-internal-linkage) + +TEST_CASE("push tables: a cell edit reaches the model and the change event refetches the row", "[net][tables][edit]") { + glz::generic_u64 schema; + REQUIRE_FALSE(glz::read_json(schema, morph::forms::schemaJson())); + CHECK(schema["x-cellEditOf"].get_string() == "editnet::Specimens.specimens"); + Server const server; + Client alice{server.url, "alice"}; + REQUIRE(alice.watch({"editnet::Specimens.specimens"}).empty()); + auto const model = alice.create("editnet::Specimens"); + // The description is checked against the action's input on the server: the count column's field fits it. + auto const described = alice.execute(model, "editnet::Specimens", "Table.specimens.describe", "{}"); + REQUIRE(described.kind == "ok"); + CHECK(described.body.contains(R"("edit":{"action":"Lims_EditSpecimenCount")")); + auto const edited = alice.execute(model, "editnet::Specimens", "Lims_EditSpecimenCount", R"({"key":1,"value":4})"); + REQUIRE(edited.kind == "ok"); + REQUIRE(alice.pumpUntil([&] { return !alice.changes.empty(); })); + CHECK(alice.keysOf("editnet::Specimens.specimens") == std::vector{"1"}); + // The refetch the change event causes: a keyed query of row 1 holds the count the model now has. + auto const page = pageOf(alice.execute(model, "editnet::Specimens", "Table.specimens", R"({"keys":[1]})")); + REQUIRE(page.rows.size() == 1); + auto const at = std::ranges::find(page.columns, std::string{"count"}); + REQUIRE(at != page.columns.end()); + CHECK(page.rows.at(0).at(static_cast(at - page.columns.begin())) == + morph::table::Cell{std::int64_t{4}}); +} +// Mutation: the client sending {"key":…, "value":…} under the wrong action id (the model never sees it). + +TEST_CASE("push tables: a principal refused the edit action sees the column read-only", "[net][tables][edit]") { + // A bundle of one screen whose mutation runs the edit action, so the catalog lists it. + morph::ui::author::CatalogFacts facts; + facts.model(); + facts.action(); + morph::ui::UiRegistry registry{morph::ui::ApplicationInfo{.id = "lims", .version = "1.0.0"}, facts.catalog()}; + morph::ui::CatalogEntry entry; + entry.id = "lims.edits"; + REQUIRE(registry.addScreen(entry, R"({"vocab":"ui/1","id":"lims.edits",)" + R"("models":{"s":{"type":"editnet::Specimens"}},)" + R"("mutations":{"edit":{"model":"s","action":"Lims_EditSpecimenCount",)" + R"("body":{"lit":{"key":1,"value":4}}}},)" + R"("view":{"kind":"button","label":"Edit","onClick":[{"run":"edit"}]}})")); + auto const bundle = registry.build(); + REQUIRE(bundle); + morph::exec::ThreadPoolExecutor pool{2}; + morph::backend::ServerConfig config; + config.services.push_back(std::make_shared(*bundle)); + auto const server = + std::make_shared(pool, std::make_shared(), std::move(config)); + auto const permitted = [&server](std::string principal) { + morph::wire::Envelope request; + request.kind = std::string{morph::ui::kCatalogKind}; + request.callId = 1; + request.body = "{}"; + request.session.principal = std::move(principal); + morph::wire::Envelope const reply = morph::wire::decode(server->handleInline(morph::wire::encode(request))); + REQUIRE(reply.kind == "ok"); + auto const parsed = morph::ui::parseCatalogReply(reply.body); + REQUIRE(parsed); + return parsed->permitted; + }; + // The catalog's permitted actions are what the client lowers the column by: the viewer's lack the edit action, + // so its column is read-only ("model table: a column whose action is not permitted is read-only" in + // tests/test_ui_table_model_*.cpp lowers that), and alice's have it. + CHECK_FALSE(std::ranges::contains(permitted("viewer"), std::string{"Lims_EditSpecimenCount"})); + CHECK(std::ranges::contains(permitted("alice"), std::string{"Lims_EditSpecimenCount"})); +} +// Mutation: the server's catalog listing every action as permitted (the viewer's column stays editable). diff --git a/tests/net/test_push_unloaded_rows.cpp b/tests/net/test_push_unloaded_rows.cpp new file mode 100644 index 000000000..b105ea92f --- /dev/null +++ b/tests/net/test_push_unloaded_rows.cpp @@ -0,0 +1,995 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Slow levels over the `net` transport (docs/spec/table/table.md, "Arrival", "The server level cache", "The view +// cache"): one server serving `bench::WideTableModel` with its recipe level cache attached, and clients sending raw +// envelopes. A reply never waits for a load; a level is loaded once for every client and only for what a query +// needs; an action's effects invalidate the cache; `announce` reaches the watchers of the record and its derived +// records; and no value crosses a row scope. +// +// The end of each case names the mutation it is meant to catch. These cases need a POSIX build, and none of +// those mutations has been run yet. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "table/wide_table_model.hpp" + +// NOLINTBEGIN(misc-use-internal-linkage): registered types must have external linkage. +namespace unloaded_rows { + +// A record derived from `WideTableModel.small`, and an action holding it, so a client may watch it. +struct UrSummary { + std::int64_t rows = 0; +}; +struct ReadSummary {}; + +// A row-scoped table: `p1` sees rows 0-499, `p2` rows 250-749, of one shared 1,000-row source with a recipe +// column `r` read through one level cache for both scopes. `UrEmptyScope` is the same table with `scope` left +// empty. +class UrModel { +public: + morph::table::ServedTable rows(morph::table::TableContext const& context); + morph::table::ServedTable emptyScope(morph::table::TableContext const& context); + UrSummary execute(ReadSummary const& action); +}; + +} // namespace unloaded_rows +// NOLINTEND(misc-use-internal-linkage) + +BRIDGE_REGISTER_RECORD(unloaded_rows::UrSummary, "UrSummary", morph::record::keyless, + morph::record::derivedFrom>) +BRIDGE_REGISTER_MODEL(unloaded_rows::UrModel, "UrModel") +BRIDGE_REGISTER_TABLE(unloaded_rows::UrModel, "urRows", &unloaded_rows::UrModel::rows, morph::table::rowScoped) +BRIDGE_REGISTER_TABLE(unloaded_rows::UrModel, "urEmptyScope", &unloaded_rows::UrModel::emptyScope, + morph::table::rowScoped) +BRIDGE_REGISTER_ACTION(unloaded_rows::UrModel, unloaded_rows::ReadSummary, "ReadSummary") + +namespace unloaded_rows { + +namespace { + +using morph::table::Cell; +using morph::table::RowId; + +// The shared rows, the scopes' sources and the recipe cache, with the loader's log. +struct UrState { + std::mutex mutex; + std::shared_ptr source; + std::map, std::less<>> scopes; + morph::exec::ThreadPoolExecutor loads{1}; + std::vector logged; + std::shared_ptr cache; + + UrState() { + source = std::make_shared(std::vector{ + {.id = "id", .kind = morph::table::ColumnKind::Integer, .comparator = {}, .format = {}, .level = {}}}); + std::vector keys; + std::vector> cells; + for (std::int64_t row = 0; row < 1'000; ++row) { + keys.emplace_back(row); + cells.push_back({Cell{row}}); + } + source->setRows(std::move(keys), std::move(cells)); + morph::table::LevelCacheOptions options; + options.records = {"UrModel.urRows", "UrModel.urEmptyScope"}; + options.level = "recipe"; + options.columns = { + {.id = "r", .kind = morph::table::ColumnKind::Text, .comparator = {}, .format = {}, .level = "recipe"}}; + options.loads = &loads; + cache = + std::make_shared(std::move(options), [this](std::span asked) { + std::vector>> out; + std::scoped_lock const lock{mutex}; + for (auto const& key : asked) { + logged.push_back(key); + out.emplace_back(key, std::vector{Cell{"r" + std::to_string(std::get(key))}}); + } + return out; + }); + } +}; + +UrState& urState() { + static UrState state; + return state; +} + +morph::table::ServedTable urTable(std::string_view principal, std::string scope) { + auto& state = urState(); + morph::table::ServedTable served; + served.description.id = "urRows"; + served.description.label = "rows"; + served.description.key = "id"; + served.description.levels = {"recipe"}; + served.description.columns = { + morph::table::TableColumn{.info = state.source->columns()[0], .label = "id", .group = {}}, + morph::table::TableColumn{.info = state.cache->columns()[0], .label = "r", .group = {}}}; + std::int64_t const first = principal == "p2" ? 250 : 0; + { + std::scoped_lock const lock{state.mutex}; + auto& scoped = state.scopes[std::string{principal}]; + if (scoped == nullptr) { + std::vector keys; + for (auto key = first; key < first + 500; ++key) { + keys.emplace_back(key); + } + scoped = morph::table::scoped(state.source, std::move(keys)); + } + served.source = scoped; + } + served.levels = {state.cache}; + served.scope = std::move(scope); + return served; +} + +} // namespace + +morph::table::ServedTable UrModel::rows(morph::table::TableContext const& context) { + return urTable(context.session.principal, context.session.principal); +} + +morph::table::ServedTable UrModel::emptyScope(morph::table::TableContext const& context) { + auto served = urTable(context.session.principal, {}); + served.description.id = "urEmptyScope"; + return served; +} + +UrSummary UrModel::execute(ReadSummary const& /*action*/) { return UrSummary{.rows = 1'000}; } + +} // namespace unloaded_rows + +namespace { + +using namespace std::chrono_literals; +namespace ui = morph::ui; +using morph::table::RowId; + +constexpr std::string_view kHello = "t-unloaded-hello"; +constexpr auto kCoalesce = 20ms; +constexpr std::string_view kWide = bench::kWideModelType; + +// Negotiates events for the connection its hello arrives on. +class Hello final : public morph::backend::IEnvelopeService { +public: + using IEnvelopeService::handle; + + [[nodiscard]] bool serves(std::string_view kind) const override { return kind == kHello; } + + [[nodiscard]] std::string handle(morph::wire::Envelope const& request, + morph::session::IAuthorizer const& /*authorizer*/) override { + return morph::wire::encode(morph::wire::makeOk(request.callId)); + } + + [[nodiscard]] std::string handle(morph::wire::Envelope const& request, + morph::session::IAuthorizer const& authorizer, + morph::backend::ConnectionFacts& facts) override { + facts.events = true; + return handle(request, authorizer); + } +}; + +// Takes the principal a client names as verified. +class NamedAuthorizer final : public morph::session::IAuthorizer { +public: + [[nodiscard]] bool authorize(morph::session::Context const& /*ctx*/, std::string_view /*modelType*/, + std::string_view /*actionType*/) const override { + return true; + } + + [[nodiscard]] std::optional authenticate(morph::session::Context const& ctx) const override { + return ctx.principal; + } +}; + +// One server on a socket over `WideTableModel` configured as given, its recipe cache attached. +struct Server { + explicit Server(bench::WideTableOptions small, bench::WideTableOptions wide = {.rows = 2'000, + .columns = 300, + .seed = 7, + .loadDelay = {}, + .recipePreloaded = 1.0, + .recipeBatch = 64, + .recipeFails = false}) { + bench::WideTableModel::recipeGate().release(); + bench::WideTableModel::configure(wide, small); + morph::backend::ServerConfig config; + config.services.push_back(std::make_shared()); + config.coalesceWindow = kCoalesce; + config.tableWork = tableWork; + server = std::make_shared(pool, std::make_shared(), + std::move(config)); + server->attach(bench::WideTableModel::recipeCache()); + server->attach(unloaded_rows::urState().cache); + socket = std::make_unique(*server, 0); + REQUIRE(socket->listen()); + url = "ws://127.0.0.1:" + std::to_string(static_cast(socket->port())); + } + + ~Server() { bench::WideTableModel::recipeGate().release(); } + + Server(Server const&) = delete; + Server& operator=(Server const&) = delete; + Server(Server&&) = delete; + Server& operator=(Server&&) = delete; + + morph::exec::ThreadPoolExecutor pool{4}; + std::shared_ptr tableWork = std::make_shared(2); + std::shared_ptr server; + std::unique_ptr socket; + std::string url; +}; + +// One client as `principal`: raw envelopes over a socket, and the `changes` events it receives. +struct Client { + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `Client(url, principal)` is a test helper whose arguments read differently at each call; a swap would fail the case's own assertion + Client(std::string const& url, std::string principal) : _principal{std::move(principal)} { + socket = std::make_unique(url); + REQUIRE(socket->waitForConnected()); + exchange = ui::exchangeOver(*socket, owner); + socket->setEventHandler( + [this](morph::wire::EventBody const& event) { + if (event.topic != morph::wire::kChangesTopic) { + return; + } + auto body = morph::wire::readChangesBody(event.payload.str); + REQUIRE(body); + changes.push_back(std::move(*body)); + }, + &owner); + morph::wire::Envelope hello; + hello.kind = std::string{kHello}; + auto const sent = send(std::move(hello)); + REQUIRE(sent.kind == "ok"); + } + + morph::wire::Envelope send(morph::wire::Envelope request) { + request.session.principal = _principal; + std::optional reply; + exchange(std::move(request), [&reply](ui::ExchangeReply answer) { reply = std::move(answer); }); + REQUIRE(pumpUntil([&] { return reply.has_value(); })); + REQUIRE(reply->has_value()); + return **reply; + } + + std::vector watch(std::vector records) { + morph::wire::Envelope env; + env.kind = std::string{morph::wire::kWatchKind}; + env.body = + glz::write_json(morph::wire::WatchBody{.records = std::move(records), .instances = {}, .replace = false}) + .value_or(std::string{}); + auto const reply = send(std::move(env)); + REQUIRE(reply.kind == "ok"); + auto const parsed = morph::wire::readWatchReply(reply.body); + REQUIRE(parsed); + return parsed->refusedRecords; + } + + std::uint64_t create(std::string const& modelType) { + auto const reply = send(morph::wire::makeRegister(modelType)); + REQUIRE(reply.kind == "ok"); + return reply.modelId; + } + + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `execute(instance, modelType, action, body)` is a test helper whose arguments read differently at each call; a swap would fail the case's own assertion + morph::wire::Envelope execute(std::uint64_t instance, std::string_view modelType, std::string const& action, + std::string body) { + morph::wire::Envelope env; + env.kind = "execute"; + env.modelId = instance; + env.modelType = std::string{modelType}; + env.actionType = action; + env.body = std::move(body); + return send(std::move(env)); + } + + template + bool pumpUntil(Done done, std::chrono::milliseconds budget = 10s) { + auto const deadline = std::chrono::steady_clock::now() + budget; + while (!done()) { + if (std::chrono::steady_clock::now() > deadline) { + return false; + } + if (!owner.runOnce()) { + std::this_thread::sleep_for(1ms); + } + } + return true; + } + + void pumpFor(std::chrono::milliseconds span) { + static_cast(pumpUntil([] { return false; }, span)); + } + + // The keys of every change of @p record received so far, and whether one came without keys. + std::vector keysOf(std::string_view record, bool* whole = nullptr) const { + std::vector keys; + for (auto const& body : changes) { + for (auto const& change : body.records) { + if (change.record != record) { + continue; + } + if (!change.keys) { + if (whole != nullptr) { + *whole = true; + } + continue; + } + for (auto const& key : *change.keys) { + keys.push_back(key.str); + } + } + } + return keys; + } + + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes): the client's executor, socket, exchange and received changes, which the cases drive and read directly + morph::exec::MainThreadExecutor owner; + std::unique_ptr socket; + ui::Exchange exchange; + std::vector changes; + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes) + +private: + std::string _principal; +}; + +morph::table::GenericPage pageOf(morph::wire::Envelope const& reply) { + REQUIRE(reply.kind == "ok"); + morph::table::GenericPage page; + REQUIRE_FALSE(glz::read_json(page, reply.body)); + return page; +} + +bench::WideTableOptions smallOptions(double preloaded, bool fails = false) { + return bench::WideTableOptions{.rows = 1'000, + .columns = 30, + .seed = 7, + .loadDelay = {}, + .recipePreloaded = preloaded, + .recipeBatch = 64, + .recipeFails = fails}; +} + +// Every key the recipe loader was given, sorted. +std::vector loggedKeys() { + std::vector out; + for (auto const& call : bench::WideTableModel::loaderCalls()) { + out.insert(out.end(), call.begin(), call.end()); + } + std::ranges::sort(out); + return out; +} + +std::vector keyRange(std::int64_t first, std::int64_t last) { + std::vector out; + for (auto key = first; key < last; ++key) { + out.emplace_back(key); + } + return out; +} + +bool waitFor(std::function const& done, std::chrono::milliseconds budget = 10s) { + auto const deadline = std::chrono::steady_clock::now() + budget; + while (!done()) { + if (std::chrono::steady_clock::now() > deadline) { + return false; + } + std::this_thread::sleep_for(2ms); + } + return true; +} + +constexpr std::string_view kRecipePage = + R"({"sort":[{"column":"id","dir":"asc"}],"columns":["id","d000","t001"],"page":{"offset":0,"limit":200}})"; + +} // namespace + +TEST_CASE("announce: a derived record is included, many keys are whole, an unregistered record is refused", + "[net][push][levels]") { + Server const server{smallOptions(1.0)}; + Client client{server.url, "alice"}; + REQUIRE(client.watch({"WideTableModel.small", "UrSummary"}).empty()); + + std::vector const three{RowId{std::int64_t{1}}, RowId{std::int64_t{2}}, RowId{std::int64_t{3}}}; + REQUIRE(server.server->announce("WideTableModel.small", morph::table::changeKeys(three))); + REQUIRE(client.pumpUntil([&] { return !client.keysOf("WideTableModel.small").empty(); })); + CHECK(client.keysOf("WideTableModel.small") == std::vector{"1", "2", "3"}); + bool summaryWhole = false; + static_cast(client.keysOf("UrSummary", &summaryWhole)); + CHECK(summaryWhole); + + client.changes.clear(); + REQUIRE(server.server->announce("WideTableModel.small", morph::table::changeKeys(keyRange(1, 4'098)))); + bool smallWhole = false; + REQUIRE(client.pumpUntil([&] { + static_cast(client.keysOf("WideTableModel.small", &smallWhole)); + return smallWhole; + })); + CHECK(client.keysOf("WideTableModel.small").empty()); + + client.changes.clear(); + CHECK_FALSE(server.server->announce("NoSuchRecord", std::vector{}).has_value()); + client.pumpFor(200ms); + CHECK(client.changes.empty()); + // Mutation: announce bypassing the derived-record walk (UrSummary is not told). +} + +TEST_CASE("table over the bridge: the first page arrives before the level", "[net][push][levels]") { + Server const server{smallOptions(0.0)}; + bench::WideTableModel::recipeGate().hold(); + Client client{server.url, "alice"}; + auto const instance = client.create(std::string{kWide}); + auto const page = pageOf(client.execute(instance, kWide, "Table.small", std::string{kRecipePage})); + REQUIRE(page.rows.size() == 200); + REQUIRE(page.unloadedRows.size() == 200); + for (std::size_t at = 0; at < 200; ++at) { + CHECK(std::cmp_equal(page.unloadedRows[at].index, at)); + CHECK(page.unloadedRows[at].levels == std::vector{"recipe"}); + CHECK(page.keys[at] == RowId{static_cast(at + 1)}); + CHECK(std::holds_alternative(page.rows[at][1])); + CHECK(std::holds_alternative(page.rows[at][2])); + } + // Mutation: the answer path waiting for its loader (the reply never comes while the gate is held). +} + +TEST_CASE("table over the bridge: a level loads only for what a query needs", "[net][push][levels]") { + { + Server const server{smallOptions(0.0)}; + Client client{server.url, "alice"}; + auto const instance = client.create(std::string{kWide}); + static_cast(pageOf(client.execute(instance, kWide, "Table.small", + R"({"columns":["id","i001"],"page":{"offset":0,"limit":200}})"))); + std::this_thread::sleep_for(200ms); + CHECK(bench::WideTableModel::loaderCalls().empty()); + } + { + Server const server{smallOptions(0.0)}; + Client client{server.url, "alice"}; + auto const instance = client.create(std::string{kWide}); + static_cast(pageOf(client.execute(instance, kWide, "Table.small", std::string{kRecipePage}))); + REQUIRE(waitFor([] { return bench::WideTableModel::recipeCache()->stats().loadedKeys >= 200; })); + CHECK(loggedKeys() == keyRange(1, 201)); + } + { + Server const server{smallOptions(0.0)}; + Client client{server.url, "alice"}; + auto const instance = client.create(std::string{kWide}); + static_cast(pageOf(client.execute( + instance, kWide, "Table.small", + R"({"sort":[{"column":"d000","dir":"asc"}],"columns":["id","i001"],"page":{"offset":0,"limit":200}})"))); + REQUIRE(waitFor([] { return bench::WideTableModel::recipeCache()->stats().loadedKeys >= 1'000; })); + CHECK(loggedKeys() == keyRange(1, 1'001)); + } + // Mutation: levelsNeeded returning every level (the first query loads its page's keys). +} + +TEST_CASE("table over the bridge: two clients load a value once", "[net][push][levels]") { + Server const server{smallOptions(0.0)}; + bench::WideTableModel::recipeGate().hold(); + Client first{server.url, "alice"}; + Client second{server.url, "carol"}; + auto const one = first.create(std::string{kWide}); + auto const two = second.create(std::string{kWide}); + static_cast(pageOf(first.execute(one, kWide, "Table.small", std::string{kRecipePage}))); + static_cast(pageOf(second.execute(two, kWide, "Table.small", std::string{kRecipePage}))); + bench::WideTableModel::recipeGate().release(); + REQUIRE(waitFor([] { return bench::WideTableModel::recipeCache()->stats().loadedKeys >= 200; })); + std::this_thread::sleep_for(100ms); + CHECK(bench::WideTableModel::recipeCache()->stats().loadedKeys == 200); + CHECK(loggedKeys() == keyRange(1, 201)); + // Mutation: want not checking the cache (each key is loaded again by the second client's want). +} + +TEST_CASE("table over the bridge: an updates effect invalidates without a call", "[net][push][levels]") { + Server const server{smallOptions(1.0)}; + Client client{server.url, "alice"}; + REQUIRE(client.watch({"WideTableModel.small"}).empty()); + auto const instance = client.create(std::string{kWide}); + auto const before = pageOf(client.execute(instance, kWide, "Table.small", std::string{kRecipePage})); + CHECK(before.unloadedRows.empty()); + REQUIRE(client.execute(instance, kWide, "EditWideRow", R"({"row":4,"column":"i001","value":1})").kind == "ok"); + // The observer runs before the change's event is queued, so the event says the invalidation happened. + REQUIRE(client.pumpUntil([&] { return !client.keysOf("WideTableModel.small").empty(); })); + bench::WideTableModel::recipeGate().hold(); + auto const after = pageOf(client.execute(instance, kWide, "Table.small", std::string{kRecipePage})); + REQUIRE(after.unloadedRows.size() == 1); + CHECK(after.unloadedRows[0].index == 4); // the row keyed 5 + bench::WideTableModel::recipeGate().release(); + REQUIRE(waitFor([] { return bench::WideTableModel::recipeCache()->stats().loadedKeys >= 1; })); + CHECK(loggedKeys() == std::vector{RowId{std::int64_t{5}}}); + // Mutation: fanOut not handing the change to observers (the row keyed 5 stays loaded and nothing is loaded). +} + +TEST_CASE("table over the bridge: no value crosses a scope", "[net][push][levels]") { + Server const server{smallOptions(1.0)}; + unloaded_rows::urState().cache->invalidateAll(); + { + std::scoped_lock const lock{unloaded_rows::urState().mutex}; + unloaded_rows::urState().logged.clear(); + } + Client p1{server.url, "p1"}; + Client p2{server.url, "p2"}; + auto const one = p1.create("UrModel"); + auto const two = p2.create("UrModel"); + std::string const query = R"({"columns":["id","r"],"page":{"offset":0,"limit":500}})"; + auto const first = pageOf(p1.execute(one, "UrModel", "Table.urRows", query)); + auto const second = pageOf(p2.execute(two, "UrModel", "Table.urRows", query)); + CHECK(first.keys == keyRange(0, 500)); + CHECK(second.keys == keyRange(250, 750)); + REQUIRE(waitFor([] { return unloaded_rows::urState().cache->stats().loadedKeys >= 750; })); + std::vector logged; + { + std::scoped_lock const lock{unloaded_rows::urState().mutex}; + logged = unloaded_rows::urState().logged; + } + for (std::int64_t key = 250; key < 500; ++key) { + CHECK(std::ranges::count(logged, RowId{key}) == 1); + } + // Each scope's source has its own snapshot, so the snapshot identity alone keeps the two views apart; the + // scope in the view key is held by "table over the bridge: two scopes over one snapshot get two views". + // Mutation: the scoped source answering every shared row (each reply holds rows of the other scope). +} + +TEST_CASE("table over the bridge: a row-scoped table announces without keys", "[net][push][levels]") { + Server const server{smallOptions(1.0)}; + unloaded_rows::urState().cache->invalidateAll(); + Client p1{server.url, "p1"}; + REQUIRE(p1.watch({"UrModel.urRows"}).empty()); + auto const instance = p1.create("UrModel"); + static_cast(pageOf( + p1.execute(instance, "UrModel", "Table.urRows", R"({"columns":["id","r"],"page":{"offset":0,"limit":50}})"))); + bool whole = false; + REQUIRE(p1.pumpUntil([&] { + static_cast(p1.keysOf("UrModel.urRows", &whole)); + return whole; + })); + CHECK(p1.keysOf("UrModel.urRows").empty()); + auto const refused = p1.execute(instance, "UrModel", "Table.urEmptyScope", R"({"page":{"offset":0,"limit":5}})"); + CHECK(refused.kind == "err"); + REQUIRE(refused.refusal.has_value()); + CHECK(refused.refusal->code == "table.sourceContract"); + // Mutation: the record registered without privateKeys (p1 is told the arrived rows' keys). +} + +TEST_CASE("table over the bridge: failed keys are not loaded again inside the delay", "[net][push][levels]") { + Server const server{smallOptions(0.0, true)}; + Client client{server.url, "alice"}; + REQUIRE(client.watch({"WideTableModel.small"}).empty()); + auto const instance = client.create(std::string{kWide}); + std::string const sorted = + R"({"sort":[{"column":"d000","dir":"asc"}],"columns":["id","d000"],"page":{"offset":0,"limit":200}})"; + static_cast(pageOf(client.execute(instance, kWide, "Table.small", sorted))); + REQUIRE(waitFor([] { return bench::WideTableModel::recipeCache()->stats().failedLoads >= 1'000; })); + auto const calls = bench::WideTableModel::loaderCalls().size(); + for (int request = 0; request < 10; ++request) { + auto const page = pageOf(client.execute(instance, kWide, "Table.small", sorted)); + CHECK(page.awaiting.empty()); + CHECK(page.failed == std::vector{"recipe"}); + CHECK(std::ranges::all_of(page.unloadedRows, [](morph::table::UnloadedRow const& row) { + return row.failed == std::vector{"recipe"}; + })); + } + std::this_thread::sleep_for(100ms); + CHECK(bench::WideTableModel::loaderCalls().size() == calls); + client.pumpFor(100ms); + std::size_t announced = 0; + for (auto const& key : client.keysOf("WideTableModel.small")) { + static_cast(key); + ++announced; + } + CHECK(announced == 1'000); // each failed key once + static_cast(pageOf(client.execute( + instance, kWide, "Table.small", + R"({"sort":[{"column":"d000","dir":"asc"}],"columns":["id","d000"],"page":{"offset":0,"limit":200},"retry":true})"))); + REQUIRE(waitFor([] { return bench::WideTableModel::recipeCache()->stats().failedLoads >= 2'000; })); + CHECK(bench::WideTableModel::loaderCalls().size() == calls + 16); // ceil(1000 / 64) + // Mutation: a failed key wanted again by every request (the ten requests call the loader). +} + +// ── A window and a query cache over the bridge ────────────────────────────── + +namespace { + +// Forwards every call, counting page requests (a body without `keys`) and keyed requests apart. +class CountingChannel final : public ui::ModelChannel { +public: + explicit CountingChannel(std::shared_ptr inner) : _inner{std::move(inner)} {} + + [[nodiscard]] morph::async::Completion execute(std::string const& actionId, + std::string const& bodyJson, + ui::CallOptions options) override { + if (!actionId.ends_with(".describe")) { + if (bodyJson.contains(R"("keys")")) { + ++keyedRequests; + } else { + ++pageRequests; + } + } + return _inner->execute(actionId, bodyJson, std::move(options)); + } + + [[nodiscard]] ui::ChannelFacts facts() const override { return _inner->facts(); } + + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes): the request counters the cases read after a run + int pageRequests = 0; + int keyedRequests = 0; + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes) + +private: + std::shared_ptr _inner; +}; + +// One client as a UI session over the bridge: its watches and events go through the session, its window's fetches +// through `Session::read`. +struct SessionClient { + explicit SessionClient(std::string const& url, ui::Catalog catalog = {}) { + auto made = std::make_unique(url); + socket = made.get(); + REQUIRE(socket->waitForConnected()); + exchange = ui::exchangeOver(*socket, owner); + bridge = std::make_unique(std::move(made), owner); + dispatcher = std::make_unique(*bridge, &owner); + ui::SessionOptions options; + options.catalog = std::move(catalog); + options.watcher = ui::watcherOver(exchange, [] { return morph::session::Context{}; }, &owner); + session = std::make_unique(runtime, std::move(options)); + socket->setEventHandler([this](morph::wire::EventBody const& event) { session->deliverEvent(event); }, &owner); + bool negotiated = false; + morph::wire::Envelope hello; + hello.kind = std::string{kHello}; + exchange(std::move(hello), [&negotiated](ui::ExchangeReply const& reply) { + negotiated = reply.has_value() && reply->kind == "ok"; + }); + REQUIRE(pumpUntil([&] { return negotiated; })); + channel = std::make_shared( + dispatcher->bind(std::string{kWide}, morph::bridge::BindSharing::Private, std::string{})); + } + + template + bool pumpUntil(Done done, std::chrono::milliseconds budget = 10s) { + auto const deadline = std::chrono::steady_clock::now() + budget; + while (!done()) { + if (std::chrono::steady_clock::now() > deadline) { + return false; + } + if (!owner.runOnce()) { + std::this_thread::sleep_for(1ms); + } + } + return true; + } + + void pumpFor(std::chrono::milliseconds span) { + static_cast(pumpUntil([] { return false; }, span)); + } + + // Reads an action's reply text through `Session::read`. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): `read(action, body)` is a test helper whose arguments read differently at each call; a swap would fail the case's own assertion + std::string read(std::string const& action, std::string const& body) { + auto json = ui::parseJson(body); + REQUIRE(json); + auto value = ui::valueFromJson(*json); + REQUIRE(value); + std::optional text; + bool failed = false; + auto completion = session->read(channel, action, *value); + completion.then([&text](std::string const& reply) { text = reply; }) + .onError([&failed](std::exception_ptr const&) { failed = true; }); + REQUIRE(pumpUntil([&] { return text.has_value() || failed; })); + REQUIRE(text.has_value()); + return *text; + } + + morph::exec::MainThreadExecutor owner; + morph::reactive::Runtime runtime{owner}; + morph::net::SocketBackend* socket = nullptr; + ui::Exchange exchange; + std::unique_ptr bridge; + std::unique_ptr dispatcher; + std::unique_ptr session; + std::shared_ptr channel; +}; + +bench::WideTableOptions gatedOptions() { + return bench::WideTableOptions{.rows = 1'000, + .columns = 30, + .seed = 7, + .loadDelay = {}, + .recipePreloaded = 0.0, + .recipeBatch = 20, + .recipeFails = false}; +} + +// A window's page fetch as the body of `Table.small`, sorted by key. +std::string pageBody(morph::table::PageFetch const& fetch) { + morph::table::TableQuery query; + query.sort = {morph::table::SortKey{.column = "id", .dir = morph::table::SortDirection::Ascending}}; + query.columns = fetch.columns; + query.page = fetch.request; + return glz::write_json(query).value_or(std::string{}); +} + +// A window's keyed fetch as the body of `Table.small`, under the same sort. +std::string keyedBody(morph::table::RowsFetch const& fetch) { + morph::table::TableQuery query; + query.sort = {morph::table::SortKey{.column = "id", .dir = morph::table::SortDirection::Ascending}}; + query.columns = fetch.columns; + query.page = morph::table::PageRequest{.offset = 0, .limit = 200}; + query.keys = fetch.keys; + return glz::write_json(query).value_or(std::string{}); +} + +} // namespace + +// Mutations: refresh asking for every held key (the plan holds 230 keys, not 21); refresh dropping the keys the +// window does not hold (the plan misses the loaded keys of rows past the held ones). Unbuilt on the host that wrote +// it, and neither mutation has been run. +TEST_CASE("table over the bridge: exactly the arrived rows update, without polling", "[net][push][levels]") { + Server const server{gatedOptions()}; + bench::WideTableModel::recipeGate().hold(); + SessionClient client{server.url}; + + // 1. Watch, then fetch. + std::optional watch; + std::vector> events; + { + auto watching = + client.session->watchRecord("WideTableModel.small", [&](morph::effects::RecordChange const& change) { + std::vector keys; + for (auto const& key : change.keys.value_or(std::vector{})) { + if (auto id = morph::table::rowIdOf(key)) { + keys.push_back(*id); + } + } + events.push_back(std::move(keys)); + }); + watching.then([&watch](ui::WatchHolder const& holder) { watch = holder; }); + REQUIRE(client.pumpUntil([&] { return watch.has_value(); })); + } + morph::table::TableDescription description; + REQUIRE_FALSE( + glz::read(description, client.read("Table.small.describe", "{}"))); + morph::table::PageWindow window{200, 8}; + std::vector const columns{"id", "d000"}; + auto const fetches = window.visible(0, 30, columns); + REQUIRE(fetches.size() == 2); // pages 0 and 1: no total is known yet + for (auto const& fetch : fetches) { + auto page = morph::table::readGenericPage(client.read("Table.small", pageBody(fetch)), description); + REQUIRE(page.has_value()); + REQUIRE(window.accept(fetch, std::move(*page))); + } + CHECK(client.channel->pageRequests == 2); + CHECK(client.channel->keyedRequests == 0); + for (std::int64_t row = 0; row < 400; ++row) { + INFO("view row " << row); + CHECK(std::ranges::equal(window.unloadedLevels(row).levels, std::vector{"recipe"})); + } + + // 2. Nothing is fetched because time passed. + client.pumpFor(200ms); + CHECK(client.channel->pageRequests == 2); + CHECK(client.channel->keyedRequests == 0); + + // 3. One loader call of 20 keys; the cache stores, then announces them. + bench::WideTableModel::recipeGate().release(1); + REQUIRE(waitFor([] { return !bench::WideTableModel::loaderCalls().empty(); })); + auto const loaded = bench::WideTableModel::loaderCalls().front(); + REQUIRE(loaded.size() == 20); + REQUIRE(client.pumpUntil([&] { return !events.empty(); })); + + // 4. The plan asks for the arrived keys and the one held run's probe. + std::vector expected = loaded; + if (std::ranges::find(expected, RowId{std::int64_t{1}}) == expected.end()) { + expected.emplace_back(std::int64_t{1}); + } + auto const plan = window.refresh(events.front()); + REQUIRE(plan.kind == morph::table::Refresh::Rows); + CHECK(std::ranges::is_permutation(plan.rows.keys, expected)); + auto reply = morph::table::readGenericPage(client.read("Table.small", keyedBody(plan.rows)), description); + REQUIRE(reply.has_value()); + CHECK(client.channel->pageRequests == 2); + CHECK(client.channel->keyedRequests == 1); + + // 5. Exactly the arrived rows (and the probe's row) are patched. + auto const replaced = window.patch(plan.rows, std::move(*reply)); + std::vector rows; + for (auto const& key : expected) { + // NOLINTNEXTLINE(performance-inefficient-vector-operation): `rows` is a fixture list built once; sizing it first would not change what the case checks + rows.push_back(std::get(key) - 1); + } + std::ranges::sort(rows); + CHECK(replaced == rows); + for (auto const& key : loaded) { + auto const row = std::get(key) - 1; + INFO("view row " << row); + CHECK(window.unloadedLevels(row).levels.empty()); + auto const* const cell = window.cell(row, "d000"); + REQUIRE(cell != nullptr); + CHECK_FALSE(std::holds_alternative(*cell)); + CHECK_FALSE(std::holds_alternative(*cell)); + } + for (std::int64_t row = 0; row < 400; ++row) { + if (std::ranges::find(loaded, RowId{row + 1}) == loaded.end()) { + INFO("view row " << row); + CHECK(std::ranges::equal(window.unloadedLevels(row).levels, std::vector{"recipe"})); + } + } + bench::WideTableModel::recipeGate().release(); +} + +namespace { + +// Binds through a dispatcher and counts the calls of every channel it hands out. +class CountingDispatcher final : public ui::Dispatcher { +public: + explicit CountingDispatcher(ui::Dispatcher& inner) : _inner{&inner} {} + + [[nodiscard]] std::shared_ptr bind(std::string const& typeId, morph::bridge::BindSharing sharing, + std::string const& instanceKey) override { + auto channel = std::make_shared(_inner->bind(typeId, sharing, instanceKey)); + channels.push_back(channel); + return channel; + } + + [[nodiscard]] int pageRequests() const { + int total = 0; + for (auto const& channel : channels) { + total += channel->pageRequests; + } + return total; + } + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes): `channels` collects the counting channels the case inspects + std::vector> channels; + +private: + ui::Dispatcher* _inner; +}; + +} // namespace + +// Mutation: the cache looking for a key member in an opaque entry (the arrival's keys match no row, and nothing +// refetches). Unbuilt on the host that wrote it, and the mutation has not been run. +TEST_CASE("table over the bridge: the same arrival through the query cache", "[net][push][levels]") { + Server const server{gatedOptions()}; + bench::WideTableModel::recipeGate().hold(); + ui::author::CatalogFacts facts; + facts.action>(); + SessionClient client{server.url, facts.catalog()}; + CountingDispatcher counting{*client.dispatcher}; + ui::Interpreter interpreter{*client.session, counting, ui::InterpreterOptions{}}; + constexpr std::string_view kSmall = R"({ + "vocab": "ui/1", "id": "small", + "models": { "wide": { "type": "WideTableModel" } }, + "queries": { "page": { "model": "wide", "action": "Table.small", + "body": { "obj": { "sort": { "list": [ { "obj": { "column": "id", "dir": "asc" } } ] }, + "columns": { "list": [ "id", "d000" ] }, + "page": { "obj": { "offset": 0, "limit": 200 } } } } } }, + "view": { "kind": "text", "testId": "rows", "text": { "fn": "format", "args": [ "{0}", { "query": "page" } ] } } })"; + auto loaded = ui::loadDocumentText(kSmall, ui::LoadOptions{.catalog = facts.catalog()}); + if (!loaded) { + FAIL(loaded.error().message()); + } + ui::testing::RecordingBackend view; + auto const mounted = interpreter.mount(std::make_shared(std::move(*loaded)), {}, view, {}); + REQUIRE(mounted.has_value()); + REQUIRE(client.pumpUntil([&] { return counting.pageRequests() == 1; })); + client.pumpFor(200ms); + REQUIRE(counting.pageRequests() == 1); + CHECK(client.session->cacheSize() == 1); + + // The arrival marks the one entry, which fetches its page once more: one page request per marked entry. + bench::WideTableModel::recipeGate().release(1); + REQUIRE(waitFor([] { return !bench::WideTableModel::loaderCalls().empty(); })); + CHECK(client.pumpUntil([&] { return counting.pageRequests() == 2; })); + client.pumpFor(200ms); + CHECK(counting.pageRequests() == 2); + bench::WideTableModel::recipeGate().release(); +} + +// E1 and E2 over the bridge: the first page of the sorted 100,000 x 300 table with `recipe` unloaded, from request +// to accepted page; and from a loader's return to patched rows, for 20 rows. Unbuilt and not run on the host that +// wrote it. +TEST_CASE("table benchmark: E1 E2 a window over the bridge", "[.benchmark][net]") { + Server const server{gatedOptions(), bench::WideTableOptions{.rows = 100'000, + .columns = 300, + .seed = 7, + .loadDelay = {}, + .recipePreloaded = 0.0, + .recipeBatch = 20, + .recipeFails = false}}; + bench::WideTableModel::recipeGate().hold(); + SessionClient client{server.url}; + morph::table::TableDescription description; + REQUIRE_FALSE( + glz::read(description, client.read("Table.wide.describe", "{}"))); + std::optional watch; + std::vector> events; + auto watching = + client.session->watchRecord("WideTableModel.wide", [&](morph::effects::RecordChange const& change) { + std::vector keys; + for (auto const& key : change.keys.value_or(std::vector{})) { + if (auto id = morph::table::rowIdOf(key)) { + keys.push_back(*id); + } + } + events.push_back(std::move(keys)); + }); + watching.then([&watch](ui::WatchHolder const& holder) { watch = holder; }); + REQUIRE(client.pumpUntil([&] { return watch.has_value(); })); + morph::table::PageWindow window{200, 8}; + std::vector columns; + for (auto const& column : description.columns) { + // NOLINTNEXTLINE(performance-inefficient-vector-operation): `columns` is a fixture list built once; sizing it first would not change what the case checks + columns.push_back(column.info.id); + } + auto const started = std::chrono::steady_clock::now(); + auto const fetches = window.visible(0, 30, columns); + REQUIRE_FALSE(fetches.empty()); + auto page = morph::table::readGenericPage(client.read("Table.wide", pageBody(fetches.front())), description); + REQUIRE(page.has_value()); + REQUIRE(window.accept(fetches.front(), std::move(*page))); + auto const e1 = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); + std::println("| E1 | first page, request to accepted | {:.3f} ms |", e1); + + std::vector samples; + for (int round = 0; round < 20; ++round) { + events.clear(); + auto const calls = bench::WideTableModel::loaderCalls().size(); + bench::WideTableModel::recipeGate().release(1); + REQUIRE(waitFor([&] { return bench::WideTableModel::loaderCalls().size() > calls; })); + auto const returned = std::chrono::steady_clock::now(); + REQUIRE(client.pumpUntil([&] { return !events.empty(); })); + auto const plan = window.refresh(events.front()); + if (plan.kind != morph::table::Refresh::Rows) { + continue; + } + auto reply = morph::table::readGenericPage(client.read("Table.wide", keyedBody(plan.rows)), description); + REQUIRE(reply.has_value()); + static_cast(window.patch(plan.rows, std::move(*reply))); + samples.push_back( + std::chrono::duration(std::chrono::steady_clock::now() - returned).count()); + } + REQUIRE_FALSE(samples.empty()); + std::ranges::sort(samples); + std::println("| E2 | loader return to patched rows, 20 rows, p50 / p99 | {:.3f} / {:.3f} ms |", + samples[samples.size() / 2], samples.back()); + bench::WideTableModel::recipeGate().release(); +} diff --git a/tests/qt/test_qt_keywords.cpp b/tests/qt/test_qt_keywords.cpp index a8cce4832..fb2f787ed 100644 --- a/tests/qt/test_qt_keywords.cpp +++ b/tests/qt/test_qt_keywords.cpp @@ -13,7 +13,9 @@ #include #include #include +#include #include +#include namespace ui = morph::ui::author; diff --git a/tests/qt_quick/CMakeLists.txt b/tests/qt_quick/CMakeLists.txt index 5cc8f24b9..dfe75a17d 100644 --- a/tests/qt_quick/CMakeLists.txt +++ b/tests/qt_quick/CMakeLists.txt @@ -24,6 +24,8 @@ add_executable(morph_qt_quick_tests test_qt_quick_theme.cpp test_qt_quick_automation.cpp test_qt_quick_inspector.cpp + wide_rows_document.hpp + bench_qt_quick_table.cpp ) target_link_libraries(morph_qt_quick_tests PRIVATE @@ -34,6 +36,7 @@ target_link_libraries(morph_qt_quick_tests # morph_test_main; morph_test_log_level carries the --log-level helper. Catch2::Catch2 morph_test_log_level + "$" ) # The widgets and the context are private to morph_qt_quick (src/qt_quick/); the tests include them as # "qt_quick/.hpp", and the interpreter harness from tests/. @@ -63,6 +66,7 @@ cmake_path(GET _morph_qq_core_dll PARENT_PATH _morph_qq_bin_dir) foreach(_morph_qq_tests IN ITEMS morph_qt_quick_tests morph_qt_quick_frontend_tests) catch_discover_tests(${_morph_qq_tests} DISCOVERY_MODE PRE_TEST + TEST_SPEC "~[heavy]" DL_PATHS "${_morph_qq_bin_dir}" PROPERTIES TIMEOUT 120 LABELS "qt_quick" ENVIRONMENT "QT_QPA_PLATFORM=offscreen" ) @@ -71,6 +75,15 @@ unset(_morph_qq_tests) unset(_morph_qq_core_dll) unset(_morph_qq_bin_dir) +# The [heavy] cases mount tables of hundreds of rows, or 100,000 rows by 300 columns, in the QML table. Each is seconds +# of CPU alone and far longer in a debug build sharing the machine with a parallel run, where they overran the +# timeout. They are discovered out of the set above (`~[heavy]`) and run here as one test, so RUN_SERIAL gives them the +# machine to themselves: they assert counts of rows scanned and cells created, never a time, so the wait is the only +# thing the load changes. +add_test(NAME "qt_quick table: the cases that mount large tables" COMMAND morph_qt_quick_tests "[heavy]") +set_tests_properties("qt_quick table: the cases that mount large tables" PROPERTIES + LABELS "qt_quick" TIMEOUT 900 RUN_SERIAL TRUE ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + # The chart's Canvas paints at the device pixel ratio: its cases run again at a ratio of 2, where a 1 px line must # still be one solid line of device pixels in its colour. add_test(NAME qt_quick_chart_scale_2 COMMAND morph_qt_quick_tests "[chart]") diff --git a/tests/qt_quick/bench_qt_quick_table.cpp b/tests/qt_quick/bench_qt_quick_table.cpp new file mode 100644 index 000000000..3f0e9cd11 --- /dev/null +++ b/tests/qt_quick/bench_qt_quick_table.cpp @@ -0,0 +1,451 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The frontend baseline of docs/spec/table/table.md ("The frontend at 300 columns"): a `rows` table of the wide-table +// fixture's 2,000 x 300 cells in a 1,280 x 800 offscreen window, before any column window exists. Hidden; run it by +// tag on a Release build with QT_QPA_PLATFORM=offscreen: +// +// morph_qt_quick_tests "[.benchmark][baseline]" +// +// The windowed case measures the same figures on a table over a `TableSource` with the column window: +// +// morph_qt_quick_tests "[.benchmark][windowed]" +// +// A frame is timed as the spec's CI method says: the test moves the scroll position one step, then times the work +// that step causes on the software scene graph -- the owner's realization, Qt's events, and polish, sync and render +// through QQuickWindow::grabWindow. It is CPU time for one frame's work, comparable between commits on one machine. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "qt_quick/widget.hpp" +#include "qt_quick_harness.hpp" +#include "table/wide_table_model.hpp" +#include "ui_fake_rows.hpp" +#include "ui_interpreter_support.hpp" +#include "wide_rows_document.hpp" + +namespace ui = morph::ui; +namespace detail = morph::qt_quick::detail; +using morph::qt_quick::testing::Scene; + +namespace { + +using Clock = std::chrono::steady_clock; + +struct Percentiles { + double p10 = 0; + double p50 = 0; + double p90 = 0; + double p99 = 0; +}; + +Percentiles percentilesOf(std::vector samples) { + std::ranges::sort(samples); + auto const at = [&](double q) { + auto const index = static_cast(std::lround(q * static_cast(samples.size() - 1))); + return samples[std::min(index, samples.size() - 1)]; + }; + return Percentiles{.p10 = at(0.1), .p50 = at(0.5), .p90 = at(0.9), .p99 = at(0.99)}; +} + +// Bounds every step of the baseline: a step that runs past its budget is named on stderr and ends the process with +// exit code 3, so a step that blocks is a reported failure and not a run that never ends. +class Watchdog { +public: + Watchdog() = default; + Watchdog(Watchdog const&) = delete; + Watchdog& operator=(Watchdog const&) = delete; + Watchdog(Watchdog&&) = delete; + Watchdog& operator=(Watchdog&&) = delete; + ~Watchdog() = default; + + // Starts @p name, which must end within @p budget. + void step(std::string name, std::chrono::seconds budget) { + std::scoped_lock const lock{_mutex}; + auto const now = Clock::now(); + if (!_name.empty()) { + std::println(stderr, "qt quick baseline: '{}' took {:.1f} s", _name, + std::chrono::duration(now - _began).count()); + } + std::println(stderr, "qt quick baseline: {} (budget {} s)", name, budget.count()); + static_cast(std::fflush(stderr)); + _name = std::move(name); + _budget = budget; + _began = now; + _deadline = now + budget; + } + +private: + void watch(std::stop_token const& stop) { + while (!stop.stop_requested()) { + std::this_thread::sleep_for(std::chrono::milliseconds{200}); + std::scoped_lock const lock{_mutex}; + if (Clock::now() > _deadline) { + std::println(stderr, "qt quick baseline: FAILED: '{}' ran past its {} s budget", _name, + _budget.count()); + static_cast(std::fflush(stderr)); + static_cast(std::fflush(stdout)); + std::_Exit(3); + } + } + } + + std::mutex _mutex; + std::string _name; + std::chrono::seconds _budget{0}; + Clock::time_point _began; + Clock::time_point _deadline = Clock::time_point::max(); + std::jthread _thread{[this](std::stop_token const& stop) { watch(stop); }}; // last: starts once the rest exists +}; + +// One client on the Qt Quick backend in a 1,280 x 800 window, with no model behind it: the table's rows are literal. +struct BenchHarness { + Scene scene; + morph::reactive::testing::ManualScheduler scheduler; + ui::Session session{scene.runtime(), ui::SessionOptions{.scheduler = &scheduler, + .clock = [this] { return scheduler.now(); }, + .keepUnused = std::chrono::minutes{5}, + .catalog = {}, + .classify = {}}}; + ui::testing::ScriptedDispatcher dispatcher{scene.owner()}; + ui::Interpreter interpreter{session, dispatcher, ui::InterpreterOptions{}}; + + BenchHarness() { + scene.window().resize(1280, 800); + scene.settle(); + } + + // Runs what one step of scrolling causes, and renders the frame; returns its time in milliseconds. + double frame() { + auto const began = Clock::now(); + scene.owner().runAll(); + QCoreApplication::processEvents(QEventLoop::AllEvents); + scene.owner().runAll(); + QCoreApplication::processEvents(QEventLoop::AllEvents); + QImage const image = scene.window().grabWindow(); + auto const millis = std::chrono::duration(Clock::now() - began).count(); + REQUIRE_FALSE(image.isNull()); + return millis; + } +}; + +// The table reports its visible range to C++ only when it scrolls, so after a mount or a resize it holds the rows +// it had; a scroll of one pixel and back realizes what the viewport shows, which is what F2 to F5 measure. +void reportRange(BenchHarness& harness, QQuickItem& flick) { + double const at = flick.property("contentY").toReal(); + flick.setProperty("contentY", at + 1.0); + static_cast(harness.frame()); + flick.setProperty("contentY", at); + static_cast(harness.frame()); + harness.scene.settle(); +} + +// Scrolls @p flick's @p property from its current value by @p step a frame for @p frames frames, timing each. +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the step per frame, then the limit, as the cases state them. +std::vector scrollFrames(BenchHarness& harness, QQuickItem& flick, char const* property, double step, + int frames, double limit) { + std::vector times; + times.reserve(static_cast(frames)); + double position = flick.property(property).toReal(); + for (int index = 0; index < frames; ++index) { + position = std::min(limit, position + step); + flick.setProperty(property, position); + times.push_back(harness.frame()); + } + return times; +} + +void printFrames(std::string_view scenario, std::vector const& times) { + auto const p = percentilesOf(times); + auto const over = std::ranges::count_if(times, [](double t) { return t > 16.6; }); + std::println("| {} | {} | {:.2f} | {:.2f}-{:.2f} | {:.2f} | {} |", scenario, times.size(), p.p50, p.p10, p.p90, + p.p99, over); + static_cast(std::fflush(stdout)); +} + +} // namespace + +TEST_CASE("qt quick baseline: F2 to F5 on a rows table of 2,000 x 300", "[.benchmark][baseline]") { + using std::chrono::seconds; + Watchdog watchdog; + watchdog.step("mount: the document's text", seconds{120}); + bench::WideTableSource const source{{.rows = 2'000, .columns = 300, .seed = 7}}; + std::string const document = bench::wideRowsDocument(source); + BenchHarness harness; + auto const memoryBefore = bench::processBytes(); + auto const mountBegan = Clock::now(); + watchdog.step("mount: parse", seconds{300}); + auto const loaded = ui::testing::loadOrFail(document); + watchdog.step("mount: interpreter mount", seconds{300}); + auto const screen = harness.interpreter.mount(loaded, {}, harness.scene.backend()); + REQUIRE(screen.has_value()); + watchdog.step("mount: settle", seconds{300}); + harness.scene.settle(); + watchdog.step("mount: first frame", seconds{300}); + static_cast(harness.frame()); + auto const mountMillis = std::chrono::duration(Clock::now() - mountBegan).count(); + + detail::ItemBase const* const table = detail::findWidget(QStringLiteral("wide")); + REQUIRE(table != nullptr); + QQuickItem const* const tableItem = table->item(); + REQUIRE(tableItem != nullptr); + auto* const flick = tableItem->findChild(QStringLiteral("flick")); + auto* const hflick = tableItem->findChild(QStringLiteral("hflick")); + REQUIRE(flick != nullptr); + REQUIRE(hflick != nullptr); + REQUIRE(tableItem->property("totalRows").toInt() == 2'000); + int const realizedAtMount = tableItem->property("realizedCount").toInt(); + watchdog.step("first range report", seconds{120}); + reportRange(harness, *flick); + int const realized = tableItem->property("realizedCount").toInt(); + REQUIRE(realized >= 30); + + // F2: widgets alive, and header cells. + auto const widgets = detail::liveWidgets().size(); + std::size_t headers = 0; + for (QQuickItem const* const item : tableItem->findChildren()) { + headers += item->objectName().startsWith(QStringLiteral("header")) ? 1U : 0U; + } + std::println( + "\nF2: a rows table of 2,000 x 300, 1,280 x 800, mounted in {:.0f} ms (document parse included), {} rows " + "realized at the mount\n\n" + "| realized rows | widgets alive | header cells | widgets per realized row |\n|---:|---:|---:|---:|\n" + "| {} | {} | {} | {:.1f} |", + mountMillis, realizedAtMount, realized, widgets, headers, + static_cast(widgets) / static_cast(std::max(realized, 1))); + static_cast(std::fflush(stdout)); + + // F3 and F4: frame times of vertical and horizontal scrolls. + double const rowHeight = flick->property("contentHeight").toReal() / 2'000.0; + double const columnWidth = hflick->property("contentWidth").toReal() / 300.0; + double const bottom = std::max(0.0, flick->property("contentHeight").toReal() - flick->height()); + double const right = std::max(0.0, hflick->property("contentWidth").toReal() - hflick->width()); + REQUIRE(rowHeight > 0); + REQUIRE(columnWidth > 0); + REQUIRE(right > 0); + std::println( + "\nF3, F4: frame time, CPU, software scene graph, offscreen (row {:.1f} px, column {:.1f} px)\n\n" + "| scroll | frames | p50 ms | p10-p90 ms | p99 ms | frames over 16.6 ms |\n|---|---:|---:|---:|---:|---:|", + rowHeight, columnWidth); + static_cast(std::fflush(stdout)); + constexpr int kFrames = 120; // two seconds at 60 frames a second + struct Scroll { + char const* name; + QQuickItem* flickable; + char const* property; + double step; + double limit; + }; + std::vector const scrolls{ + {.name = "F3: vertical, 20 rows/s", + .flickable = flick, + .property = "contentY", + .step = rowHeight * 20.0 / 60.0, + .limit = bottom}, + {.name = "F3: vertical fling, 2,000 rows/s", + .flickable = flick, + .property = "contentY", + .step = rowHeight * 2'000.0 / 60.0, + .limit = bottom}, + {.name = "F3: thumb drag across the table in 2 s", + .flickable = flick, + .property = "contentY", + .step = bottom / kFrames, + .limit = bottom}, + {.name = "F4: horizontal, 10 columns/s", + .flickable = hflick, + .property = "contentX", + .step = columnWidth * 10.0 / 60.0, + .limit = right}, + {.name = "F4: horizontal fling, 100 columns/s", + .flickable = hflick, + .property = "contentX", + .step = columnWidth * 100.0 / 60.0, + .limit = right}, + }; + for (Scroll const& scroll : scrolls) { + watchdog.step(scroll.name, seconds{120}); + printFrames(scroll.name, + scrollFrames(harness, *scroll.flickable, scroll.property, scroll.step, kFrames, scroll.limit)); + scroll.flickable->setProperty(scroll.property, 0.0); + static_cast(harness.frame()); + } + + // F5: memory per realized row, from the growth when a taller window realizes more rows. + watchdog.step("F5: resize to 1,600 px and report the range", seconds{120}); + auto const memoryMounted = bench::processBytes(); + harness.scene.window().resize(1280, 1600); + harness.scene.settle(); + reportRange(harness, *flick); + int const realizedTaller = tableItem->property("realizedCount").toInt(); + auto const memoryTaller = bench::processBytes(); + REQUIRE(realizedTaller > realized); + double const perRow = (static_cast(memoryTaller) - static_cast(memoryMounted)) / + static_cast(realizedTaller - realized); + std::println( + "\nF5: memory per realized row, from a window of 800 px to one of 1,600 px\n\n" + "| realized rows | process bytes after mount (over before) | rows added | bytes added | bytes per row |\n" + "|---|---:|---:|---:|---:|\n| {} -> {} | {} | {} | {} | {:.0f} |", + realized, realizedTaller, static_cast(memoryMounted) - static_cast(memoryBefore), + realizedTaller - realized, static_cast(memoryTaller) - static_cast(memoryMounted), + perRow); + static_cast(std::fflush(stdout)); + watchdog.step("teardown", seconds{300}); +} + +namespace { + +std::string benchField(ui::Value const& record, std::string const& field) { + ui::Value const* const value = record.field(field); + return value != nullptr && value->asString() != nullptr ? *value->asString() : std::string{}; +} + +} // namespace + +// The same figures with the column window: a table over a `TableSource` of 100,000 x 300, each column 8 units, in the +// same window. It first asserts the table is windowed both ways, so a mount that realized every column could not pass +// for the windowed one. +TEST_CASE("qt quick windowed: F3 to F5 on a source table of 100,000 x 300", "[.benchmark][windowed]") { + using std::chrono::seconds; + Watchdog watchdog; + watchdog.step("mount", seconds{300}); + BenchHarness harness; + auto const rows = std::make_shared(100'000, 300, harness.scene.owner()); + std::vector columns; + columns.reserve(300); + for (std::size_t column = 0; column < 300; ++column) { + columns.push_back(ui::TableColumn{ + .id = "c" + std::to_string(column), .label = "C" + std::to_string(column), .width = ui::Sizing::fixed(8)}); + } + ui::TableSource source; + source.rows = rows; + source.ownCell.assign(300, false); + source.defaultCellView = [](morph::reactive::Signal const& column, + morph::reactive::Signal const& row) { + return ui::text( + {.text = [&column, &row] { return benchField(row.get(), "c" + std::to_string(column.get())); }}); + }; + source.cellView = [](std::size_t column, morph::reactive::Signal const& row) { + return ui::text({.text = [&row, column] { return benchField(row.get(), "c" + std::to_string(column)); }}); + }; + auto const memoryBefore = bench::processBytes(); + ui::Mounted const view{harness.scene.runtime(), harness.scene.backend(), + ui::table(std::move(columns), std::move(source), ui::TableOptions{})}; + harness.scene.settle(); + static_cast(harness.frame()); + QQuickItem const* const tableItem = &Scene::itemOf(view.root()); + auto* const flick = tableItem->findChild(QStringLiteral("flick")); + auto* const hflick = tableItem->findChild(QStringLiteral("hflick")); + REQUIRE(flick != nullptr); + REQUIRE(hflick != nullptr); + reportRange(harness, *flick); + + // Windowed both ways. + int const realized = tableItem->property("realizedCount").toInt(); + int const windowColumns = tableItem->property("realizedColumnCount").toInt(); + REQUIRE(tableItem->property("arranged").toBool()); + REQUIRE(realized > 0); + REQUIRE(realized < 100); + REQUIRE(windowColumns > 0); + REQUIRE(windowColumns < 100); + std::println("\nwindowed: {} rows x {} columns realized, {} header cells, {} cells created", realized, + windowColumns, tableItem->property("headerCellCount").toInt(), view.stats().cellsCreated); + + double const rowHeight = tableItem->property("meanRowHeight").toReal(); + double const columnWidth = tableItem->property("windowTotalWidth").toReal() / 300.0; + double const bottom = std::max(0.0, flick->property("contentHeight").toReal() - flick->height()); + double const right = std::max(0.0, hflick->property("contentWidth").toReal() - hflick->width()); + REQUIRE(rowHeight > 0); + REQUIRE(columnWidth > 0); + REQUIRE(right > 0); + std::println( + "\nF3, F4 windowed: frame time, CPU, software scene graph, offscreen (row {:.1f} px, column {:.1f} px)" + "\n\n| scroll | frames | p50 ms | p10-p90 ms | p99 ms | frames over 16.6 ms |\n" + "|---|---:|---:|---:|---:|---:|", + rowHeight, columnWidth); + static_cast(std::fflush(stdout)); + constexpr int kFrames = 120; + struct Scroll { + char const* name; + QQuickItem* flickable; + char const* property; + double step; + double limit; + }; + std::vector const scrolls{ + {.name = "F3: vertical, 20 rows/s", + .flickable = flick, + .property = "contentY", + .step = rowHeight * 20.0 / 60.0, + .limit = bottom}, + {.name = "F3: vertical fling, 2,000 rows/s", + .flickable = flick, + .property = "contentY", + .step = rowHeight * 2'000.0 / 60.0, + .limit = bottom}, + {.name = "F3: thumb drag across the table in 2 s", + .flickable = flick, + .property = "contentY", + .step = bottom / kFrames, + .limit = bottom}, + {.name = "F4: horizontal, 10 columns/s", + .flickable = hflick, + .property = "contentX", + .step = columnWidth * 10.0 / 60.0, + .limit = right}, + {.name = "F4: horizontal fling, 100 columns/s", + .flickable = hflick, + .property = "contentX", + .step = columnWidth * 100.0 / 60.0, + .limit = right}, + }; + for (Scroll const& scroll : scrolls) { + watchdog.step(scroll.name, seconds{120}); + printFrames(scroll.name, + scrollFrames(harness, *scroll.flickable, scroll.property, scroll.step, kFrames, scroll.limit)); + scroll.flickable->setProperty(scroll.property, 0.0); + static_cast(harness.frame()); + harness.scene.settle(); + } + + // F5: memory per realized row, from the growth when a taller window realizes more rows. + watchdog.step("F5: resize to 1,600 px and report the range", seconds{120}); + auto const memoryMounted = bench::processBytes(); + harness.scene.window().resize(1280, 1600); + harness.scene.settle(); + reportRange(harness, *flick); + int const realizedTaller = tableItem->property("realizedCount").toInt(); + auto const memoryTaller = bench::processBytes(); + REQUIRE(realizedTaller > realized); + double const perRow = (static_cast(memoryTaller) - static_cast(memoryMounted)) / + static_cast(realizedTaller - realized); + std::println( + "\nF5 windowed: memory per realized row, from a window of 800 px to one of 1,600 px\n\n" + "| realized rows | process bytes after mount (over before) | rows added | bytes added | bytes per row |\n" + "|---|---:|---:|---:|---:|\n| {} -> {} | {} | {} | {} | {:.0f} |", + realized, realizedTaller, static_cast(memoryMounted) - static_cast(memoryBefore), + realizedTaller - realized, static_cast(memoryTaller) - static_cast(memoryMounted), + perRow); + static_cast(std::fflush(stdout)); + watchdog.step("teardown", seconds{300}); +} diff --git a/tests/qt_quick/test_qt_quick_conformance.cpp b/tests/qt_quick/test_qt_quick_conformance.cpp index 006c929c1..a3b72a5b7 100644 --- a/tests/qt_quick/test_qt_quick_conformance.cpp +++ b/tests/qt_quick/test_qt_quick_conformance.cpp @@ -5,11 +5,19 @@ // presses, moves and releases sent to the window at a widget's place, and keys sent to the item with focus. A menu // entry and a file drop go through the component's own entry point, which the menu's items and the drop area call. +#include +#include +#include +#include +#include +#include #include #include #include #include #include +#include +#include #include #include #include @@ -81,7 +89,7 @@ class QtProbe final : public ui::testing::ConformanceProbe { void click(ui::Widget& widget) override { settle(); QQuickItem const* target = Backend::itemOf(widget); - if (auto* const part = + if (auto const* const part = target != nullptr ? target->findChild(QStringLiteral("action")) : nullptr) { target = part; } @@ -140,7 +148,7 @@ class QtProbe final : public ui::testing::ConformanceProbe { if (_fault == Fault::DeadInput) { return; } - if (auto* const banner = dynamic_cast(&widget)) { + if (auto const* const banner = dynamic_cast(&widget)) { QQuickItem const* const item = banner->item(); mouseClick(item != nullptr ? item->findChild(QStringLiteral("dismiss")) : nullptr); return; @@ -182,22 +190,97 @@ class QtProbe final : public ui::testing::ConformanceProbe { } // A mouse click on the column's header label. - void clickHeader(ui::Widget& table, std::size_t column) override { + void clickHeader(ui::Widget& table, std::size_t column, ui::HeaderClick click) override { settle(); - // The labels are a Repeater's delegates: items under the table's item, not QObject children of it. - QString const name = QStringLiteral("header%1").arg(column); - QList pending{Backend::itemOf(table)}; - while (!pending.isEmpty()) { - QQuickItem const* const item = pending.takeLast(); - if (item->objectName() == name) { - mouseClick(item, Qt::NoModifier); + mouseClick(named(table, QStringLiteral("header%1").arg(column)), + click == ui::HeaderClick::Shift ? Qt::ShiftModifier : Qt::NoModifier); + } + + // A right click on the header, or a click on the `⋯`, opens the menu; its entries are read back from the open + // popup, and Esc must close it. A menu that does not open, or does not close on Esc, reads as none. + std::vector headerMenu(ui::Widget& table, std::optional column) override { + QObject const* const menu = openMenu(table, column); + std::vector entries; + if (menu == nullptr) { + return entries; + } + for (QVariant const& entry : listOf(menu->property("level"))) { + QVariantMap const map = entry.toMap(); + entries.push_back(ui::MenuEntry{.label = detail::toUtf8(map.value(QStringLiteral("label")).toString()), + .enabled = map.value(QStringLiteral("enabled")).toBool(), + .separator = map.value(QStringLiteral("separator")).toBool()}); + } + _scene.key(Qt::Key_Escape); + if (menu->property("opened").toBool()) { + return {}; + } + return entries; + } + // The menu opened as `headerMenu` opens it, then a click on each level's entry in the open popup. + void chooseHeaderMenuEntry(ui::Widget& table, std::optional column, + std::vector const& path) override { + QObject const* const menu = openMenu(table, column); + if (menu == nullptr) { + return; + } + for (std::size_t const index : path) { + auto* const entries = menu->property("contentItem").value(); + QQuickItem const* const entry = + entries == nullptr ? nullptr : namedUnder(*entries, QStringLiteral("menuEntry%1").arg(index)); + if (entry == nullptr || !menu->property("opened").toBool()) { return; } - for (QQuickItem const* const child : item->childItems()) { - pending.append(child); - } + mouseClick(entry); } } + // A drag of the header onto the header at the place asked for: the column the table shows there. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the interface fixes the order: the column, then the position it moves to. + void moveColumn(ui::Widget& table, std::size_t column, std::size_t position) override { + settle(); + QVariantList const visible = Backend::itemOf(table)->property("visibleColumns").toList(); + auto const place = static_cast(position); + int target = static_cast(position); + if (!visible.isEmpty()) { + target = place < visible.size() ? visible.at(place).toInt() : -1; + } + QQuickItem const* const from = named(table, QStringLiteral("header%1").arg(column)); + QQuickItem const* const to = target < 0 ? nullptr : named(table, QStringLiteral("header%1").arg(target)); + if (from == nullptr || to == nullptr || !from->isVisible() || _fault == Fault::DeadInput) { + return; + } + QPoint const start = Scene::centreOf(*from); + QPoint const end = Scene::centreOf(*to); + QTest::mousePress(&_scene.window(), Qt::LeftButton, {}, start); + constexpr int steps = 10; + for (int step = 1; step <= steps; ++step) { + QTest::mouseMove(&_scene.window(), start + ((end - start) * step / steps)); + } + QTest::mouseRelease(&_scene.window(), Qt::LeftButton, {}, end); + settle(); + } + void pressFilter(ui::Widget& table, std::size_t column) override { + settle(); + mouseClick(named(table, QStringLiteral("filter%1").arg(column))); + } + void pressGroupFilter(ui::Widget& table, std::size_t group) override { + settle(); + mouseClick(named(table, QStringLiteral("groupFilter%1").arg(group))); + } + std::string headerText(ui::Widget const& table, std::size_t column) override { + settle(); + QQuickItem const* const header = named(table, QStringLiteral("header%1").arg(column)); + if (header == nullptr || _fault == Fault::WrongText) { + return _fault == Fault::WrongText ? "?" : ""; + } + return detail::toUtf8(header->property("text").toString()); + } + std::string headerName(ui::Widget const& table, std::size_t column) override { + return accessibleText(named(table, QStringLiteral("header%1").arg(column)), QAccessible::Name); + } + std::string headerDescription(ui::Widget const& table, std::size_t column) override { + return accessibleText(named(table, QStringLiteral("header%1").arg(column)), QAccessible::Description); + } + std::string clipboardText() override { return detail::toUtf8(QGuiApplication::clipboard()->text()); } std::vector selectedRows(ui::Widget const& table) override { settle(); @@ -213,7 +296,7 @@ class QtProbe final : public ui::testing::ConformanceProbe { void moveCursor(ui::Widget& field, std::size_t position) override { settle(); - auto* const input = dynamic_cast(&field); + auto const* const input = dynamic_cast(&field); if (input == nullptr || _fault == Fault::DeadInput) { return; } @@ -285,7 +368,7 @@ class QtProbe final : public ui::testing::ConformanceProbe { std::optional boundsOf(ui::Widget const& widget) override { settle(); QQuickItem const* const item = base(widget).item(); - auto* const theme = + auto const* const theme = _scene.engine().singletonInstance(QStringLiteral("MorphUi"), QStringLiteral("Theme")); if (item == nullptr || theme == nullptr) { return std::nullopt; @@ -312,7 +395,7 @@ class QtProbe final : public ui::testing::ConformanceProbe { std::optional textExtentOf(ui::Widget const& widget) override { settle(); QQuickItem const* const item = base(widget).item(); - auto* const theme = + auto const* const theme = _scene.engine().singletonInstance(QStringLiteral("MorphUi"), QStringLiteral("Theme")); if (item == nullptr || theme == nullptr) { return std::nullopt; @@ -348,6 +431,82 @@ class QtProbe final : public ui::testing::ConformanceProbe { private: using Backend = morph::qt_quick::Backend; + // The item named @p name under the table's item: the headers are a Repeater's delegates, items under the table's + // item and not QObject children of it. + QQuickItem* named(ui::Widget const& table, QString const& name) { + QList pending{Backend::itemOf(table)}; + while (!pending.isEmpty()) { + QQuickItem* const item = pending.takeLast(); + if (item == nullptr) { + continue; + } + if (item->objectName() == name) { + return item; + } + for (QQuickItem* const child : item->childItems()) { + pending.append(child); + } + } + return nullptr; + } + + // What assistive technology reads of an item. + std::string accessibleText(QQuickItem* item, QAccessible::Text text) { + settle(); + if (item == nullptr) { + return {}; + } + bool const wasActive = QAccessible::isActive(); + QAccessible::setActive(true); + QAccessibleInterface const* const found = QAccessible::queryAccessibleInterface(item); + std::string const read = found == nullptr ? std::string{} : detail::toUtf8(found->text(text)); + QAccessible::setActive(wasActive); + return read; + } + + // A list a QML `var` property holds, which reaches C++ as a JavaScript value. + static QVariantList listOf(QVariant const& value) { + QVariant const plain = + value.metaType() == QMetaType::fromType() ? value.value().toVariant() : value; + return plain.toList(); + } + + // The item named @p name under @p root, depth first; null when none is. + static QQuickItem* namedUnder(QQuickItem& root, QString const& name) { + QList pending{&root}; + while (!pending.isEmpty()) { + QQuickItem* const item = pending.takeLast(); + if (item->objectName() == name) { + return item; + } + pending.append(item->childItems()); + } + return nullptr; + } + + // The column's menu by a right click on its header, or the table's by a click on the `⋯`; the popup, once it is + // open and shows entries, or null. + QObject* openMenu(ui::Widget& table, std::optional column) { + settle(); + if (_fault == Fault::DeadInput) { + return nullptr; + } + if (column) { + QQuickItem const* const header = named(table, QStringLiteral("header%1").arg(*column)); + if (header == nullptr || !header->isVisible()) { + return nullptr; + } + QTest::mouseClick(&_scene.window(), Qt::RightButton, {}, Scene::centreOf(*header)); + settle(); + } else { + mouseClick(named(table, QStringLiteral("tableMenuButton"))); + } + auto* const menu = Backend::itemOf(table)->findChild(QStringLiteral("configMenu")); + bool const open = + menu != nullptr && menu->property("opened").toBool() && !listOf(menu->property("level")).isEmpty(); + return open ? menu : nullptr; + } + static detail::ItemBase const& base(ui::Widget const& widget) { detail::ItemBase const* const found = detail::baseOf(widget); REQUIRE(found != nullptr); diff --git a/tests/qt_quick/test_qt_quick_interpreter.cpp b/tests/qt_quick/test_qt_quick_interpreter.cpp index 150cb634c..04da61c2d 100644 --- a/tests/qt_quick/test_qt_quick_interpreter.cpp +++ b/tests/qt_quick/test_qt_quick_interpreter.cpp @@ -7,9 +7,12 @@ #include #include +#include +#include #include #include #include +#include #include #include #include @@ -159,7 +162,7 @@ QList radiosOf(std::string_view testId) { TEST_CASE("qt_quick interpreter: a bound property follows its value", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(kBehaviour); + auto const screen = h.mount(kBehaviour); CHECK(QtHarness::widget("count").shownText() == "0"); h.click("add"); h.click("add"); @@ -172,7 +175,7 @@ TEST_CASE("qt_quick interpreter: a bound property follows its value", "[qt_quick TEST_CASE("qt_quick interpreter: a page inside a locale scope mounts, lays out and has its size", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(R"({ + auto const screen = h.mount(R"({ "vocab": "ui/1", "id": "around", "view": { "kind": "localeScope", "locale": "de", "children": [ { "kind": "page", "testId": "sheet", "width": 210000, "height": 297000, "a11y": { "name": "Sheet" }, "children": [ @@ -189,7 +192,7 @@ TEST_CASE("qt_quick interpreter: a page inside a locale scope mounts, lays out a TEST_CASE("qt_quick interpreter: a refused selection snaps back, an accepted one stays", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(kBehaviour); + auto const screen = h.mount(kBehaviour); auto const& refused = dynamic_cast(QtHarness::widget("refused")); auto const& taken = dynamic_cast(QtHarness::widget("taken")); CHECK(refused.shownText() == "a"); @@ -204,7 +207,7 @@ TEST_CASE("qt_quick interpreter: a refused selection snaps back, an accepted one TEST_CASE("qt_quick interpreter: typing into a controlled input keeps the cursor", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(kBehaviour); + auto const screen = h.mount(kBehaviour); auto const& name = dynamic_cast(QtHarness::widget("name")); h.click("name"); h.scene.type(QStringLiteral("abc")); @@ -219,7 +222,7 @@ TEST_CASE("qt_quick interpreter: typing into a controlled input keeps the cursor TEST_CASE("qt_quick interpreter: a dialog dismisses and reopens, and a document that keeps it open keeps it open", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(kBehaviour); + auto const screen = h.mount(kBehaviour); h.click("open"); REQUIRE(detail::findWidget(QStringLiteral("inside")) != nullptr); CHECK(QtHarness::widget("inside").item()->isVisible()); @@ -253,7 +256,7 @@ constexpr char const* kFrames = R"({ TEST_CASE("qt_quick interpreter: a flush that changes several values is one frame", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(kFrames); + auto const screen = h.mount(kFrames); int frames = 0; QObject::connect(&h.scene.window(), &QQuickWindow::frameSwapped, &h.scene.window(), [&frames] { ++frames; }); h.scene.settle(); @@ -325,7 +328,7 @@ detail::ContainerCore& rowsContainer() { TEST_CASE("qt_quick interpreter: a list change moves the fewest rows and keeps every kept row's item", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(kList); + auto const screen = h.mount(kList); CHECK(cellTexts() == std::vector{"one", "two", "three"}); std::vector const before = cellItems(); detail::ContainerCore const& rows = rowsContainer(); @@ -360,7 +363,7 @@ TEST_CASE("qt_quick interpreter: a list change moves the fewest rows and keeps e TEST_CASE("qt_quick interpreter: focus and a half-typed edit survive a reorder", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(kList); + auto const screen = h.mount(kList); detail::ItemBase const& two = *QtHarness::widgets("cell").at(1); h.scene.click(*two.focusTarget()); h.scene.type(QStringLiteral("!")); @@ -390,14 +393,14 @@ constexpr char const* kKeys = R"({ TEST_CASE("qt_quick interpreter: a table row keyed above 2^53 is selected and reported exactly", "[qt_quick][interpreter]") { QtHarness h; - auto screen = h.mount(kKeys); + auto const screen = h.mount(kKeys); h.reply(0, R"([{"id":9007199254740993,"name":"big"},{"id":9007199254740994,"name":"bigger"}])"); std::vector const names = QtHarness::widgets("name"); REQUIRE(names.size() == 2); // The row is the cell's container's container: the cell sits in the column that holds the row's scope. detail::ContainerCore* const holder = names.at(1)->container(); REQUIRE(holder != nullptr); - auto* const row = dynamic_cast(holder); + auto const* const row = dynamic_cast(holder); detail::ItemBase const* rowBase = row; if (rowBase == nullptr) { auto const* const inner = dynamic_cast(holder); @@ -456,7 +459,7 @@ std::unique_ptr mountRows(QtHarness& h) { TEST_CASE("qt_quick interpreter: server-calculated values show in their row, stale while a newer one is in flight", "[qt_quick][interpreter]") { QtHarness h; - auto screen = mountRows(h); + auto const screen = mountRows(h); CHECK(cell("result", 0).shownText() == "1"); CHECK(cell("result", 1).shownText() == "2"); CHECK(cell("mass", 0).shownText() == "10"); @@ -492,7 +495,7 @@ TEST_CASE("qt_quick interpreter: server-calculated values show in their row, sta TEST_CASE("qt_quick interpreter: a failed calculation keeps the stale value and shows the row's error", "[qt_quick][interpreter]") { QtHarness h; - auto screen = mountRows(h); + auto const screen = mountRows(h); h.scene.click(*cell("mass", 1).focusTarget()); h.scene.type(QStringLiteral("1")); h.advance(300ms); @@ -508,7 +511,7 @@ TEST_CASE("qt_quick interpreter: a failed calculation keeps the stale value and // exact body through the model alias. TEST_CASE("qt_quick interpreter: a form document renders and submits", "[qt_quick][interpreter][forms]") { QtHarness h; - auto screen = h.mount(R"({ + auto const screen = h.mount(R"({ "vocab": "ui/1", "id": "capture", "models": { "sample": { "type": "Lims_SampleModel" } }, "view": { "kind": "column", "children": [ @@ -531,7 +534,7 @@ TEST_CASE("qt_quick interpreter: a form document renders and submits", "[qt_quic TEST_CASE("qt_quick interpreter: a required form field shows one required mark, its control's", "[qt_quick][interpreter][forms]") { QtHarness h; - auto screen = h.mount(R"({ + auto const screen = h.mount(R"({ "vocab": "ui/1", "id": "capture", "models": { "sample": { "type": "Lims_SampleModel" } }, "view": { "kind": "form", "id": "cap", "model": "sample", "action": "Lims_CaptureConcentration" } })"); @@ -551,7 +554,7 @@ TEST_CASE("qt_quick interpreter: a required form field shows one required mark, TEST_CASE("qt_quick interpreter: a standalone input draws its caption above the control when the document asks", "[qt_quick][interpreter][forms]") { QtHarness h; - auto screen = h.mount(R"({ + auto const screen = h.mount(R"({ "vocab": "ui/1", "id": "captions", "models": { "sample": { "type": "Lims_SampleModel" } }, "view": { "kind": "column", "children": [ @@ -590,7 +593,7 @@ TEST_CASE("qt_quick interpreter: a standalone input draws its caption above the TEST_CASE("qt_quick interpreter: a collection document lists, confirms and edits", "[qt_quick][interpreter][forms]") { QtHarness h; h.dispatcher.autoReply.emplace("Lims_ListSamples", R"({"rows":[{"id":9007199254740993,"name":"Water"}]})"); - auto screen = h.mount(R"({ + auto const screen = h.mount(R"({ "vocab": "ui/1", "id": "samples", "models": { "sample": { "type": "Lims_SampleModel" } }, "view": { "kind": "collection", "model": "sample", "action": "Lims_ListSamples" } })"); @@ -618,7 +621,7 @@ TEST_CASE("qt_quick interpreter: a collection document lists, confirms and edits TEST_CASE("qt_quick interpreter: a wizard document steps on", "[qt_quick][interpreter][forms]") { QtHarness h; h.dispatcher.autoReply.emplace("Lims_CaptureConcentration", R"({"ok":true})"); - auto screen = h.mount(R"({ + auto const screen = h.mount(R"({ "vocab": "ui/1", "id": "flow", "models": { "sample": { "type": "Lims_SampleModel" } }, "view": { "kind": "wizard", "model": "sample", "action": "Lims_CaptureConcentration" } })"); @@ -970,7 +973,7 @@ TEST_CASE("qt_quick interpreter: a table's empty state is drawn while its rows a TEST_CASE("qt_quick interpreter: a switch sized as a share of its row is that share, and its case fills it", "[qt_quick][interpreter][percent]") { QtHarness h; - auto screen = h.mount(R"({ "vocab": "ui/1", "id": "share", "view": { "kind": "row", "testId": "row", + auto const screen = h.mount(R"({ "vocab": "ui/1", "id": "share", "view": { "kind": "row", "testId": "row", "sizing": { "lit": { "fixed": 80 } }, "children": [ { "kind": "switch", "testId": "slot", "on": 1, "sizing": { "lit": { "percent": 30 } }, "cases": [ { "when": 1, "children": [ { "kind": "text", "testId": "inside", "text": "inside" } ] } ] }, @@ -1066,3 +1069,36 @@ TEST_CASE("qt_quick interpreter: a screen's head trail spaces its tools and acti CHECK(left("head_action_print") - right("head_action_save") == Catch::Approx(expected).margin(1.0)); } } + +// Mutation: tell a source table that realizes every row no window in `realizeWindow` (`totalRows` stays -1, the rows +// plane has no height, and the rows fall outside the table). Not built on this host: Qt Quick does not configure here. +TEST_CASE("qt_quick interpreter: a rows table below its threshold draws its rows", "[qt_quick][interpreter]") { + QtHarness h; + auto const screen = h.mount(R"({ + "vocab": "ui/1", "id": "few", "state": { "rows": { "init": { "lit": [ + { "id": 1, "n": "one" }, { "id": 2, "n": "two" }, { "id": 3, "n": "three" } ] } } }, + "view": { "kind": "table", "testId": "list", "id": "t", "rows": { "ref": "rows" }, "key": { "row": "id" }, + "columns": [ { "id": "n", "label": "Name" } ] } })"); + h.scene.settle(); + QQuickItem* const table = QtHarness::widget("list").item(); + REQUIRE(table != nullptr); + CHECK(table->property("totalRows").toLongLong() == 3); + CHECK(table->property("sourceContentHeight").toReal() > 0); + for (QString const& name : {QStringLiteral("one"), QStringLiteral("two"), QStringLiteral("three")}) { + INFO(name.toStdString()); + QQuickItem const* shown = nullptr; + QList pending{table}; + while (!pending.isEmpty() && shown == nullptr) { + QQuickItem const* const item = pending.takeLast(); + if (item->isVisible() && item->property("text").toString() == name) { + shown = item; + } + pending.append(item->childItems()); + } + REQUIRE(shown != nullptr); + QPointF const at = shown->mapToItem(table, QPointF{0, 0}); + CHECK(shown->height() > 0); + CHECK(at.y() >= 0); + CHECK(at.y() + shown->height() <= table->height() + 0.5); + } +} diff --git a/tests/qt_quick/test_qt_quick_table.cpp b/tests/qt_quick/test_qt_quick_table.cpp index 88d590a56..89964b500 100644 --- a/tests/qt_quick/test_qt_quick_table.cpp +++ b/tests/qt_quick/test_qt_quick_table.cpp @@ -20,16 +20,23 @@ #include #include #include +#include #include #include #include +#include #include #include #include +#include +#include #include +#include #include #include #include +#include +#include #include #include #include @@ -39,11 +46,14 @@ #include #include #include +#include #include #include +#include "grid_test_support.hpp" #include "qt_quick/kinds.hpp" #include "qt_quick_harness.hpp" +#include "ui_fake_rows.hpp" namespace ui = morph::ui; namespace detail = morph::qt_quick::detail; @@ -83,6 +93,21 @@ qreal columnPadding(Scene& scene) { return 2 * theme->property("tableCellPaddingX").toReal(); } +// The first item at or under @p root, by visual children, named @p name; null for none. A Repeater's delegates are not +// QObject children of the item they sit in, so `findChild` does not reach them. +// NOLINTNEXTLINE(misc-no-recursion): the items form a tree, and the search descends it. +QQuickItem* itemNamed(QQuickItem& root, QString const& name) { + if (root.objectName() == name) { + return &root; + } + for (QQuickItem* const child : root.childItems()) { + if (QQuickItem* const found = itemNamed(*child, name)) { + return found; + } + } + return nullptr; +} + } // namespace TEST_CASE("qt_quick table: a row made in a table is a table row, and an int64 key above 2^53 comes back exactly", @@ -364,7 +389,7 @@ TEST_CASE("qt_quick table: Enter on a focused row activates it", "[qt_quick]") { // Mutation: never update the cache in `reportCellWidth` (growing a cell's text then shows the same `rowScans` // delta as a no-op, and the column's reported width stays at its pre-growth value). TEST_CASE("qt_quick table: growing one row's cell does not rescan every row, and the column still widens", - "[qt_quick]") { + "[qt_quick][heavy]") { Scene scene; auto table = scene.backend().createTable(nullptr); table->setColumns({{.label = "A"}, {.label = "B"}, {.label = "C"}}); @@ -410,7 +435,7 @@ TEST_CASE("qt_quick table: growing one row's cell does not rescan every row, and // Mutation: skip the invalidateColumn/reportCellWidth wiring from TableRowImpl::adopted entirely (a cell's width // changing then never reaches the table, so this never observes the rescan it measures). // Mutation: never update the cache in `reportCellWidth`, forcing every grow through the shrink/full-rescan path. -TEST_CASE("qt_quick table: a single-row grow's scan cost does not scale with row count", "[qt_quick]") { +TEST_CASE("qt_quick table: a single-row grow's scan cost does not scale with row count", "[qt_quick][heavy]") { // What this measures: the number of rows `widestCell` visits for a single-row grow, not wall-clock time. A // grown column's cells still all need their x/width updated once the column widens (MorphTableRow.qml's // onWidthsChanged: place(), one call per row) -- that O(rows) placement cost is real, necessary, and not what @@ -607,6 +632,52 @@ TEST_CASE( CHECK_FALSE(partOf(*table.rows.at(1), "tint").isVisible()); } +// Mutation: MorphTable.qml ignoring `busy` (MorphTableRow's busy mark never shown), under which row 1 shows no busy +// mark. +TEST_CASE("qt_quick table: a row's marks are drawn", "[qt_quick]") { + Scene scene; + Rows table = makeTable(scene, {ui::Key{std::string{"a"}}, ui::Key{std::string{"b"}}, ui::Key{std::string{"c"}}}, + ui::SelectionMode::Single); + table.table->setRowMarks(*table.rows.at(0), + ui::RowMarks{.unmatched = true, .tooltip = "This row no longer matches the filter"}); + table.table->setRowMarks(*table.rows.at(1), ui::RowMarks{.busy = true}); + table.table->setRowMarks(*table.rows.at(2), + ui::RowMarks{.locked = true, .tooltip = "Being edited by another user"}); + scene.settle(); + auto* const theme = scene.engine().singletonInstance(QStringLiteral("MorphUi"), QStringLiteral("Theme")); + REQUIRE(theme != nullptr); + auto const markOf = [](ui::StackWidget const& row, char const* name) -> QQuickItem& { + auto* const found = Scene::itemOf(row).findChild(QString::fromLatin1(name)); + REQUIRE(found != nullptr); + return *found; + }; + QQuickItem const& muted = Scene::itemOf(*table.rows.at(0)); + CHECK(muted.opacity() == theme->property("mutedOpacity").toReal()); + CHECK(muted.property("tooltipText").toString() == QStringLiteral("This row no longer matches the filter")); + CHECK(markOf(*table.rows.at(1), "busyMark").isVisible()); + CHECK_FALSE(markOf(*table.rows.at(0), "busyMark").isVisible()); + CHECK(markOf(*table.rows.at(2), "lockedWash").isVisible()); + // The marks draw in the theme's tokens, and the busy bar sits inside the selection's. + CHECK(markOf(*table.rows.at(1), "busyMark").property("color").value() == + theme->property("tableBusy").value()); + CHECK(markOf(*table.rows.at(1), "busyMark").x() == 3.0); + CHECK(markOf(*table.rows.at(2), "lockedWash").property("color").value() == + theme->property("tableLocked").value()); + CHECK(Scene::itemOf(*table.rows.at(1)).property("tooltipText").toString() == QStringLiteral("Saving this row")); + CHECK(Scene::itemOf(*table.rows.at(2)).property("tooltipText").toString() == + QStringLiteral("Being edited by another user")); + for (auto const& row : table.rows) { + table.table->setRowMarks(*row, ui::RowMarks{}); + } + scene.settle(); + for (auto const& row : table.rows) { + CHECK(Scene::itemOf(*row).opacity() == 1.0); + CHECK_FALSE(markOf(*row, "busyMark").isVisible()); + CHECK_FALSE(markOf(*row, "lockedWash").isVisible()); + CHECK(Scene::itemOf(*row).property("tooltipText").toString().isEmpty()); + } +} + namespace { struct VirtualRow { @@ -625,6 +696,7 @@ TEST_CASE("qt_quick table: a virtualized table realizes only the window, reporti Scene scene; std::vector const many = [] { std::vector rows; + rows.reserve(20); for (std::int64_t i = 0; i < 20; ++i) { rows.push_back(VirtualRow{.id = i, .name = "row-" + std::to_string(i)}); } @@ -1131,14 +1203,19 @@ QQuickItem& headerOf(ui::Widget const& table, int column) { } // namespace -// Mutation: leave the label's text without the mark (the sorted header reads `Name`). +// Mutation: leave the label's text without the mark (the sorted header reads `Name`); read the Shift state from the +// tapped signal's event point, which has no modifiers (every click reports `Plain`). TEST_CASE("qt_quick table: the sorted column's header shows and states its direction, and a click asks to sort", "[qt_quick]") { Scene scene; Rows table = makeTable(scene, {ui::Key{std::int64_t{1}}}, ui::SelectionMode::None); table.table->setColumns({{.label = "Name", .width = ui::Sizing::fixed(12), .sortable = true}, {.label = "Mass"}}); std::vector asked; - table.table->setOnSort([&asked](std::size_t column) { asked.push_back(column); }); + std::vector clicks; + table.table->setOnSort([&asked, &clicks](std::size_t column, ui::HeaderClick click) { + asked.push_back(column); + clicks.push_back(click); + }); scene.settle(); QQuickItem& name = headerOf(*table.table, 0); QQuickItem const& mass = headerOf(*table.table, 1); @@ -1146,7 +1223,7 @@ TEST_CASE("qt_quick table: the sorted column's header shows and states its direc CHECK(name.property("activeFocusOnTab").toBool()); CHECK_FALSE(mass.property("activeFocusOnTab").toBool()); - table.table->setSort(ui::TableSort{.column = 0, .direction = ui::SortDirection::Descending}); + table.table->setSort({ui::TableSort{.column = 0, .direction = ui::SortDirection::Descending}}); scene.settle(); CHECK(name.property("text").toString() == QStringLiteral("Name ▼")); CHECK(asked.empty()); @@ -1154,18 +1231,90 @@ TEST_CASE("qt_quick table: the sorted column's header shows and states its direc QAccessible::setActive(true); QAccessibleInterface const* const header = QAccessible::queryAccessibleInterface(&name); REQUIRE(header != nullptr); - CHECK(header->text(QAccessible::Description) == QStringLiteral("Sorted descending")); + CHECK(header->text(QAccessible::Description) == QStringLiteral("sorted descending")); CHECK(header->text(QAccessible::Name) == QStringLiteral("Name")); QAccessible::setActive(wasActive); scene.click(name); scene.click(mass); CHECK(asked == std::vector{0}); - table.table->setSort(std::nullopt); + // Shift held reports `Shift`; Ctrl, which the contract gives no meaning on a header, reports `Plain`. + scene.click(name, Qt::ShiftModifier); + scene.click(name, Qt::ControlModifier); + CHECK(clicks == + std::vector{ui::HeaderClick::Plain, ui::HeaderClick::Shift, ui::HeaderClick::Plain}); + table.table->setSort({}); scene.settle(); CHECK(name.property("text").toString() == QStringLiteral("Name")); } +// Controls: report the edge drag's width in pixels instead of units; read the drag's translation once it has ended +// (no change of width); leave the filter button above the edge (the filterable header's drag reaches no edge). +TEST_CASE("qt_quick table: dragging a header's trailing edge reports units, a double click on it none", + "[qt_quick][table]") { + bool const filterable = GENERATE(false, true); + CAPTURE(filterable); + Scene scene; + Rows table = makeTable(scene, {ui::Key{std::int64_t{1}}}, ui::SelectionMode::None); + table.table->setColumns( + {{.label = "Name", .width = ui::Sizing::fixed(12), .filterable = filterable}, {.label = "Mass"}}); + int filters = 0; + table.table->setOnFilter([&filters](std::size_t /*column*/) { ++filters; }); + std::vector>> resized; + table.table->setOnColumnResize( + [&resized](std::size_t column, std::optional units) { resized.emplace_back(column, units); }); + scene.settle(); + QQuickItem const& name = headerOf(*table.table, 0); + QQuickItem* edge = nullptr; + for (QQuickItem* const child : name.childItems()) { + if (child->objectName() == QStringLiteral("edge0")) { + edge = child; + } + } + REQUIRE(edge != nullptr); + // The header is the column's 12 units and its padding; four units more to the right make 16 units of content. + qreal const unit = units(scene).width(); + QPoint const start = Scene::centreOf(*edge); + QPoint const end = start + QPoint{static_cast(std::lround(4 * unit)), 0}; + QTest::mousePress(&scene.window(), Qt::LeftButton, {}, start); + constexpr int steps = 10; + for (int step = 1; step <= steps; ++step) { + QTest::mouseMove(&scene.window(), start + ((end - start) * step / steps)); + } + QTest::mouseRelease(&scene.window(), Qt::LeftButton, {}, end); + scene.settle(); + REQUIRE(resized.size() == 1); + CHECK(resized.front().first == 0); + CHECK(resized.front().second == std::optional{16}); + scene.doubleClick(*edge); + REQUIRE_FALSE(resized.empty()); + CHECK(resized.back() == std::pair>{0, std::nullopt}); + CHECK(filters == 0); +} + +// Control: ignore a drag that ends on another header. +TEST_CASE("qt_quick table: dragging a header onto another reports the move", "[qt_quick][table]") { + Scene scene; + Rows table = makeTable(scene, {ui::Key{std::int64_t{1}}}, ui::SelectionMode::None); + table.table->setColumns({{.label = "Name", .width = ui::Sizing::fixed(10)}, + {.label = "Mass", .width = ui::Sizing::fixed(10)}, + {.label = "Site", .width = ui::Sizing::fixed(10)}}); + std::vector> moves; + table.table->setOnColumnMove( + [&moves](std::size_t column, std::size_t position) { moves.emplace_back(column, position); }); + scene.settle(); + QPoint const start = Scene::centreOf(headerOf(*table.table, 0)); + QPoint const end = Scene::centreOf(headerOf(*table.table, 2)); + QTest::mousePress(&scene.window(), Qt::LeftButton, {}, start); + constexpr int steps = 10; + for (int step = 1; step <= steps; ++step) { + QTest::mouseMove(&scene.window(), start + ((end - start) * step / steps)); + } + QTest::mouseRelease(&scene.window(), Qt::LeftButton, {}, end); + scene.settle(); + CHECK(moves == std::vector>{{0, 2}}); +} + // Control: ignore the token in MorphTableRow's `place` (the cell's top is the row's top, 0). TEST_CASE("qt_quick table: a cell is inset by table.cellPaddingY and a row grows by twice it", "[qt_quick]") { Scene scene; @@ -1255,11 +1404,11 @@ TEST_CASE("qt_quick table: a column header follows field.caption.case and its co REQUIRE(morph::qt_quick::applyTheme(scene.engine(), values).empty()); scene.settle(); for (char const* const name : {"header0", "header1"}) { - QFont const font = headerOf(name)->property("font").value(); + auto const font = headerOf(name)->property("font").value(); CHECK(font.capitalization() == QFont::AllUppercase); CHECK(font.letterSpacing() > 0.0); } - QFont const font = headerOf("header1")->property("font").value(); + auto const font = headerOf("header1")->property("font").value(); qreal const capitals = QFontMetricsF{font}.horizontalAdvance(QStringLiteral("MIXING PLANT AND SAMPLING POINT")); CHECK(tableItem.property("widths").toList().at(1).toReal() >= capitals + columnPadding(scene)); CHECK(tableItem.property("widths").toList().at(1).toReal() > plainWidth); @@ -1360,7 +1509,7 @@ TEST_CASE("qt_quick table: a cell whose content is wider than its column keeps i {{.label = "Sample", .width = ui::Sizing::fixed(10)}, {.label = "Lot", .width = ui::Sizing::fixed(10)}}); auto row = scene.backend().createStack(table.get(), ui::Axis::Horizontal); table->setRowKey(*row, ui::Key{std::int64_t{1}}); - auto packed = scene.backend().createStack(row.get(), ui::Axis::Horizontal); + auto const packed = scene.backend().createStack(row.get(), ui::Axis::Horizontal); auto first = scene.backend().createText(packed.get()); first->setText("a long sample identifier"); auto second = scene.backend().createText(packed.get()); @@ -1700,7 +1849,7 @@ TEST_CASE("qt_quick table: a table in a cell settles to the layout a fresh build TEST_CASE("qt_quick table: the width-free natural width of runs that wrap is the widest line's advance", "[qt_quick][table]") { Scene scene; - auto column = scene.backend().createStack(nullptr, ui::Axis::Vertical); + auto const column = scene.backend().createStack(nullptr, ui::Axis::Vertical); auto text = scene.backend().createText(column.get()); text->setSpans({{.text = "first line\n"}, {.text = "the second line is longer", .strong = true}}); scene.window().resize(400, 300); @@ -1780,7 +1929,7 @@ TEST_CASE("qt_quick table: a spanning cell reaches the foot of the rows it cover table.table->setColumns( {{.label = "Name", .width = ui::Sizing::fixed(12), .valign = ui::Align::Stretch}, {.label = "Mass"}}); scene.settle(); - QQuickItem& tableItem = Scene::itemOf(*table.table); + QQuickItem const& tableItem = Scene::itemOf(*table.table); QQuickItem const& first = Scene::itemOf(*table.cells.at(0)); qreal const oneRow = first.height(); table.table->setRowSpans(*table.rows.at(0), {{.column = 0, .rows = 3}}); @@ -1846,8 +1995,8 @@ TEST_CASE("qt_quick table: hovering the part of a spanning cell over a covered r Rows table = makeTable(scene, {ui::Key{1}, ui::Key{2}, ui::Key{3}}, ui::SelectionMode::Single); table.table->setRowSpans(*table.rows.at(0), {{.column = 0, .rows = 3}}); scene.settle(); - QQuickItem& origin = Scene::itemOf(*table.rows.at(0)); - QQuickItem& covered = Scene::itemOf(*table.rows.at(1)); + QQuickItem const& origin = Scene::itemOf(*table.rows.at(0)); + QQuickItem const& covered = Scene::itemOf(*table.rows.at(1)); // Away from the table's rows, nothing is hovered. QTest::mouseMove(&scene.window(), QPoint{1, 1}); scene.settle(); @@ -2087,3 +2236,1028 @@ TEST_CASE("qt_quick table: a Ctrl-click in a virtualized table keeps selected ke REQUIRE(reported.size() == 1); CHECK(reported.back().size() == static_cast(rowCount - 1)); } + +// ── The column window ─────────────────────────────────────────────────────── + +namespace { + +using morph::testing::FakeRows; +using ui::CellRef; +using ui::Key; +using ui::TableArrangement; + +struct QuickWindowOptions { + // A cell drawn on more lines than one: the row's text, then a line more for each line past the first. + struct Wrapped { + std::int64_t row = 0; + std::size_t column = 0; + int lines = 1; + }; + struct Level { + std::size_t column = 0; + std::string level; + }; + std::size_t pinned = 0; + std::vector wrapped; + bool wrap = true; + std::vector levels; + ui::SelectionMode selection = ui::SelectionMode::None; + bool selectColumn = false; + // Each column's unit, by index; a column past the list has none. + std::vector units; + // Whether the table has a select-all handler, which counts its calls in `selectAlls`. + bool selectAllHandler = false; + // The cells' menu; empty for none. + std::function(ui::Key const&, std::size_t)> cellMenu; +}; + +std::string groupedCount(std::int64_t n) { + std::string digits = std::to_string(n); + for (auto at = static_cast(digits.size()) - 3; at > 0; at -= 3) { + digits.insert(static_cast(at), ","); + } + return digits; +} + +std::string fieldText(ui::Value const& record, std::string const& field) { + ui::Value const* const value = record.field(field); + return value != nullptr && value->asString() != nullptr ? *value->asString() : std::string{}; +} + +std::int64_t idOf(ui::Value const& record) { + ui::Value const* const value = record.field("id"); + return value != nullptr && value->asInt() != nullptr ? *value->asInt() : -1; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the column count, then the column left out. +std::vector allColumnsBut(std::size_t n, std::size_t left) { + std::vector out; + for (std::size_t column = 0; column < n; ++column) { + if (column != left) { + out.push_back(column); + } + } + return out; +} + +// The recording backend's `WindowFixture` on Qt Quick: one table over `FakeRows` in a 1,280 × 800 window, every +// column 8 units wide with the default text cell, and the window made twenty columns wide (`column` px each) once the +// mount has laid the columns out in the table's measure; the status line shows the count. +struct QuickWindowFixture { + QuickWindowFixture(std::int64_t rowCount, std::size_t columnCount, QuickWindowOptions options = {}) + : rows{std::make_shared(rowCount, columnCount, scene.owner())}, + arrangement{scene.runtime(), TableArrangement{.visible = {}, .pinned = options.pinned, .widths = {}}}, + focus{scene.runtime(), std::nullopt}, + status{scene.runtime(), ui::TableStatus{.counts = groupedCount(rowCount) + " rows", .shown = true}}, + accents{scene.runtime(), {}}, + selected{scene.runtime(), {}}, + wrapped{std::move(options.wrapped)} { + scene.window().resize(1280, 800); + std::vector columns; + columns.reserve(columnCount); + for (std::size_t index = 0; index < columnCount; ++index) { + columns.push_back( + ui::TableColumn{.id = "c" + std::to_string(index), + .label = "C" + std::to_string(index), + .width = ui::Sizing::fixed(8), + .unit = index < options.units.size() ? options.units.at(index) : std::string{}, + .wrap = options.wrap}); + } + ui::TableSource source; + source.rows = rows; + source.ownCell.assign(columnCount, false); + source.levels.assign(columnCount, std::string{}); + for (QuickWindowOptions::Level const& level : options.levels) { + source.levels.at(level.column) = level.level; + } + source.defaultCellView = [this](morph::reactive::Signal const& cellColumn, + morph::reactive::Signal const& row) { + return ui::accentedCell( + ui::text({.text = [this, &cellColumn, &row] { return textOf(row.get(), cellColumn.get()); }}), + [this, &cellColumn, &row] { + auto const& all = accents.get(); + auto const found = all.find(std::pair{idOf(row.get()), cellColumn.get()}); + return found == all.end() ? ui::CellAccent{} : found->second; + }); + }; + source.cellView = [this](std::size_t cellColumn, morph::reactive::Signal const& row) { + return ui::text({.text = [this, &row, cellColumn] { return textOf(row.get(), cellColumn); }}); + }; + ui::TableOptions tableOptions; + // A table over a source is a viewport onto rows it does not hold: it takes the window's height. + tableOptions.common.layout.height = ui::Sizing::stretch(); + tableOptions.arrangement = [this] { return arrangement.get(); }; + tableOptions.focus = [this] { return focus.get(); }; + tableOptions.status = [this] { return status.get(); }; + tableOptions.onRetry = [this] { ++retries; }; + tableOptions.selectionMode = options.selection; + tableOptions.selectColumn = options.selectColumn; + tableOptions.onSelectRange = [this](std::size_t anchor, std::size_t focusAt, ui::SelectionChange change) { + ranges.emplace_back(anchor, focusAt, change); + }; + if (options.selectAllHandler) { + tableOptions.onSelectAll = [this] { ++selectAlls; }; + } + // The selection is held here, as a document holds it: each change the user makes is recorded and kept. + tableOptions.selection = [this] { return selected.get(); }; + tableOptions.onSelectionChange = [this](std::vector keys, ui::SelectionChange change) { + selections.emplace_back(keys, change); + selected.set(std::move(keys)); + }; + tableOptions.cellMenu = std::move(options.cellMenu); + view.emplace(scene.runtime(), scene.backend(), + ui::table(std::move(columns), std::move(source), std::move(tableOptions))); + settle(); + column = static_cast(call("columnWidth", 0).toReal()); + REQUIRE(column > 0); + scene.window().resize(20 * column, 800); + settle(); + } + + [[nodiscard]] std::string textOf(ui::Value const& record, std::size_t cellColumn) const { + std::string text = fieldText(record, "c" + std::to_string(cellColumn)); + for (QuickWindowOptions::Wrapped const& cell : wrapped) { + if (cell.row == idOf(record) && cell.column == cellColumn) { + for (int line = 1; line < cell.lines; ++line) { + text += "\n" + text; + } + } + } + return text; + } + + void settle() { scene.settle(); } + + [[nodiscard]] QQuickItem* item() const { return &Scene::itemOf(view->root()); } + [[nodiscard]] QVariant prop(char const* name) const { return item()->property(name); } + + // Evaluates `name(args…)` on the MorphTable item. + template + QVariant call(char const* name, Args const&... args) { + // NOLINTNEXTLINE(misc-const-correctness): the fold expression below appends to it, which the check does not see. + QStringList list; + (list.append(QString::number(args)), ...); + QQmlExpression expression{ + scene.engine().rootContext(), item(), + QStringLiteral("%1(%2)").arg(QString::fromLatin1(name), list.join(QStringLiteral(",")))}; + QVariant const result = expression.evaluate(); + REQUIRE_FALSE(expression.hasError()); + return result; + } + + // The cell items shown in the realized rows. + int cellItems() { + QQmlExpression expression{scene.engine().rootContext(), item(), QStringLiteral(R"((() => { + let shown = 0 + for (let i = 0; i < rowsHolder.children.length; ++i) { + const row = rowsHolder.children[i] + if (!row.visible || !row.content) + continue + for (let j = 0; j < row.content.children.length; ++j) { + const cell = row.content.children[j] + shown += cell.measuredIndex !== undefined && cell.visible ? 1 : 0 + } + } + return shown + })())")}; + QVariant const result = expression.evaluate(); + REQUIRE_FALSE(expression.hasError()); + return result.toInt(); + } + + void scrollRows(std::size_t first) { + firstRow = first; + static_cast(call("scrollRowToTop", static_cast(first))); + settle(); + } + + void scrollColumns(int scrollX) { + auto* const hflick = item()->findChild(QStringLiteral("hflick")); + REQUIRE(hflick != nullptr); + hflick->setProperty("contentX", scrollX); + settle(); + } + + // Scrolls down over @p n rows a viewport at a time, one owner turn at a time, and keeps the largest number of + // cells built or rebound in one turn. + void flingRows(std::size_t n) { + auto const work = [this] { return stats().cellsRebound + stats().cellsCreated; }; + for (std::size_t moved = 0; moved < n; moved += 30) { + std::size_t before = work(); + firstRow += 30; + static_cast(call("scrollRowToTop", static_cast(firstRow))); + maxRebindsPerTurn = std::max(maxRebindsPerTurn, work() - before); + for (;;) { + before = work(); + if (!scene.owner().runOne()) { + break; + } + maxRebindsPerTurn = std::max(maxRebindsPerTurn, work() - before); + } + } + settle(); + } + + [[nodiscard]] ui::MountStats const& stats() const { return view->stats(); } + + Scene scene; + std::shared_ptr rows; + morph::reactive::Signal arrangement; + morph::reactive::Signal> focus; + morph::reactive::Signal status; + // Each cell's accent, by row id and column; a cell not named has none. + morph::reactive::Signal, ui::CellAccent>> accents; + // The selected keys, and every change the backend reported. + morph::reactive::Signal> selected; + std::vector, ui::SelectionChange>> selections; + std::vector wrapped; + int retries = 0; + int selectAlls = 0; + std::vector> ranges; + std::size_t firstRow = 0; + std::size_t maxRebindsPerTurn = 0; + int column = 0; ///< A column's width in pixels, the measure of a fixed column of 8 units and its padding. + std::optional view; +}; + +} // namespace + +// Mutation: MorphTable instantiating a cell per column of a realized row (cellItems is 50 × 300). Gate F2. +TEST_CASE("qt_quick table window: cells and header cells alive are the windows'", "[qt_quick][heavy]") { + QuickWindowFixture f{100'000, 300, {.pinned = 2}}; + f.scrollRows(500); + f.scrollColumns(100 * f.column); // columns 100 to 119 in view + int const window = 2 + 20 + (2 * 4); + CHECK(f.prop("realizedColumnCount").toInt() == window); + CHECK(f.prop("pinnedShown").toInt() == 2); + CHECK(f.cellItems() == f.prop("realizedCount").toInt() * window); + CHECK(f.prop("headerCellCount").toInt() == window); +} + +// Mutation: a pool keyed by column for default cells (a column scrolling in creates 50 cells). Gate F8. +TEST_CASE("qt_quick table window: flings create no cell once the pools are warm", "[qt_quick][heavy]") { + QuickWindowFixture f{100'000, 300, {.pinned = 2}}; + // Two flings warm the rows: the first measures the rows it passes, and the mean height they settle at can put one + // more row in the window than the estimate did, which only the second fling's pool has to hold. + f.flingRows(2'000); + f.flingRows(2'000); + for (int x = 0; x < 200 * f.column; x += 10 * f.column) { + f.scrollColumns(x); // warm both ways + } + auto const created = f.stats().cellsCreated; + f.flingRows(2'000); + for (int x = 200 * f.column; x < 300 * f.column; x += 10 * f.column) { + f.scrollColumns(x); + } + CHECK(f.stats().cellsCreated == created); + CHECK(f.maxRebindsPerTurn <= 240); +} + +// Mutation: MorphTable keeping focus on the delegate item, which a recycled row loses. Gate F10. +TEST_CASE("qt_quick table window: focus and counts after scrolling far away", "[qt_quick][heavy]") { + QuickWindowFixture f{100'000, 300, {.pinned = 2}}; + f.focus.set(CellRef{.key = Key{std::int64_t{7}}, .column = "c5"}); + f.settle(); + f.scrollRows(10'000); + f.scrollColumns(200 * f.column); + CHECK(f.call("focusedRow").toInt() == 7); + CHECK(f.call("focusedColumn").toInt() == 5); + CHECK(f.call("cellRealized", 7, 5).toBool()); + CHECK(f.prop("accessibleRowCount").toInt() == 100'000); + CHECK(f.prop("accessibleColumnCount").toInt() == 300); +} + +// Mutation: MorphTable rebuilding its row delegates when the column window changes. Gate D8, Qt Quick half. +TEST_CASE("qt_quick table window: hiding and moving a column create no cell items", "[qt_quick][heavy]") { + QuickWindowFixture f{100'000, 300, {.pinned = 2}}; + auto const created = f.stats().cellsCreated; + int const items = f.cellItems(); + TableArrangement hidden = f.arrangement.peek(); + hidden.visible = allColumnsBut(300, 5); + f.arrangement.set(hidden); + f.settle(); + CHECK(f.stats().cellsCreated == created); + CHECK(f.cellItems() == items); + CHECK_FALSE(f.call("cellRealized", 0, 5).toBool()); + TableArrangement moved = hidden; + std::swap(moved.visible.at(3), moved.visible.at(4)); + f.arrangement.set(moved); + f.settle(); + CHECK(f.stats().cellsCreated == created); + CHECK(f.cellItems() == items); +} + +// Mutation: MorphTable ignoring setStatus (statusText is empty). +TEST_CASE("qt_quick table: the status line shows counts and Retry", "[qt_quick]") { + QuickWindowFixture f{100'000, 30}; + CHECK(f.prop("statusText").toString() == QStringLiteral("100,000 rows")); + CHECK_FALSE(f.prop("retryShown").toBool()); + f.status.set(ui::TableStatus{ + .counts = "100,000 rows", .state = "Recipe data could not be loaded.", .retry = true, .shown = true}); + f.settle(); + CHECK(f.prop("statusText").toString() == QStringLiteral("100,000 rows Recipe data could not be loaded.")); + REQUIRE(f.prop("retryShown").toBool()); + auto* const retry = f.item()->findChild(QStringLiteral("retry")); + REQUIRE(retry != nullptr); + f.scene.click(*retry); + CHECK(f.retries == 1); +} + +// Mutation: MorphTable ignoring setCellLoad (an unloaded cell draws its empty content: cellLoadAt is 0). +TEST_CASE("qt_quick table: an unloaded cell is a placeholder and a failed one an error mark", "[qt_quick]") { + QuickWindowFixture f{100, 4, {.levels = {{.column = 1, .level = "recipe"}}}}; + int const widthBefore = f.call("columnWidth", 1).toInt(); + f.rows->unload(0, "recipe"); + f.rows->fail(1, "recipe"); + f.settle(); + CHECK(f.call("cellLoadAt", 0, 1).toInt() == 1); + CHECK(f.call("cellLoadAt", 1, 1).toInt() == 2); + CHECK(f.call("cellLoadAt", 2, 1).toInt() == 0); + CHECK(f.call("columnWidth", 1).toInt() == widthBefore); // a placeholder widens nothing +} + +// Mutations: the tint painted opaque over the row's selection fill (its alpha is 1); the slot under the row's +// background (z -1), where a toned or selected row hides it; `invalid` ignored by +// MorphTableRow.qml, which draws no error mark (cellLoadAt is 0 and no failedMark exists). +TEST_CASE( + "qt_quick table: a toned cell keeps its selection mark, a tooltip cell is described, a unit header is named " + "with its unit", + "[qt_quick]") { + QuickWindowFixture f{10, 3, {.units = {"kg"}}}; + auto* const header = itemNamed(*f.item(), QStringLiteral("header0")); + REQUIRE(header != nullptr); + CHECK(header->property("text").toString() == QStringLiteral("C0 [kg]")); + bool const wasActive = QAccessible::isActive(); + QAccessible::setActive(true); + QAccessibleInterface const* const named = QAccessible::queryAccessibleInterface(header); + REQUIRE(named != nullptr); + CHECK(named->text(QAccessible::Name) == QStringLiteral("C0, kg")); + + f.accents.set({{{0, 0}, ui::CellAccent{.tone = ui::Tone::Warn, .tooltip = "Above limit", .invalid = false}}, + {{0, 1}, ui::CellAccent{.tone = {}, .tooltip = "The value could not be read", .invalid = true}}}); + f.settle(); + QVariant const accent = f.call("cellAccentAt", 0, 0); + REQUIRE(accent.isValid()); + auto* const tinted = itemNamed(*f.item(), QStringLiteral("cellAccent0")); + REQUIRE(tinted != nullptr); + auto* const tint = itemNamed(*tinted, QStringLiteral("cellTint")); + REQUIRE(tint != nullptr); + CHECK(tint->isVisible()); + CHECK(itemNamed(*tinted, QStringLiteral("moreMark"))->isVisible()); + QAccessibleInterface const* const described = QAccessible::queryAccessibleInterface(tinted); + REQUIRE(described != nullptr); + CHECK(described->text(QAccessible::Description) == QStringLiteral("Above limit")); + // Half the tone's fill: the row's selection fill and bar show through it. + CHECK(tint->property("color").value().alphaF() < 1.0F); + // Over the row's background, whose tone tint and selection fill are opaque: after it among the row's children, at + // no lower z, so a toned cell keeps its tone in a toned or selected row. + QQuickItem* const row = tinted->parentItem(); + REQUIRE(row != nullptr); + QQuickItem* layer = itemNamed(*row, QStringLiteral("fill")); + while (layer != nullptr && layer->parentItem() != row) { + layer = layer->parentItem(); + } + REQUIRE(layer != nullptr); + CHECK(tinted->z() >= layer->z()); + CHECK(row->childItems().indexOf(tinted) > row->childItems().indexOf(layer)); + CHECK(f.call("cellLoadAt", 0, 1).toInt() == 0); // the load is the mount's; the mark is the accent's + CHECK(itemNamed(*f.item(), QStringLiteral("failedMark")) != nullptr); + QAccessible::setActive(wasActive); + + f.accents.set({}); + f.settle(); + CHECK(itemNamed(*f.item(), QStringLiteral("cellAccent0")) == nullptr); + CHECK(itemNamed(*f.item(), QStringLiteral("failedMark")) == nullptr); +} + +// Mutations: a row's height recomputed from its realized cells each pass (it shrinks when the tall cell leaves); +// measuring a table whose columns are all wrap:false (rowMeasures grows). +TEST_CASE("qt_quick table: a row's height only grows while it is realized", "[qt_quick][heavy]") { + QuickWindowFixture f{2'000, 300, {.pinned = 0, .wrapped = {{.row = 3, .column = 60, .lines = 2}}}}; + // Before the first viewport report every column is realized, the wrapped one too; a row that left the row window + // and came back has measured only the columns in view. + f.scrollRows(1'000); + f.scrollRows(0); + int const low = f.call("rowHeight", 3).toInt(); + f.scrollColumns(60 * f.column); + int const tall = f.call("rowHeight", 3).toInt(); + CHECK(tall > low); + f.scrollColumns(0); + CHECK(f.call("rowHeight", 3).toInt() == tall); // scrolled out: not shorter + f.scrollRows(1'000); + f.scrollRows(0); + CHECK(f.call("rowHeight", 3).toInt() == low); // it left the row window: forgotten + QuickWindowFixture flat{2'000, 300, {.pinned = 0, .wrap = false}}; + flat.flingRows(200); + CHECK(flat.prop("rowMeasures").toInt() == 0); +} + +// Mutation: MorphTable keeping the view's offset when a row above the first visible row grows (the first visible +// row moves down by the growth). +TEST_CASE("qt_quick table: a row growing above the view keeps the rows in view where they are", "[qt_quick][heavy]") { + QuickWindowFixture f{2'000, 300, {.pinned = 0, .wrapped = {{.row = 95, .column = 60, .lines = 3}}}}; + f.scrollRows(100); + QQuickItem const* const flick = f.item()->findChild(QStringLiteral("flick")); + REQUIRE(flick != nullptr); + qreal const offsetBefore = flick->property("contentY").toReal() - f.call("rowTop", 100).toReal(); + f.scrollColumns(60 * f.column); // row 95, above the view and realized, grows + CHECK(f.call("rowHeight", 95).toReal() > f.call("rowHeight", 96).toReal()); + CHECK(flick->property("contentY").toReal() - f.call("rowTop", 100).toReal() == Catch::Approx(offsetBefore)); +} + +// Mutation: the Qt Quick table answering the default measure (a windowed column of 8 units is 8 px plus nothing). +TEST_CASE("qt_quick table: a windowed fixed column is as wide as an unwindowed one", "[qt_quick][heavy]") { + QuickWindowFixture windowed{100'000, 300}; + REQUIRE(windowed.prop("arranged").toBool()); + Scene scene; + ui::Mounted const plain{ + scene.runtime(), scene.backend(), + ui::table( + {{.label = "C0", .width = ui::Sizing::fixed(8)}}, [] { return std::vector{1, 2}; }, + [](std::int64_t const& row) { return ui::Key{row}; }, + [](morph::reactive::Signal const& row) { + return std::vector{ui::text({.text = [&row] { return std::to_string(row.get()); }})}; + })}; + scene.settle(); + QVariantList const widths = Scene::itemOf(plain.root()).property("widths").toList(); + REQUIRE(widths.size() == 1); + CHECK(windowed.call("columnWidth", 0).toReal() == Catch::Approx(widths.at(0).toReal()).margin(1.0)); +} + +// Mutations: a tap on a row of a source table focusing the row (the table loses `activeFocus`); MorphTable announcing +// nothing (no announcement event reaches the accessibility handler). +TEST_CASE("qt_quick table window: a tap keeps the focus on the table, and the status line is announced", + "[qt_quick]") { + QuickWindowFixture f{100'000, 30}; + QQuickItem const* const row = f.item()->property("rowsHolder").value()->childItems().value(3); + REQUIRE(row != nullptr); + f.scene.click(*row); + CHECK(f.item()->hasActiveFocus()); +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + // Announcements are Qt 6.8's. + static std::vector announced; + announced.clear(); + QAccessible::installUpdateHandler([](QAccessibleEvent* event) { + if (event->type() == QAccessible::Announcement) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast): the event type was checked above. + announced.push_back(static_cast(event)->message()); + } + }); + QAccessible::setActive(true); + f.status.set(ui::TableStatus{.counts = "100,000 rows", .message = "Copied 2 rows", .shown = true}); + f.settle(); + QTest::qWait(700); // the announcement waits for the text to hold half a second + QAccessible::installUpdateHandler(nullptr); + CHECK(std::ranges::contains(announced, QStringLiteral("100,000 rows Copied 2 rows"))); +#endif +} + +// Mutation: the select-all box over a source selecting the realized rows (`TableImpl::selectAll`: no range reaches +// the mount). +TEST_CASE("qt_quick table window: the select-all box selects the view through the mount", "[qt_quick]") { + QuickWindowFixture f{100'000, 30, {.selection = ui::SelectionMode::Multiple, .selectColumn = true}}; + auto* const box = itemNamed(*f.item(), QStringLiteral("selectAll")); + REQUIRE(box != nullptr); + f.scene.click(*box); + REQUIRE_FALSE(f.ranges.empty()); + CHECK(f.ranges.back() == std::tuple{std::size_t{0}, std::size_t{99'999}, ui::SelectionChange::Extend}); +} + +// Mutation: Shift with an arrow over a source handled by the realized rows (no range reaches the mount). +TEST_CASE("qt_quick table window: Shift with an arrow and Ctrl+A select through the mount", "[qt_quick]") { + QuickWindowFixture f{100'000, 30, {.selection = ui::SelectionMode::Multiple}}; + f.item()->forceActiveFocus(); + f.scene.key(Qt::Key_Down); + f.scene.key(Qt::Key_Down, Qt::ShiftModifier); + f.scene.key(Qt::Key_Down, Qt::ShiftModifier); + REQUIRE_FALSE(f.ranges.empty()); + CHECK(f.ranges.back() == std::tuple{std::size_t{1}, std::size_t{3}, ui::SelectionChange::Replace}); + f.scene.key(Qt::Key_A, Qt::ControlModifier); + CHECK(f.ranges.back() == std::tuple{std::size_t{0}, std::size_t{99'999}, ui::SelectionChange::Extend}); +} + +// Mutation: `TableImpl::setOnSelectAll` not writing `selectAllHandled` (Ctrl+A and the box fire a range, and the +// handler is never called). +TEST_CASE("qt_quick table window: a select-all handler takes Ctrl+A and the select-all box over a source", + "[qt_quick]") { + QuickWindowFixture f{ + 100'000, 30, {.selection = ui::SelectionMode::Multiple, .selectColumn = true, .selectAllHandler = true}}; + CHECK(f.prop("selectAllHandled").toBool()); + f.item()->forceActiveFocus(); + f.scene.key(Qt::Key_A, Qt::ControlModifier); + CHECK(f.selectAlls == 1); + auto* const box = itemNamed(*f.item(), QStringLiteral("selectAll")); + REQUIRE(box != nullptr); + f.scene.click(*box); + CHECK(f.selectAlls == 2); + CHECK(f.ranges.empty()); +} + +// Control: leave the menu popup without the focus (the arrows and Enter go to the header, and Escape does not close +// it). +TEST_CASE("qt_quick table: a header menu opened from the keyboard takes the arrows, Enter and Escape", + "[qt_quick][table]") { + Scene scene; + Rows table = makeTable(scene, {ui::Key{std::int64_t{1}}}, ui::SelectionMode::None); + table.table->setColumns({{.label = "Name", .width = ui::Sizing::fixed(12)}, {.label = "Mass"}}); + std::vector, std::vector>> chosen; + table.table->setMenu( + [](std::optional) { + return std::vector{ + {.label = "Sort ascending"}, {.separator = true}, {.label = "Hide column"}}; + }, + [&chosen](std::optional column, std::vector path) { + chosen.emplace_back(column, std::move(path)); + }); + scene.settle(); + QQuickItem& name = headerOf(*table.table, 0); + auto* const menu = Scene::itemOf(*table.table).findChild(QStringLiteral("configMenu")); + REQUIRE(menu != nullptr); + name.forceActiveFocus(); + scene.key(Qt::Key_F10, Qt::ShiftModifier); + REQUIRE(menu->property("opened").toBool()); + // Down passes over the separator to Hide column; Enter chooses it. + scene.key(Qt::Key_Down); + scene.key(Qt::Key_Return); + CHECK_FALSE(menu->property("opened").toBool()); + REQUIRE(chosen.size() == 1); + CHECK(chosen.front().first == std::optional{0}); + CHECK(chosen.front().second == std::vector{2}); + CHECK(name.hasActiveFocus()); + // Opened with the mouse, Escape closes it and chooses nothing. + QTest::mouseClick(&scene.window(), Qt::RightButton, {}, Scene::centreOf(name)); + scene.settle(); + REQUIRE(menu->property("opened").toBool()); + scene.key(Qt::Key_Escape); + CHECK_FALSE(menu->property("opened").toBool()); + CHECK(chosen.size() == 1); +} + +// Control: draw a menu entry's label alone (the checked entry reads `Wrap`, and assistive technology hears no check). +TEST_CASE("qt_quick table: a header menu shows a checked entry's mark, its chord and its description, and states it", + "[qt_quick][table]") { + Scene scene; + Rows table = makeTable(scene, {ui::Key{std::int64_t{1}}}, ui::SelectionMode::None); + table.table->setColumns({{.label = "Name", .width = ui::Sizing::fixed(12)}, {.label = "Mass"}}); + table.table->setMenu( + [](std::optional) { + return std::vector{ + {.label = "Wrap", .keys = "Ctrl+W", .checked = true, .description = "Long text wraps"}, + {.separator = true}, + {.label = "Pin", .checked = false}}; + }, + [](std::optional, std::vector const&) {}); + scene.settle(); + QQuickItem const& name = headerOf(*table.table, 0); + QTest::mouseClick(&scene.window(), Qt::RightButton, {}, Scene::centreOf(name)); + scene.settle(); + auto* const menu = Scene::itemOf(*table.table).findChild(QStringLiteral("configMenu")); + REQUIRE(menu != nullptr); + REQUIRE(menu->property("opened").toBool()); + auto* const entries = menu->property("contentItem").value(); + REQUIRE(entries != nullptr); + QQuickItem* wrap = nullptr; + QQuickItem* pin = nullptr; + QStringList texts; + QList pending{entries}; + while (!pending.isEmpty()) { + QQuickItem* const item = pending.takeLast(); + if (item->objectName() == QStringLiteral("menuEntry0")) { + wrap = item; + } else if (item->objectName() == QStringLiteral("menuEntry2")) { + pin = item; + } + if (item->isVisible() && !item->property("text").toString().isEmpty()) { + texts.append(item->property("text").toString()); + } + pending.append(item->childItems()); + } + REQUIRE(wrap != nullptr); + REQUIRE(pin != nullptr); + CHECK(wrap->property("text").toString() == QStringLiteral("\u2713 Wrap Ctrl+W")); + CHECK(pin->property("text").toString() == QStringLiteral(" Pin")); + CHECK(texts.contains(QStringLiteral("Long text wraps"))); + bool const wasActive = QAccessible::isActive(); + QAccessible::setActive(true); + QAccessibleInterface const* const wrapNode = QAccessible::queryAccessibleInterface(wrap); + QAccessibleInterface const* const pinNode = QAccessible::queryAccessibleInterface(pin); + REQUIRE(wrapNode != nullptr); + REQUIRE(pinNode != nullptr); + CHECK(wrapNode->role() == QAccessible::MenuItem); + CHECK(wrapNode->state().checkable); + CHECK(wrapNode->state().checked); + CHECK(pinNode->state().checkable); + CHECK_FALSE(pinNode->state().checked); + QAccessible::setActive(wasActive); + scene.key(Qt::Key_Escape); +} + +// Mutation: the menu opened without moving focus (the cell menu's entries not focusing the cell, so the focused row +// stays -1). +TEST_CASE("qt_quick table: a right-click opens the cell menu on that cell and selects its row alone", + "[qt_quick][table]") { + QuickWindowOptions options{.selection = ui::SelectionMode::Multiple}; + options.cellMenu = [](ui::Key const&, std::size_t) { + std::vector items(2); + items.at(0).label = std::string{"Open"}; + items.at(1).label = std::string{"Close"}; + return items; + }; + QuickWindowFixture f{10, 3, std::move(options)}; + f.selected.set({ui::Key{std::int64_t{1}}, ui::Key{std::int64_t{3}}}); + f.settle(); + QQmlExpression find{f.scene.engine().rootContext(), f.item(), QStringLiteral(R"((() => { + const row = realizedRow(2) + if (!row) + return null + for (let i = 0; i < row.content.children.length; ++i) { + const cell = row.content.children[i] + if (cell.measuredIndex === 1 && cell.visible) + return cell + } + return null + })())")}; + auto* const cell = qobject_cast(find.evaluate().value()); + REQUIRE_FALSE(find.hasError()); + REQUIRE(cell != nullptr); + QTest::mouseClick(&f.scene.window(), Qt::RightButton, {}, Scene::centreOf(*cell)); + f.settle(); + REQUIRE_FALSE(f.selections.empty()); + CHECK(f.selections.back() == + std::pair{std::vector{ui::Key{std::int64_t{2}}}, ui::SelectionChange::Replace}); + CHECK(f.call("focusedRow").toInt() == 2); + CHECK(f.call("focusedColumn").toInt() == 1); + auto* const menu = f.item()->findChild(QStringLiteral("configMenu")); + REQUIRE(menu != nullptr); + REQUIRE(menu->property("opened").toBool()); + auto const labels = [menu] { + QStringList out; + for (QVariant const& entry : menu->property("entries").toList()) { + out.append(entry.toMap().value(QStringLiteral("label")).toString()); + } + return out; + }; + QStringList const expected{QStringLiteral("Open"), QStringLiteral("Close")}; + CHECK(labels() == expected); + f.scene.key(Qt::Key_Escape); + f.settle(); + REQUIRE_FALSE(menu->property("opened").toBool()); + // The focus is back on the table, and the menu key on the focused cell opens the same menu. + CHECK(f.item()->hasActiveFocus()); + f.scene.key(Qt::Key_Menu); + f.settle(); + CHECK(menu->property("opened").toBool()); + CHECK(labels() == expected); + f.scene.key(Qt::Key_Escape); +} + +// Written by reading: this tree's Qt Quick build was not configured, so these two cases were not compiled or run. +// Mutation: `setOnSelectAll` ignored, under which Ctrl+A reports the five keys through `onSelectionChange`. +TEST_CASE("qt_quick table: select-all asks the handler and marks the view", "[qt_quick]") { + Scene scene; + std::vector keys; + for (std::int64_t id = 1; id <= 5; ++id) { + keys.emplace_back(id); + } + Rows table = makeTable(scene, keys, ui::SelectionMode::Multiple); + table.table->setSelectColumn(true); + scene.settle(); + int asked = 0; + std::vector, ui::SelectionChange>> reported; + table.table->setOnSelectAll([&asked] { ++asked; }); + table.table->setOnSelectionChange([&reported](std::vector chosen, ui::SelectionChange change) { + reported.emplace_back(std::move(chosen), change); + }); + scene.key(Qt::Key_Tab); + scene.key(Qt::Key_A, Qt::ControlModifier); + CHECK(asked == 1); + scene.click(selectAllOf(*table.table)); + CHECK(asked == 2); + CHECK(reported.empty()); + + table.table->setSelectionView({ui::Key{std::int64_t{2}}}); + scene.settle(); + for (std::size_t at = 0; at < table.rows.size(); ++at) { + CHECK(Scene::itemOf(*table.rows.at(at)).property("selected").toBool() == (at != 1)); + } + scene.click(Scene::itemOf(*table.rows.at(0)), Qt::ControlModifier); + REQUIRE(reported.size() == 1); + CHECK(reported.back().second == ui::SelectionChange::Extend); + CHECK(reported.back().first == + std::vector{ui::Key{std::int64_t{3}}, ui::Key{std::int64_t{4}}, ui::Key{std::int64_t{5}}}); + table.table->setSelection({}); + scene.settle(); + for (auto const& row : table.rows) { + CHECK_FALSE(Scene::itemOf(*row).property("selected").toBool()); + } +} + +// Mutation: the entries drawn as plain text, under which the click reports nothing. +TEST_CASE("qt_quick table: a status entry reports its id", "[qt_quick]") { + Scene scene; + Rows table = makeTable(scene, {ui::Key{std::int64_t{1}}}, ui::SelectionMode::Multiple); + std::vector chosen; + table.table->setOnStatusEntry([&chosen](std::string id) { chosen.push_back(std::move(id)); }); + table.table->setStatus(ui::TableStatus{ + .message = "m", + .entries = {{.id = "run", .label = "Run on these"}}, + .standing = "1 row could not be saved", + .standingEntries = {{.id = "select", .label = "Select them"}, {.id = "clear", .label = "Clear marks"}}, + .shown = true}); + scene.settle(); + QQuickItem& item = Scene::itemOf(*table.table); + for (auto const& [id, label] : + std::vector>{{QStringLiteral("run"), QStringLiteral("Run on these")}, + {QStringLiteral("select"), QStringLiteral("Select them")}, + {QStringLiteral("clear"), QStringLiteral("Clear marks")}}) { + auto const* const button = itemNamed(item, QStringLiteral("statusEntry_") + id); + REQUIRE(button != nullptr); + CHECK(button->property("text").toString() == label); + } + scene.click(*itemNamed(item, QStringLiteral("statusEntry_clear"))); + CHECK(chosen == std::vector{"clear"}); +} + +namespace { + +// A grid of two specimens (`morph::test::grid::kSpecimens`) between two text inputs, `before` and `after`, on Qt +// Quick. Its columns are every member in schema order: label 0, mass 1, volume 2, density 3, limit 4, note 5. +struct QuickGrid { + QuickGrid() { + form = std::make_unique( + scene.runtime(), morph::test::formsengine::modelOf("Lims_RecordSpecimens", morph::test::grid::kSpecimens), + server.submitter(), server.fetcher(), + morph::forms::FormSessionOptions{.locale = ui::localeFacts("de").numeric, .bcp47 = "de"}); + form->prefill(R"({"sampleId":1,"specimens":[{},{}]})"); + std::vector columns; + for (morph::forms::FieldSpec const& member : form->field("specimens").spec().children) { + columns.push_back( + ui::GridColumn{.id = member.name, .label = member.name, .field = member.name, .value = {}}); + } + ui::TableOptions table; + table.common.testId = "grid"; + grid = ui::makeFormGrid(*form, form->field("specimens"), std::move(columns), {}, ui::formatOf(*form), + std::move(table)); + ui::TextInput before; + before.common.testId = "before"; + ui::TextInput after; + after.common.testId = "after"; + view.emplace(scene.runtime(), scene.backend(), + ui::column(ui::Column{ + .children = {ui::textInput(std::move(before)), grid.node, ui::textInput(std::move(after))}})); + scene.settle(); + } + QuickGrid(QuickGrid const&) = delete; + QuickGrid& operator=(QuickGrid const&) = delete; + QuickGrid(QuickGrid&&) = delete; + QuickGrid& operator=(QuickGrid&&) = delete; + ~QuickGrid() { + view.reset(); + grid = {}; + } + + [[nodiscard]] QQuickItem& named(QString const& name) { + QQuickItem* const found = itemNamed(*scene.window().contentItem(), name); + REQUIRE(found != nullptr); + return *found; + } + + // The row item of view row @p viewRow. + [[nodiscard]] QQuickItem& rowAt(int viewRow) { + for (QQuickItem* const row : Scene::itemsOf(named(QStringLiteral("grid")), "QQuickItem")) { + if (row->property("viewRow").toInt() == viewRow && row->property("cellMarks").isValid()) { + return *row; + } + } + FAIL("no row at " << viewRow); + throw std::logic_error{"unreachable"}; + } + + // The cell of view row @p viewRow in column @p column. + [[nodiscard]] QQuickItem& cellAt(int viewRow, int column) { + for (QQuickItem* const row : Scene::itemsOf(named(QStringLiteral("grid")), "QQuickItem")) { + if (row->property("viewRow").toInt() != viewRow || !row->property("cellMarks").isValid()) { + continue; + } + for (QQuickItem* const cell : Scene::itemsOf(*row, "QQuickItem")) { + if (cell->property("measuredIndex").isValid() && cell->property("measuredIndex").toInt() == column && + cell->isVisible()) { + return *cell; + } + } + } + FAIL("no cell at " << viewRow << ", " << column); + throw std::logic_error{"unreachable"}; + } + + Scene scene; + morph::test::formsengine::FakeServer server{scene.owner()}; + std::unique_ptr form; + ui::FormGrid grid; + std::optional view; +}; + +} // namespace + +// Mutation: the QML cell ignoring setOnText. +TEST_CASE("qt_quick grid: typing on a focused cell opens its editor, Tab walks and leaves", "[qt_quick][grid]") { + QuickGrid g; + g.grid.grid->focusCell(morph::test::grid::at(1, "mass")); + g.scene.settle(); + QQuickItem& table = g.named(QStringLiteral("grid")); + table.forceActiveFocus(); + g.scene.type(QStringLiteral("5")); + CHECK(g.grid.grid->editing() == morph::test::grid::at(1, "mass")); + QList const fields = Scene::itemsOf(table, "QQuickTextField"); + REQUIRE(fields.size() == 1); + CHECK(fields.front()->property("text").toString() == QStringLiteral("5")); + g.scene.key(Qt::Key_Tab); + CHECK(g.form->field("specimens[0].mass").draft() == "5"); + CHECK(g.grid.grid->focus() == morph::test::grid::at(1, "volume")); + g.grid.grid->focusCell(morph::test::grid::at(2, "note")); + g.scene.settle(); + table.forceActiveFocus(); + g.scene.key(Qt::Key_Tab); + QQuickItem const* const focused = g.scene.window().activeFocusItem(); + REQUIRE(focused != nullptr); + CHECK(focused->objectName() == QStringLiteral("after")); +} + +// Mutation: the QML cell sending a double click as two single clicks (no editor opens). +TEST_CASE("qt_quick grid: a double click opens the editor in the cell and focus leaving commits", "[qt_quick][grid]") { + QuickGrid g; + QQuickItem const& cell = g.cellAt(1, 1); + // The cell's slot: its column's span across the row's height. A cell draws only as tall as its text, which a wide + // font leaves shorter than the editor that replaces it. + QRectF const area = + cell.parentItem()->mapRectToScene(QRectF{cell.x(), 0, cell.width(), cell.parentItem()->height()}); + g.scene.doubleClick(cell); + CHECK(g.grid.grid->editing() == morph::test::grid::at(2, "mass")); + QList const fields = Scene::itemsOf(g.named(QStringLiteral("grid")), "QQuickTextField"); + REQUIRE(fields.size() == 1); + QPointF const centre = + fields.front()->mapToScene(QPointF{fields.front()->width() / 2, fields.front()->height() / 2}); + CHECK(area.contains(centre)); + CHECK(fields.front()->hasActiveFocus()); + g.scene.type(QStringLiteral("7")); + g.scene.click(g.named(QStringLiteral("after"))); + CHECK(g.form->field("specimens[1].mass").draft() == "7"); + CHECK(Scene::itemsOf(g.named(QStringLiteral("grid")), "QQuickTextField").empty()); +} + +// Mutation: the column's field resolved once for every row (row 2's editor is a ComboBox too). +TEST_CASE("qt_quick grid: a column's kind follows its row", "[qt_quick][grid]") { + Scene scene; + morph::test::formsengine::FakeServer server{scene.owner()}; + auto form = std::make_unique( + scene.runtime(), morph::test::formsengine::modelOf("Lims_RecordRows", morph::test::grid::kKindPerRow), + server.submitter(), server.fetcher(), + morph::forms::FormSessionOptions{.locale = ui::localeFacts("de").numeric, .bcp47 = "de"}); + form->prefill(R"({"rows":[{"isChoice":true},{"isChoice":false}]})"); + ui::TableOptions options; + options.common.testId = "grid"; + ui::FormGrid grid = ui::makeFormGrid(*form, form->field("rows"), morph::test::grid::kindPerRowColumns(), {}, + ui::formatOf(*form), std::move(options)); + std::optional view; + view.emplace(scene.runtime(), scene.backend(), grid.node); + scene.settle(); + QQuickItem* const table = itemNamed(*scene.window().contentItem(), QStringLiteral("grid")); + REQUIRE(table != nullptr); + grid.grid->activate(morph::test::grid::at(1, "value")); + scene.settle(); + CHECK(Scene::itemsOf(*table, "QQuickComboBox").size() == 1); + CHECK(Scene::itemsOf(*table, "QQuickTextField").empty()); + grid.grid->press("Escape"); + grid.grid->activate(morph::test::grid::at(2, "value")); + scene.settle(); + CHECK(Scene::itemsOf(*table, "QQuickComboBox").empty()); + CHECK(Scene::itemsOf(*table, "QQuickTextField").size() == 1); + view.reset(); + grid = {}; +} + +// Mutation: the QML table reporting the drag as a row selection (the rectangle is not selected and a row is). +TEST_CASE("qt_quick grid: a drag selects a rectangle of cells and a row header click its row", "[qt_quick][grid]") { + QuickGrid g; + QQuickItem& table = g.named(QStringLiteral("grid")); + CHECK(table.property("selectsCells").toBool()); + QPoint const start = Scene::centreOf(g.cellAt(0, 1)); // (1, mass) + QPoint const end = Scene::centreOf(g.cellAt(1, 2)); // (2, volume) + QTest::mousePress(&g.scene.window(), Qt::LeftButton, {}, start); + constexpr int steps = 10; + for (int step = 1; step <= steps; ++step) { + QTest::mouseMove(&g.scene.window(), start + ((end - start) * step / steps)); + } + QTest::mouseRelease(&g.scene.window(), Qt::LeftButton, {}, end); + g.scene.settle(); + CHECK(g.grid.grid->selection() == + ui::CellRange{morph::test::grid::at(1, "mass"), morph::test::grid::at(2, "volume")}); + QVariantList const rect = table.property("cellRect").toList(); + REQUIRE(rect.size() == 4); + CHECK(rect.at(0).toInt() == 0); + CHECK(rect.at(1).toInt() == 2); + CHECK(rect.at(2).toInt() == 1); + CHECK(rect.at(3).toInt() == 2); + QQuickItem const& box = g.named(QStringLiteral("cellSelection")); + CHECK(box.isVisible()); + for (QQuickItem const* const row : Scene::itemsOf(table, "QQuickItem")) { + if (row->property("cellMarks").isValid()) { + CHECK_FALSE(row->property("selected").toBool()); + } + } + // A click on a row's header, the leading strip before its first cell, selects the row's cells. + qreal const lead = table.property("lead").toReal(); + REQUIRE(lead > 0); + QQuickItem const& row = g.rowAt(1); + QPointF const header = row.mapToScene(QPointF{lead / 2, row.height() / 2}); + QTest::mouseClick(&g.scene.window(), Qt::LeftButton, {}, header.toPoint()); + g.scene.settle(); + CHECK(g.grid.grid->selection() == + ui::CellRange{morph::test::grid::at(2, "label"), morph::test::grid::at(2, "note")}); +} + +// Mutation: the header's sort handler taking only a Shift-click in a table that selects cells (the plain click reports +// no sort). +TEST_CASE("qt_quick grid: a header click sorts, a Shift-click adds, a Ctrl-click selects the column", + "[qt_quick][grid]") { + Scene scene; + morph::test::formsengine::FakeServer server{scene.owner()}; + auto form = std::make_unique( + scene.runtime(), morph::test::formsengine::modelOf("Lims_RecordSpecimens", morph::test::grid::kSpecimens), + server.submitter(), server.fetcher(), + morph::forms::FormSessionOptions{.locale = ui::localeFacts("de").numeric, .bcp47 = "de"}); + form->prefill(R"({"sampleId":1,"specimens":[{},{}]})"); + std::vector columns; + std::vector shown; + for (morph::forms::FieldSpec const& member : form->field("specimens").spec().children) { + columns.push_back(ui::GridColumn{.id = member.name, .label = member.name, .field = member.name, .value = {}}); + shown.push_back(ui::TableColumn{.id = member.name, .label = member.name, .sortable = member.name == "mass"}); + } + std::vector> sorts; + ui::TableOptions options; + options.common.testId = "grid"; + options.onSort = [&sorts](std::size_t column, ui::HeaderClick click) { sorts.emplace_back(column, click); }; + ui::FormGrid grid = ui::makeFormGrid(*form, form->field("specimens"), std::move(columns), {}, ui::formatOf(*form), + std::move(options), std::move(shown)); + std::optional view; + view.emplace(scene.runtime(), scene.backend(), grid.node); + scene.settle(); + QQuickItem* const table = itemNamed(*scene.window().contentItem(), QStringLiteral("grid")); + REQUIRE(table != nullptr); + QQuickItem const* const header = itemNamed(*table, QStringLiteral("header1")); // mass + REQUIRE(header != nullptr); + scene.click(*header); + REQUIRE(sorts.size() == 1); + CHECK(sorts.back() == std::pair{std::size_t{1}, ui::HeaderClick::Plain}); + scene.click(*header, Qt::ShiftModifier); + REQUIRE(sorts.size() == 2); + CHECK(sorts.back() == std::pair{std::size_t{1}, ui::HeaderClick::Shift}); + scene.click(*header, Qt::ControlModifier); + CHECK(sorts.size() == 2); // a Ctrl-click sorts nothing + CHECK(grid.grid->selection() == ui::CellRange{morph::test::grid::at(1, "mass"), morph::test::grid::at(2, "mass")}); + view.reset(); + grid = {}; +} + +// Mutation: the QML band item placed from its first run's x to its last run's end (one item, as wide as columns 1 to +// 4). +TEST_CASE("qt_quick table: a band draws over each run of its columns", "[qt_quick][bands]") { + Scene scene; + Rows table = makeTable(scene, {ui::Key{std::int64_t{1}}}, ui::SelectionMode::None); + table.table->setColumns({{.label = "Name", .width = ui::Sizing::fixed(8)}, + {.label = "M8", .width = ui::Sizing::fixed(8)}, + {.label = "M2", .width = ui::Sizing::fixed(8)}, + {.label = "Total", .width = ui::Sizing::fixed(8)}, + {.label = "M4", .width = ui::Sizing::fixed(8)}}); + table.table->setBands( + {{.level = 0, .label = "Mass retained", .unit = "g", .first = 1, .count = 2, .pinned = false}, + {.level = 0, .label = "Mass retained", .unit = "g", .first = 4, .count = 1, .pinned = false}}); + scene.settle(); + QQuickItem& tableItem = Scene::itemOf(*table.table); + auto* const first = itemNamed(tableItem, QStringLiteral("band0")); + auto* const second = itemNamed(tableItem, QStringLiteral("band1")); + REQUIRE(first != nullptr); + REQUIRE(second != nullptr); + QQuickItem const& m8 = headerOf(*table.table, 1); + QQuickItem const& m2 = headerOf(*table.table, 2); + QQuickItem const& m4 = headerOf(*table.table, 4); + auto const left = [&first](QQuickItem const& item) { return item.mapToItem(first->parentItem(), QPointF{}).x(); }; + CHECK(first->x() == Catch::Approx(left(m8))); + CHECK(first->x() + first->width() == Catch::Approx(left(m2) + m2.width())); + CHECK(second->x() == Catch::Approx(left(m4))); + CHECK(second->width() == Catch::Approx(m4.width())); +} + +// Mutation: `setRowSummary` writing nothing (the row's summary surface stays hidden). +TEST_CASE("qt_quick table: a summary row is drawn on the summary surface", "[qt_quick][summary]") { + Scene scene; + Rows table = makeTable(scene, {ui::Key{std::int64_t{1}}, ui::Key{std::int64_t{2}}}, ui::SelectionMode::Single); + table.table->setRowSummary(*table.rows.at(1)); + scene.settle(); + auto const fill = [](ui::Widget& row) { + return Scene::itemOf(row).findChild(QStringLiteral("summaryFill")); + }; + REQUIRE(fill(*table.rows.at(1)) != nullptr); + CHECK(fill(*table.rows.at(1))->isVisible()); + CHECK_FALSE(fill(*table.rows.at(0))->isVisible()); +} diff --git a/tests/qt_quick/test_qt_quick_theme.cpp b/tests/qt_quick/test_qt_quick_theme.cpp index 366f78b8c..a7210cf14 100644 --- a/tests/qt_quick/test_qt_quick_theme.cpp +++ b/tests/qt_quick/test_qt_quick_theme.cpp @@ -192,6 +192,41 @@ TEST_CASE("qt_quick theme: a host component reads the same tokens; a missing tok CHECK(item.property("muted").value() == QColor{"#6e6e73"}); } +// Mutation: `Theme.tableLocked` written in the token's byte order (#RRGGBBAA, which QML reads as #AARRGGBB: an +// olive wash at 56 %). +TEST_CASE("qt_quick theme: Theme's table row defaults are the token defaults", "[qt_quick]") { + Scene scene; + auto const* const theme = + scene.engine().singletonInstance(QStringLiteral("MorphUi"), QStringLiteral("Theme")); + REQUIRE(theme != nullptr); + ui::ThemeValues const defaults = ui::themeValues(); + for (auto const& [path, property] : + {std::pair{"color.table.busy", "tableBusy"}, std::pair{"color.table.locked", "tableLocked"}}) { + INFO(path); + ui::Rgba const& token = defaults.colors.at(path); + CHECK(theme->property(property).value() == QColor{token.r, token.g, token.b, token.a}); + } + CHECK(theme->property("mutedOpacity").toDouble() == defaults.numbers.at("opacity.muted")); +} + +// Mutation: `opacity.muted` left out of applyTheme (Theme keeps 0.55), or either table colour left out of +// kColorProperties (Theme keeps its default). +TEST_CASE("qt_quick theme: a table row's busy, locked and muted tokens reach Theme", "[qt_quick]") { + Scene scene; + auto const tokens = ui::parseTokens(R"({"color": {"table": {"$type": "color", "busy": {"$value": "#123456"}, + "locked": {"$value": "#65432180"}}}, "opacity": {"muted": {"$type": "number", "$value": 0.4}}})"); + REQUIRE(tokens); + auto const resolved = ui::resolveTokens({&*tokens}); + REQUIRE(resolved); + REQUIRE(morph::qt_quick::applyTheme(scene.engine(), ui::themeValues(*resolved)).empty()); + auto const* const theme = + scene.engine().singletonInstance(QStringLiteral("MorphUi"), QStringLiteral("Theme")); + REQUIRE(theme != nullptr); + CHECK(theme->property("tableBusy").value() == QColor{"#123456"}); + CHECK(theme->property("tableLocked").value() == QColor::fromRgb(0x65, 0x43, 0x21, 0x80)); + CHECK(theme->property("mutedOpacity").toDouble() == 0.4); +} + TEST_CASE("qt_quick theme: the shell's tokens reach Theme", "[qt_quick]") { Scene scene; auto const tokens = ui::parseTokens(R"({"color": {"background": {"$type": "color", "$value": "#101010"}}, diff --git a/tests/qt_quick/wasm/CMakeLists.txt b/tests/qt_quick/wasm/CMakeLists.txt new file mode 100644 index 000000000..b38fb2a0b --- /dev/null +++ b/tests/qt_quick/wasm/CMakeLists.txt @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# B5 and U8 (docs/spec/table/table.md, "Benchmarks"): the Qt for WebAssembly build of the frontend baseline, run +# by hand in a headless browser with emrun. No ctest test: its result is what it prints to the console. + +qt_add_executable(wide_rows_baseline wide_rows_baseline.cpp) +target_link_libraries(wide_rows_baseline PRIVATE morph::qt_quick morph_wide_table_model) +target_include_directories(wide_rows_baseline PRIVATE ${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/tests) +target_link_options(wide_rows_baseline PRIVATE -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=4GB) +apply_warnings(wide_rows_baseline) + +# U8 (docs/spec/table/table.md, "Benchmarks: every surface"): the interpreter's sort and the column window's scrolls in +# the browser, over a `rows` table of 20,000 and a model-backed table of 100,000 x 300. The fixture's registrations are +# linked whole, as the native executables link them, so the model is found by its type id. +qt_add_executable(u8_scrolls u8_scrolls.cpp) +target_link_libraries(u8_scrolls PRIVATE morph::qt_quick "$") +target_include_directories(u8_scrolls PRIVATE ${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/tests) +target_link_options(u8_scrolls PRIVATE -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=4GB) +apply_warnings(u8_scrolls) diff --git a/tests/qt_quick/wasm/u8_scrolls.cpp b/tests/qt_quick/wasm/u8_scrolls.cpp new file mode 100644 index 000000000..147de7e31 --- /dev/null +++ b/tests/qt_quick/wasm/u8_scrolls.cpp @@ -0,0 +1,772 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// U8 (docs/spec/table/table.md, "Benchmarks: every surface"): the interpreter and the Qt Quick column window in the +// WebAssembly build, in a browser. Two tables are mounted in one 1,280 x 800 window, one after the other. +// +// 1. A `rows` table of 20,000 rows over document state (U1, U2, F3): +// U1 a header click on the text column `name`, to the first frame that shows the sorted rows +// U2 one row's name replaced in the state, to the first frame that shows it +// then the vertical scrolls of F3. +// 2. A model-backed table of 100,000 x 300 over an in-process `bench::WideTableModel`, through a `Bridge` on a +// `LocalBackend` (F3 and F4: the vertical and the horizontal scrolls, windowed in both directions). +// +// Output, one line each, on the console: +// +// mounted table= rows= realized= columns= ms=